メインコンテンツまでスキップ

回答とコンテキスト、関連性、ジャッジとスコアラー

judges.is_context_relevant()定義済みのジャッジは、RAG システムによって取得されたコンテキスト、またはツール呼び出しによって生成されたコンテキストがユーザーの要求に関連しているかどうかを評価します。これは品質の問題を診断するために非常に重要であり、コンテキストが関連しない場合、生成ステップは有用な応答を生成できません。

このジャッジは、次の 2 つの事前定義されたスコアラーを通じて利用できます。

  • RelevanceToQuery : アプリのレスポンスがユーザーの入力に直接対応しているかどうかを評価します
  • RetrievalRelevance : アプリのレトリーバーから返された各ドキュメントが関連しているかどうかを評価します

API シグネチャ

詳細については、 mlflow.genai.judges.is_context_relevant()を参照してください。

Python
from mlflow.genai.judges import is_context_relevant

def is_context_relevant(
*,
request: str, # User's question or query
context: Any, # Context to evaluate for relevance, can be any Python primitive or a JSON-seralizable dict
name: Optional[str] = None, # Optional custom name for display in the MLflow UIs
model: Optional[str] = None, # Optional LiteLLM compatible custom judge model
) -> mlflow.entities.Feedback:
"""Returns Feedback with 'yes' or 'no' value and a rationale"""

デフォルトでは、この審査員は、GenAI 品質評価を実行するために特別に調整された、Databricks がホストする LLM モデルを使用します。スコアラー定義のモデル引数を使用して、審査員モデルを変更できます。モデルは<provider>:/<model-name>形式で指定する必要があります。プロバイダーは LiteLLM 互換のモデル プロバイダーです。モデル プロバイダーとしてdatabricksを使用する場合、モデル名はサービス エンドポイント名と同じになります。

例を実行するための前提条件

  1. MLflow と必要なパッケージをインストールする

    Bash
    pip install --upgrade "mlflow[databricks]>=3.4.0" openai "databricks-connect>=16.1"
  2. MLflow エクスペリメントを作成するには、環境のセットアップに関するクイックスタートに従ってください。

SDKの直接使用

Python
from mlflow.genai.judges import is_context_relevant

# Example 1: Relevant context
feedback = is_context_relevant(
request="What is the capital of France?",
context="Paris is the capital of France."
)
print(feedback.value) # "yes"
print(feedback.rationale) # Explanation of relevance

# Example 2: Irrelevant context
feedback = is_context_relevant(
request="What is the capital of France?",
context="Paris is known for its Eiffel Tower."
)
print(feedback.value) # "no"
print(feedback.rationale) # Explanation of why it's not relevant

# Example 3: Custom judge model
feedback = is_context_relevant(
request="What is the capital of France?",
context="Paris is known for its Eiffel Tower.",
model="databricks:/databricks-gpt-oss-120b",
)

事前構築済みのスコアラーを使用する

is_context_relevantジャッジは、2 つの事前構築済みスコアラーから利用できます。

1. RelevanceToQuery スコアラー

このスコアラーは、アプリのレスポンスが、無関係なトピックに逸脱することなく、ユーザーの入力に直接対処しているかどうかを評価します。

要件:

  • トレース要件 : inputsoutputs はトレースのルート スパン上にある必要があります
Python
from mlflow.genai.scorers import RelevanceToQuery

eval_dataset = [
{
"inputs": {"query": "What is the capital of France?"},
"outputs": {
"response": "Paris is the capital of France. It's known for the Eiffel Tower and is a major European city."
},
},
{
"inputs": {"query": "What is the capital of France?"},
"outputs": {
"response": "France is a beautiful country with great wine and cuisine."
},
}
]

# Run evaluation with RelevanceToQuery scorer
eval_results = mlflow.genai.evaluate(
data=eval_dataset,
scorers=[
RelevanceToQuery(
model="databricks:/databricks-gpt-oss-120b", # Optional. Defaults to custom Databricks model.
)
],
)

2. RetrievalRelevance スコアラー

このスコアラーは、アプリの取得者によって返された各ドキュメントが入力リクエストに関連しているかどうかを評価します。

要件:

  • トレース要件 : MLflow トレースには、 span_type が 1 に設定されたスパンが少なくとも 1 つ含まれている必要があります。 RETRIEVER
Python
import mlflow
from mlflow.genai.scorers import RetrievalRelevance
from mlflow.entities import Document
from typing import List

# Define a retriever function with proper span type
@mlflow.trace(span_type="RETRIEVER")
def retrieve_docs(query: str) -> List[Document]:
# Simulated retrieval - in practice, this would query a vector database
if "capital" in query.lower() and "france" in query.lower():
return [
Document(
id="doc_1",
page_content="Paris is the capital of France.",
metadata={"source": "geography.txt"}
),
Document(
id="doc_2",
page_content="The Eiffel Tower is located in Paris.",
metadata={"source": "landmarks.txt"}
)
]
else:
return [
Document(
id="doc_3",
page_content="Python is a programming language.",
metadata={"source": "tech.txt"}
)
]

# Define your app that uses the retriever
@mlflow.trace
def rag_app(query: str):
docs = retrieve_docs(query)
# In practice, you would pass these docs to an LLM
return {"response": f"Found {len(docs)} relevant documents."}

# Create evaluation dataset
eval_dataset = [
{
"inputs": {"query": "What is the capital of France?"}
},
{
"inputs": {"query": "How do I use Python?"}
}
]

# Run evaluation with RetrievalRelevance scorer
eval_results = mlflow.genai.evaluate(
data=eval_dataset,
predict_fn=rag_app,
scorers=[
RetrievalRelevance(
model="databricks:/databricks-gpt-oss-120b", # Optional. Defaults to custom Databricks model.
)
]
)

カスタムスコアラーでの使用

事前定義されたスコアラー の要件 とは異なるデータ構造を持つアプリケーションを評価する場合は、ジャッジをカスタムスコアラーで包みます。

Python
from mlflow.genai.judges import is_context_relevant
from mlflow.genai.scorers import scorer
from typing import Dict, Any

eval_dataset = [
{
"inputs": {"query": "What are MLflow's main components?"},
"outputs": {
"retrieved_context": [
{"content": "MLflow has four main components: Tracking, Projects, Models, and Registry."}
]
}
},
{
"inputs": {"query": "What are MLflow's main components?"},
"outputs": {
"retrieved_context": [
{"content": "Python is a popular programming language."}
]
}
}
]

@scorer
def context_relevance_scorer(inputs: Dict[Any, Any], outputs: Dict[Any, Any]):
# Extract first context chunk for evaluation
context = outputs["retrieved_context"]
return is_context_relevant(
request=inputs["query"],
context=context
)

# Run evaluation
eval_results = mlflow.genai.evaluate(
data=eval_dataset,
scorers=[context_relevance_scorer]
)

結果の解釈

ジャッジは、次の Feedback オブジェクトを返します。

  • value : 文脈が適切であれば「はい」、そうでない場合は「いいえ」
  • rationale :コンテキストが関連性があるか無関係であると見なされた理由の説明

次のステップ