バージョンと環境の追跡
生成AI アプリケーションの実行環境とアプリケーションバージョンを追跡することで、コードに関連するパフォーマンスと品質の問題をデバッグできます。このメタデータにより、次のことが可能になります。
- 以下のフェーズ固有の環境: 
development、staging、およびproduction - アプリのバージョン間での パフォーマンス/品質の追跡 とレグレッションの検出
 - 問題発生時の 根本原因分析の迅速化
 
MLflow では、 メタデータ (キーと値のペア) を使用して、トレースにコンテキスト情報を格納します。
バージョニングのしくみの包括的な概要については、「 バージョンの追跡」を参照してください。
自動的に入力されたメタデータ
これらの標準メタデータ フィールドは、実行環境に基づいて MLflow によって自動的にキャプチャされます。
自動キャプチャロジックが要件を満たさない場合は、 mlflow.update_current_trace(metadata={"mlflow.source.name": "custom_name"})を使用して、これらの自動的に入力されたメタデータを手動で上書きできます。
カテゴリー  | メタデータフィールド  | 説明  | 自動設定ロジック  | 
|---|---|---|---|
実行環境  | 
  | トレースを生成したエントリポイントまたはスクリプト。  | Pythonスクリプトのファイル名、Databricks/Jupyter ノートブックのノートブック名が自動的に入力されます。  | 
  | Git コミット ハッシュ。  | Git リポジトリから実行した場合、コミット ハッシュは自動的に検出され、入力されます。  | |
  | Git ブランチ。  | Git リポジトリから実行した場合、現在のブランチ名が自動的に検出され、入力されます。  | |
  | Git リポジトリの URL。  | Git リポジトリから実行した場合、リポジトリの URL は自動的に検出され、入力されます。  | |
  | 実行環境をキャプチャします。  | Jupyter または Databricks ノートブックで実行されている場合は自動的に   | |
アプリケーションのバージョン  | 
  | MLflow LoggedModel ID。  | 環境変数   | 
自動的に入力されるメタデータのカスタマイズ
mlflow.update_current_trace()を使用して、自動的に入力されたメタデータフィールドを上書きできます。これは、自動検出が要件を満たしていない場合、またはコンテキストを追加する場合に便利です。
import mlflow
import os
# We suggest populating metadata from environment variables rather than hard coding the values
@mlflow.trace
def my_app(user_question: str) -> dict:
    # Override automatically populated metadata and add custom context
    mlflow.update_current_trace(
        metadata={
            # Use any of the keys from above
            "mlflow.source.type": current_env = os.getenv("APP_ENVIRONMENT", "development"),  # Override default LOCAL/NOTEBOOK
        }
    )
    # Application logic
    return {"response": user_question + "!!"}
my_app("test")
完全にカスタム化されたメタデータ
カスタムメタデータ をアタッチして、アプリケーション固有のコンテキストをキャプチャできます。カスタムメタデータのアタッチの詳細については、「 カスタムメタデータ/タグのアタッチ」を参照してください。
たとえば、次のような情報を添付できます。
app_version: 例:"1.0.0"(APP_VERSION環境変数から)deployment_id: 例:"deploy-abc-123"(DEPLOYMENT_ID環境変数から)region: 例:"us-east-1"(REGION環境変数から)- (機能フラグなどの他のカスタムタグも追加できます)
 
import mlflow
import os
# We suggest populating metadata from environment variables rather than hard coding the values
@mlflow.trace
def my_app(user_question: str) -> dict:
    # Override automatically populated metadata and add custom context
    mlflow.update_current_trace(
        metadata={
            # Use any key
            "app_version": os.getenv("APP_VERSION", "development")
        }
    )
    # Application logic
    return {"response": user_question + "!!"}
my_app("test")
本番運用 Web アプリケーションの例
本番運用 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
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 popoulated 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")
        }
    )
    # --- 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 UI の使用
MLflow UI (トレースタブ) では、アタッチされたメタデータを表示できます。

プログラムによる分析
MLflow SDK を使用して、より複雑な分析を行ったり、他のツールと統合したりします。
from mlflow.client import MlflowClient
client = MlflowClient()
# Example 1: Compare error rates across app versions in production
def compare_version_error_rates(experiment_id: str, versions: list):
    error_rates = {}
    for version in versions:
        traces = client.search_traces(
            filter_string=f"metadata.`mlflow.source.type` = 'production' AND metadata.app_version = '{version}'"
        )
        if not traces:
            error_rates[version] = None # Or 0 if no traces means no errors
            continue
        error_count = sum(1 for t in traces if t.info.status == "ERROR")
        error_rates[version] = (error_count / len(traces)) * 100
    return error_rates
# version_errors = compare_version_error_rates("your_exp_id", ["1.0.0", "1.1.0"])
# print(version_errors)
# Example 2: Analyze performance for a specific feature flag
def analyze_feature_flag_performance(experiment_id: str, flag_name: str):
    control_latency = []
    treatment_latency = []
    control_traces = client.search_traces(
        filter_string=f"metadata.feature_flag_{flag_name} = 'false'",
        # extract_fields=["execution_time_ms"] # Not a real field, use span attributes if needed
    )
    for t in control_traces: control_latency.append(t.info.execution_time_ms)
    treatment_traces = client.search_traces(
        experiment_ids=[experiment_id],
        filter_string=f"metadata.feature_flag_{flag_name} = 'true'",
    )
    for t in treatment_traces: treatment_latency.append(t.info.execution_time_ms)
    avg_control_latency = sum(control_latency) / len(control_latency) if control_latency else 0
    avg_treatment_latency = sum(treatment_latency) / len(treatment_latency) if treatment_latency else 0
    return {
        f"avg_latency_{flag_name}_off": avg_control_latency,
        f"avg_latency_{flag_name}_on": avg_treatment_latency
    }
# perf_metrics = analyze_feature_flag_performance("your_exp_id", "new_retriever")
# print(perf_metrics)
次のステップ
- トレースを使用したエージェントのデプロイ - 本番運用のログトレースを理解する
 - ユーザーとセッションの追跡 - ユーザー中心の可観測性をトレースに追加
 - カスタムタグ/メタデータの添付 - コンテキストでトレースを充実させる方法の詳細をご覧ください
 
機能参照
このガイドの概念と機能の詳細については、以下を参照してください。
- トレーシングデータモデル - メタデータと、それがトレースにどのように格納されるかを理解する
 - アプリのバージョン追跡の概念 - バージョニング戦略の詳細
 - SDK によるトレースのクエリ - メタデータ フィルターを使用した高度なクエリ