メタデータとユーザーフィードバックをトレースに追加する
MLflow Tracing により、本番運用アプリは、リクエスト ID、セッション ID とユーザー ID、カスタム タグなどの追加のメタデータとコンテキストでトレースを拡張できます。 アプリは、トレースとともにユーザーフィードバックをログに記録することもできます。このメタデータは、トレースの整理、分析、デバッグに使用できます。
トレースにメタデータを追加する
基本的なトレースが機能したら、メタデータまたはコンテキストをトレースに追加して、 デバッグ と 知見。 本番運用アプリケーションは、デバッグのクライアント要求 ID、マルチターン会話のセッション ID、パーソナライゼーションとアナリティクスのユーザー ID、運用知見の環境メタデータなど、複数のコンテキストを同時に追跡する必要があります。 MLflow には、重要なコンテキスト情報をキャプチャするための次の標準化されたタグと属性があります。
メタデータ | ユースケース | MLflow 属性またはタグ |
|---|---|---|
クライアント要求 ID | トレースを特定のクライアント要求またはAPI呼び出しにリンクして、エンドツーエンドのデバッグを行います | |
ユーザー・セッションID | 複数ターンの会話のトレースをグループ化し、会話フロー全体を分析できるようにします | |
ユーザーID | トレースを特定のユーザーに関連付けて、パーソナライゼーション、コホート分析、ユーザー固有のデバッグを行います | |
環境データ | デプロイメントコンテキスト(環境、バージョン、リージョン)を追跡する 運用上の知見とデバッグ さまざまなデプロイメント | |
カスタムタグ | カスタムメタデータの追加 (特に、トレースの整理、検索、フィルタリング用) | (あなたのタグ) |
以下は、FastAPI アプリケーションでこれらすべてを追跡する方法を示す包括的な例です。
import mlflow
import os
from fastapi import FastAPI, Request, HTTPException # HTTPException might be needed depending on full app logic
from pydantic import BaseModel
# Initialize FastAPI app
app = FastAPI()
class ChatRequest(BaseModel):
message: str
@mlflow.trace # Ensure @mlflow.trace is the outermost decorator
@app.post("/chat") # FastAPI decorator should be inner decorator
def handle_chat(request: Request, chat_request: ChatRequest):
# Retrieve all context from request headers
client_request_id = request.headers.get("X-Request-ID")
session_id = request.headers.get("X-Session-ID")
user_id = request.headers.get("X-User-ID")
# Update the current trace with all context and environment metadata
# The @mlflow.trace decorator ensures an active trace is available
mlflow.update_current_trace(
client_request_id=client_request_id,
metadata={
# Session context - groups traces from multi-turn conversations
"mlflow.trace.session": session_id,
# User context - associates traces with specific users
"mlflow.trace.user": user_id,
# Override automatically populated environment metadata
"mlflow.source.type": os.getenv("APP_ENVIRONMENT", "development"), # Override default LOCAL/NOTEBOOK
# Add customer environment metadata
"environment": "production",
"app_version": os.getenv("APP_VERSION", "1.0.0"),
"deployment_id": os.getenv("DEPLOYMENT_ID", "unknown"),
"region": os.getenv("REGION", "us-east-1"),
# Add custom tags
"my_custom_tag": "custom tag value",
}
)
# --- Your application logic for processing the chat message ---
# For example, calling a language model with context
# response_text = my_llm_call(
# message=chat_request.message,
# session_id=session_id,
# user_id=user_id
# )
response_text = f"Processed message: '{chat_request.message}'"
# --- End of application logic ---
# Return response
return {
"response": response_text
}
# To run this example (requires uvicorn and fastapi):
# uvicorn your_file_name:app --reload
#
# Example curl request with context headers:
# curl -X POST "http://127.0.0.1:8000/chat" \
# -H "Content-Type: application/json" \
# -H "X-Request-ID: req-abc-123-xyz-789" \
# -H "X-Session-ID: session-def-456-uvw-012" \
# -H "X-User-ID: user-jane-doe-12345" \
# -d '{"message": "What is my account balance?"}'
詳細については、 情報 トレースにコンテキストを追加する方法については、以下を参照してください。
- ユーザーとセッションの追跡
- バージョンと環境の追跡
- カスタムタグとメタデータを添付する
- メタデータを追加するための
mlflow.update_current_trace()API - 自動的に入力されたタグと予約済みの標準タグのリストに関するMLflow Tracingドキュメント
ユーザーからのフィードバックを収集する
特定のインタラクションに関するユーザーからのフィードバックを収集することは、品質を理解し、生成AIアプリケーションを改善するために不可欠です。ト レースにメタデータを追加するに示されているクライアントリクエストIDトラッキングに基づいて、以下のFastAPIの例は、次の方法を示しています。
- クライアント要求 ID を使用して正確なトレースを見つけ、フィードバックを添付することで、 フィードバックを特定の対話にリンク します。
log_feedbackとlog_expectationAPIsを使用して構造化フィードバックを格納し、MLflow UI に表示される構造化フィードバック オブジェクトを作成します。
**以下にサンプルコードを示します。
import mlflow
from mlflow.client import MlflowClient
from fastapi import FastAPI, Query, Request
from pydantic import BaseModel
from typing import Optional
from mlflow.entities import AssessmentSource
# Initialize FastAPI app
app = FastAPI()
class FeedbackRequest(BaseModel):
is_correct: bool # True for correct, False for incorrect
comment: Optional[str] = None
@app.post("/chat_feedback")
def handle_chat_feedback(
request: Request,
client_request_id: str = Query(..., description="The client request ID from the original chat request"),
feedback: FeedbackRequest = ...
):
"""
Collect user feedback for a specific chat interaction identified by client_request_id.
"""
# Search for the trace with the matching client_request_id
client = MlflowClient()
# Get the experiment by name (using Databricks workspace path)
experiment = client.get_experiment_by_name("/Shared/production-app")
traces = client.search_traces(
experiment_ids=[experiment.experiment_id],
filter_string=f"attributes.client_request_id = '{client_request_id}'",
max_results=1
)
if not traces:
return {
"status": "error",
"message": f"Unable to find data for client request ID: {client_request_id}"
}, 500
# Log feedback using MLflow's log_feedback API
feedback = mlflow.log_feedback(
trace_id=traces[0].info.trace_id,
name="response_is_correct",
value=feedback.is_correct,
source=AssessmentSource(
source_type="HUMAN",
source_id=request.headers.get("X-User-ID")
),
rationale=feedback.comment
)
return feedback
# Example usage:
# After a chat interaction returns a response, the client can submit feedback:
#
# curl -X POST "http://127.0.0.1:8000/chat_feedback?client_request_id=req-abc-123-xyz-789" \
# -H "Content-Type: application/json" \
# -H "X-User-ID: user-jane-doe-12345" \
# -d '{
# "is_correct": true,
# "comment": "The response was accurate and helpful"
# }'
詳細については、ユーザーフィードバックのログ記録については、以下を参照してください。
- ユーザーからのフィードバックを収集する
- 構造化されたフィードバックを格納するための
mlflow.log_feedback()API とlog_expectationAPI メタデータを使用したトレースのクエリ
トレースにメタデータを追加した後、そのコンテキスト情報を使用して分析できます 本番運用 動作。 具体的には、MLflowClient.search_traces() メソッドでは、タグとメタデータによるフィルタリングが可能です。次の例では、特定のユーザーと特定のユーザー セッションのトレースを検索します。
import mlflow
from mlflow.client import MlflowClient
import pandas as pd
client = MlflowClient()
experiment = client.get_experiment_by_name("/Shared/production-app")
# Query traces by user
user_traces = client.search_traces(
experiment_ids=[experiment.experiment_id],
filter_string="tags.`mlflow.trace.user` = 'user-jane-doe-12345'",
max_results=100
)
# Query traces by session
session_traces = client.search_traces(
experiment_ids=[experiment.experiment_id],
filter_string="tags.`mlflow.trace.session` = 'session-123'",
max_results=100
)
mlflow.search_traces()の多くのユースケース例については、「トレースの検索と分析」を参照してください。
次のステップ
- ユーザーとセッションの追跡
- バージョンと環境の追跡
- カスタムタグとメタデータを添付する
- ユーザーからのフィードバックを収集する
- スコアラー、評価データセット、本番運用 モニタリングを使用してエージェントを評価および監視 する 機能参照
このガイドの概念と機能の詳細については、以下を参照してください。
- トレース データ モデル - トレース、スパン、属性について学習します
- 評価のログ記録 - フィードバックの保存方法と使用方法を理解する
- トレースの検索と分析 - の多くの一般的なユースケースのクエリの例を参照してください。
mlflow.search_traces()**