GenAI アプリケーションを改善する最も効果的な方法の 1 つは、ドメインエキスパートに既存のトレースのレビューとラベル付けをしてもらう方法です。 MLflow のレビュー アプリは、アプリケーションとの実際の相互作用に関するこの専門家のフィードバックを収集するための構造化されたプロセスを提供します。
[前提条件]
- 開発環境は、GenAI アプリケーション トレースがログに記録される MLflow 実験 に接続されています。
- トレースの クイックスタート に従って、開発環境を接続します。
- ドメインエキスパートは、MLflow 実験を含む Databricks ワークスペースにアクセスできる必要があります。
注
このガイドで説明する機能には、MLflow バージョン 3.1.0 以降が必要です。
次のコマンドを実行して、Databricks 統合に必要な追加機能を含め、MLflow SDK をインストールまたはアップグレードします。
pip install --upgrade "mlflow[databricks]>=3.1.0"
概要
手順 1: トレースを使用してアプリを作成する
フィードバックを収集するには、GenAI アプリケーションからトレースをログに記録しておく必要があります。 これらのトレースは、アプリケーションの実行の入力、出力、中間ステップ (ツール呼び出しや取得アクションなど) をキャプチャします。
トレースをログに記録する方法の例を次に示します。 この例には偽の取得機能が含まれているため、トレース内で取得されたドキュメントがレビュー アプリでどのようにレンダリングされるかを示すことができます。 レビュー アプリによるトレースのレンダリング方法の詳細については、アプリのレビューの概要を参照してください。
import os
import mlflow
from openai import OpenAI
from mlflow.entities import Document
from typing import List, Dict
# Enable auto instrumentation for OpenAI SDK
mlflow.openai.autolog()
# Connect to a Databricks LLM via OpenAI using the same credentials as MLflow
# Alternatively, you can use your own OpenAI credentials here
mlflow_creds = mlflow.utils.databricks_utils.get_databricks_host_creds()
client = OpenAI(
api_key=mlflow_creds.token,
base_url=f"{mlflow_creds.host}/serving-endpoints"
)
# Spans of type RETRIEVER are rendered in the Review App as documents.
@mlflow.trace(span_type="RETRIEVER")
def retrieve_docs(query: str) -> List[Document]:
normalized_query = query.lower()
if "john doe" in normalized_query:
return [
Document(
id="conversation_123",
page_content="John Doe mentioned issues with login on July 10th. Expressed interest in feature X.",
metadata={"doc_uri": "http://domain.com/conversations/123"},
),
Document(
id="conversation_124",
page_content="Follow-up call with John Doe on July 12th. Login issue resolved. Discussed pricing for feature X.",
metadata={"doc_uri": "http://domain.com/conversations/124"},
),
]
else:
return [
Document(
id="ticket_987",
page_content="Acme Corp raised a critical P0 bug regarding their main dashboard on July 15th.",
metadata={"doc_uri": "http://domain.com/tickets/987"},
)
]
# Sample app that we will review traces from
@mlflow.trace
def my_app(messages: List[Dict[str, str]]):
# 1. Retrieve conversations based on the last user message
last_user_message_content = messages[-1]["content"]
retrieved_documents = retrieve_docs(query=last_user_message_content)
retrieved_docs_text = "\n".join([doc.page_content for doc in retrieved_documents])
# 2. Prepare messages for the LLM
messages_for_llm = [
{"role": "system", "content": "You are a helpful assistant!"},
{
"role": "user",
"content": f"Additional retrieved context:\n{retrieved_docs_text}\n\nNow, please provide the one-paragraph summary based on the user's request {last_user_message_content} and this retrieved context.",
},
]
# 3. Call LLM to generate the summary
return client.chat.completions.create(
model="databricks-claude-3-7-sonnet", # This example uses Databricks hosted Claude-3-7-Sonnet. If you provide your own OpenAI credentials, replace with a valid OpenAI model e.g., gpt-4o, etc.
messages=messages_for_llm,
)
手順 2: ラベル付けスキーマを定義する
ラベル付けスキーマでは、ドメイン エキスパートがトレースに関するフィードバックを提供するために使用する質問と入力の種類を定義します。 MLflow の組み込みスキーマを使用することも、特定の評価基準に合わせてカスタマイズしたカスタム スキーマを作成することもできます。
ラベル付けスキーマには、主に次の 2 種類があります。
-
期待値の種類 (
type="expectation"
): 専門家が "地上の真実" または正しい回答を提供するときに使用されます。 たとえば、RAG システムの応答のexpected_facts
を指定します。 多くの場合、これらのラベルは評価データセットで直接使用できます。 -
フィードバックの種類 (
type="feedback"
):主観的な評価、評価、または分類に使用されます。 たとえば、応答を 1 から 5 のスケールで評価して丁寧に評価したり、応答が特定の条件を満たしているかどうかを分類したりします。
カテゴリの選択肢 (ラジオ ボタン)、数値スケール、自由形式のテキストなど、スキーマのさまざまな入力方法を理解するには、 スキーマのラベル付けのドキュメントを 参照してください。
from mlflow.genai.label_schemas import create_label_schema, InputCategorical, InputText
# Collect feedback on the summary
summary_quality = create_label_schema(
name="summary_quality",
type="feedback",
title="Is this summary concise and helpful?",
input=InputCategorical(options=["Yes", "No"]),
instruction="Please provide a rationale below.",
enable_comment=True,
overwrite=True,
)
# Collect a ground truth summary
expected_summary = create_label_schema(
name="expected_summary",
type="expectation",
title="Please provide the correct summary for the user's request.",
input=InputText(),
overwrite=True,
)
手順 3: ラベル付けセッションを作成する
ラベル付けセッションは、特別な種類の MLflow Run で、選択したラベル付けスキーマを使用して、特定のエキスパートによるレビュー用のトレースのセットを整理します。 レビュー プロセスのキューとして機能します。
詳細については、 ラベル付けセッションのドキュメント を参照してください。
ラベル付けセッションを作成する方法を次に示します。
from mlflow.genai.labeling import create_labeling_session
# Create the Labeling Session with the schemas we created in the previous step
label_summaries = create_labeling_session(
name="label_summaries",
assigned_users=[],
label_schemas=[summary_quality.name, expected_summary.name],
)
手順 4: トレースを生成し、ラベル付けセッションに追加する
ラベル付けセッションが作成されたら、トレースを追加する必要があります。 トレースはラベル付けセッションにコピーされるため、レビュー プロセス中に行われたラベルや変更は、元のログに記録されたトレースには影響しません。
任意のトレースを MLflow 実験に追加できます。 詳細については、 ラベル付けセッションのドキュメント を参照してください。
注
トレースが生成されたら、[トレース] タブでトレースを選択し、[トレースの エクスポート] をクリックして、上で作成したラベル付けセッションを選択して、トレースをラベル付けセッションに追加することもできます。
import mlflow
# Use verison tracking to be able to easily query for the traces
tracked_model = mlflow.set_active_model(name="my_app")
# Run the app to generate traces
sample_messages_1 = [
{"role": "user", "content": "what issues does john doe have?"},
]
summary1_output = my_app(sample_messages_1)
sample_messages_2 = [
{"role": "user", "content": "what issues does acme corp have?"},
]
summary2_output = my_app(sample_messages_2)
# Query for the traces we just generated
traces = mlflow.search_traces(model_id=tracked_model.model_id)
# Add the traces to the session
label_summaries.add_traces(traces)
# Print the URL to share with your domain experts
print(f"Share this Review App with your team: {label_summaries.url}")
手順 5: レビュー アプリをエキスパートと共有する
ラベル付けセッションにトレースが設定されたら、その URL をドメイン エキスパートと共有できます。 この URL を使用すると、レビュー アプリにアクセスしたり、割り当てられているトレースを表示したり (割り当てられていないトレースから選択したり)、構成したラベル付けスキーマを使用してフィードバックを提供したりできます。
Von Bedeutung
ドメインエキスパートは、Databricks ワークスペースへのアクセスと、MLflow 実験に対するWRITE
の権限が必要です。
手順 6: 収集されたラベルを表示して使用する
ドメインエキスパートがレビューを完了すると、収集されたフィードバックがラベル付けセッション内のトレースに添付されます。 これらのラベルをプログラムで取得して分析したり、評価データセットの作成に使用したりできます。
ラベルは、ラベル付けセッション内の各トレースに Assessment
オブジェクトとして格納されます。
MLflow UI を使用する
MLflow SDK を使用する
このコード サンプルでは、ラベル付けセッションの実行からすべてのトレースをフェッチし、簡単に分析できるように評価 (ラベル) を Pandas DataFrame に抽出する方法を示します。
# This is a requirement for a code sample showing:
# Goal: Demonstrate how to retrieve and process collected assessments (labels) from traces within a completed or in-progress labeling session.
# Outline:
# 1. Assume a 'labeling_session' object (from previous steps) is available.
# 2. Get the 'session_id' from the 'labeling_session', which also serves as the MLflow Run ID for that session.
# 3. Use 'mlflow.search_traces(run_id=session_run_id)' to fetch all traces logged within that specific labeling session run.
# 4. Iterate through the retrieved traces (e.g., rows in the DataFrame returned by search_traces).
# 5. For each trace, access its 'assessments'. Assessments are typically stored as a list of dictionaries within a field of the trace object (e.g., often accessible directly as a column if `search_traces` flattens it, or within `trace.info.assessments` if fetching a full trace object).
# - Each assessment dictionary should contain keys like 'name' (the schema name), 'value' (the expert's input), 'comment', 'assessor_id', and 'timestamp'.
# 6. Compile these assessments from all traces into a Pandas DataFrame.
# - The DataFrame should have columns such as: 'request_id', 'assessment_name', 'assessment_value', 'assessment_comment', 'assessor_id', 'timestamp'.
# 7. Print the head of the resulting DataFrame to display some of the collected labels.
# 8. Demonstrate how to filter this DataFrame, for example, to show only assessments related to a specific schema (e.g., 'response_formality_assessment').
次のステップ
評価データセットへの変換
"期待値" 型のラベル (例: この例の expected_summary
) は、 評価データセットの作成に特に役立ちます。 これらのデータセットを mlflow.genai.evaluate()
と共に使用して、GenAI アプリケーションの新しいバージョンを専門家が定義した地上の真実に対して体系的にテストできます。