ユーザーとセッションの追跡
生成AI アプリケーションでユーザーとセッションを追跡すると、ユーザーの行動を理解し、会話フローを分析し、パーソナライゼーションを改善するための重要なコンテキストが提供されます。MLflow は、トレースをユーザーに関連付け、それらをセッションにグループ化するための組み込みサポートを提供します。
前提 条件
環境に基づいて適切なインストール方法を選択します。
- Production
 - Development
 
本番運用デプロイメントの場合は、 mlflow-tracing パッケージをインストールします。
pip install --upgrade mlflow-tracing
mlflow-tracingパッケージは、本番運用での使用に最適化されており、依存関係が最小限に抑えられ、パフォーマンス特性が向上しています。
開発環境の場合は、Databricks の追加機能を含む完全な MLflow パッケージをインストールします。
pip install --upgrade "mlflow[databricks]>=3.1"
フル mlflow[databricks] パッケージには、Databricks でのローカル開発と実験に必要なすべての機能が含まれています。
MLflow 3 は、ユーザーとセッションの追跡に必要です。MLflow 2.x は、パフォーマンスの制限と、本番運用での使用に不可欠な機能が不足しているため、サポートされていません。
ユーザーとセッションを追跡する理由
ユーザーとセッションの追跡により、強力なアナリティクスと改善が可能になります。
- ユーザー行動分析 - さまざまなユーザーがアプリケーションとどのように対話するかを理解する
 - 会話フローの追跡 - 複数ターンの会話とコンテキスト保持を分析します
 - パーソナライゼーションの知見 - ユーザー固有のエクスペリエンスを向上させるためのパターンを特定する
 - ユーザーあたりの品質 - さまざまなユーザー セグメント間でパフォーマンス メトリクスを追跡します
 - セッションの継続性 - 複数のインタラクション間でコンテキストを維持
 
標準の MLflow メタデータ フィールド
MLflow には、セッションとユーザーの追跡用に 2 つの標準メタデータ フィールドが用意されています。
mlflow.trace.user- トレースを特定のユーザーに関連付けますmlflow.trace.session- 複数ターンの会話に属するトレースをグループ化します
これらの標準メタデータ フィールドを使用すると、MLflow は UI でフィルター処理とグループ化を自動的に有効にします。タグとは異なり、メタデータはトレースがログに記録されると更新できないため、ユーザーIDやセッションIDなどの不変識別子に最適です。
基本的な実装
ユーザーにとセッションの追跡をアプリケーションに追加する方法を次に示します。
import mlflow
@mlflow.trace
def chat_completion(user_id: str, session_id: str, message: str):
    """Process a chat message with user and session tracking."""
    # Add user and session context to the current trace
    # The @mlflow.trace decorator ensures there's an active trace
    mlflow.update_current_trace(
        metadata={
            "mlflow.trace.user": user_id,      # Links this trace to a specific user
            "mlflow.trace.session": session_id, # Groups this trace with others in the same conversation
        }
    )
    # The trace will capture the execution time, inputs, outputs, and any errors
    # Your chat logic here
    response = generate_response(message)
    return response
# Example usage in a chat application
def handle_user_message(request):
    # Extract user and session IDs from your application's context
    # These IDs should be consistent across all interactions
    return chat_completion(
        user_id=request.user_id,        # e.g., "user-123" - unique identifier for the user
        session_id=request.session_id,   # e.g., "session-abc-456" - groups related messages
        message=request.message
    )
# Placeholder chat logic
def generate_response(message: str) -> str:
    """Your chat logic here"""
    return "Placeholder response"
# Run the chat completion with user and session context
result = chat_completion(
    user_id="user-123",
    session_id="session-abc-456",
    message="What is MLflow and how does it help with machine learning?"
)
キーポイント:
@mlflow.traceデコレータは、関数実行のトレースを自動的に作成しますmlflow.update_current_trace()は、ユーザー ID とセッション ID をメタデータとしてアクティブ・トレースに追加しますmetadataを使用すると、トレースが作成されると、これらの識別子が不変になります
本番運用 Web アプリケーションの例
本番運用アプリケーションでは、通常、ユーザー、セッション、およびその他のコンテキスト情報を同時に追跡します。 次の例は、 メタデータとユーザーフィードバックをトレースに追加 するから適応されており、 本番運用Webアプリケーションの例に示すように、環境とデプロイメントのコンテキストも組み込まれています。
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
    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,
        }
    )
    # --- 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?"}'

この例では、コンテキスト追跡に対する統一されたアプローチを示しており、以下をキャプチャします。
- ユーザー情報 : 
X-User-IDヘッダーから、mlflow.trace.userメタデータとしてログに記録されます。 - セッション情報 : 
X-Session-IDヘッダーから、mlflow.trace.sessionメタデータとしてログに記録されます。 
データのクエリと分析
MLflow UI の使用
MLflow UI でトレースをフィルター処理するには、次の検索クエリを使用します。
# Find all traces for a specific user
metadata.`mlflow.trace.user` = 'user-123'
# Find all traces in a session
metadata.`mlflow.trace.session` = 'session-abc-456'
# Find traces for a user within a specific session
metadata.`mlflow.trace.user` = 'user-123' AND metadata.`mlflow.trace.session` = 'session-abc-456'

プログラムによる分析
MLflow SDK を使用して、ユーザーとセッションのデータをプログラムで分析します。これにより、カスタム分析の構築、レポートの生成、ユーザーの行動パターンの監視を大規模に行うことができます。
from mlflow.client import MlflowClient
client = MlflowClient()
# Analyze user behavior
def analyze_user_behavior(user_id: str, experiment_id: str):
    """Analyze a specific user's interaction patterns."""
    # Search for all traces from a specific user
    user_traces = client.search_traces(
        experiment_ids=[experiment_id],
        filter_string=f"metadata.`mlflow.trace.user` = '{user_id}'",
        max_results=1000
    )
    # Calculate key metrics
    total_interactions = len(user_traces)
    unique_sessions = len(set(t.info.metadata.get("mlflow.trace.session", "") for t in user_traces))
    avg_response_time = sum(t.info.execution_time_ms for t in user_traces) / total_interactions
    return {
        "total_interactions": total_interactions,
        "unique_sessions": unique_sessions,
        "avg_response_time": avg_response_time
    }
# Analyze session flow
def analyze_session_flow(session_id: str, experiment_id: str):
    """Analyze conversation flow within a session."""
    # Get all traces from a session, ordered chronologically
    session_traces = client.search_traces(
        experiment_ids=[experiment_id],
        filter_string=f"metadata.`mlflow.trace.session` = '{session_id}'",
        order_by=["timestamp ASC"]
    )
    # Build a timeline of the conversation
    conversation_turns = []
    for i, trace in enumerate(session_traces):
        conversation_turns.append({
            "turn": i + 1,
            "timestamp": trace.info.timestamp,
            "duration_ms": trace.info.execution_time_ms,
            "status": trace.info.status
        })
    return conversation_turns
主な機能:
- ユーザー行動分析 - ユーザーごとのインタラクションの頻度、セッション数、パフォーマンスメトリクスを追跡します
 - セッションフロー分析 - 会話のタイムラインを再構築して、マルチターンのインタラクションを理解する
 - 柔軟なフィルタリング - MLflow の検索構文を使用して、メタデータ フィールドの任意の組み合わせでトレースをクエリします
 - スケーラブルな分析 - 数千のトレースをプログラムで処理し、大規模な知見を実現
 - エクスポート可能なデータ - 結果は簡単に DataFrames に変換したり、さらに分析するためにエクスポートしたりできます
 
おすすめの方法
- 一貫した ID 形式 - ユーザー ID とセッション ID に標準化された形式を使用します
 - セッション境界 - セッションの開始と終了のタイミングに関する明確なルールを定義します
 - メタデータのエンリッチメント - ユーザーセグメントやセッションタイプなどのコンテキストを追加します
 - リクエストトラッキングとの組み合わせ - ユーザー/セッションデータをリクエストIDにリンクして、完全なトレーサビリティを実現
 - 定期的な分析 - ユーザーの行動とセッションパターンを監視するためのダッシュボードを設定します
 
他の MLflow 機能との統合
ユーザーとセッションの追跡は、他の MLflow 機能とシームレスに統合されます。
- 評価 - 異なるユーザーセグメント間で品質メトリクスを比較し、改善すべき領域を特定します。
 - 本番運用 モニタリング - ユーザーコホートまたはセッションタイプごとにパフォーマンスパターンを追跡します
 - フィードバック収集 - ユーザーフィードバックを特定のセッションに関連付けて、品質分析を行います
 - 評価データセットの構築 - 特定のユーザーセッションからターゲットを絞ったデータセットを作成します
 
本番運用に関する考慮事項
包括的な本番運用の実装については、以下について説明します。「 メタデータとユーザーフィードバックをトレースに追加 する」を参照してください。
- 本番運用環境でのユーザーとセッションの追跡の設定
 - セッション ID と要求 ID の組み合わせによる完全なトレーサビリティ
 - セッション全体に対するフィードバック収集の実装
 - 大量のセッション管理のベストプラクティス
 
次のステップ
- トレースを使用したエージェントのデプロイ - 本番運用のログトレースを理解する
 - 環境とコンテキストの追跡 - デプロイと環境のメタデータをトレースに追加します
 - ユーザーフィードバックの収集 - ユーザーからの質の高いシグナルをキャプチャ
 
機能参照
このガイドの概念と機能の詳細については、以下を参照してください。
- トレーシングデータモデル - メタデータ、タグ、トレース構造を理解する
 - SDKによるトレースのクエリ - 高度なクエリ手法を学ぶ
 - 本番運用 モニタリング コンセプト - モニタリング パターンの探索