PydanticAI のトレース
PydanticAIは、強力なタイピングと人間工学に基づいたAPIsを備えた本番運用グレードのAI世代アプリを構築するためのPythonフレームワークです。Pydantic モデルを中心に、エージェントのワークフロー全体で構造と検証を強制します。
MLflow Tracing は PydanticAI と統合して、エージェントのステップ、ツール呼び出し、モデル呼び出しを入力された入力と出力とともに記録します。mlflow.pydantic_ai.autologで有効にします。
サーバレス コンピュート クラスタでは、生成 AI トレースフレームワークの自動ログは自動的に有効になりません。 トレースする特定の統合に対して適切な mlflow.<library>.autolog() 関数を呼び出して、自動ログを明示的に有効にする必要があります。
この統合によって提供されるもの:
- プロンプト、kwargs、出力応答を含むエージェントコール
 - LLM 要求ログ、モデル名、プロンプト、パラメーター、応答
 - Tool 実行 キャプチャー tool name, arguments &; usage メトリクス
 - MCP サーバー呼び出しとツール呼び出しトレースのリスト
 - スパンメタデータ:レイテンシー、エラー、実行ID連携
 
前提 条件
PydanticAI で MLflow Tracing を使用するには、 MLflow と関連する PydanticAI パッケージをインストールする必要があります。
- Development
 - Production
 
開発環境の場合は、Databricks エクストラと PydanticAI を含む完全な MLflow パッケージをインストールします。
pip install --upgrade "mlflow[databricks]>=3.1" pydantic-ai openai
完全な mlflow[databricks] パッケージには、Databricks でのローカル開発と実験のためのすべての機能が含まれています。
本番運用デプロイの場合は、 mlflow-tracing とPydanticAIをインストールします。
pip install --upgrade mlflow-tracing pydantic-ai openai
mlflow-tracingパッケージは本番運用用に最適化されています。
最適なトレース エクスペリエンスを得るには、MLflow 3 をお勧めします。
例を実行する前に、環境を構成する必要があります。
Databricks ノートブック以外のユーザーの場合 : Databricks 環境変数を設定します。
export DATABRICKS_HOST="https://your-workspace.cloud.databricks.com"
export DATABRICKS_TOKEN="your-personal-access-token"
Databricks ノートブック内のユーザーの場合 : これらの資格情報は自動的に設定されます。
使用例
import os
from dataclasses import dataclass
from typing import Any
from httpx import AsyncClient
from pydantic_ai import Agent, ModelRetry, RunContext
@dataclass
class Deps:
    client: AsyncClient
    weather_api_key: str | None
    geo_api_key: str | None
weather_agent = Agent(
    # Switch to your favorite LLM
    "google-gla:gemini-2.0-flash",
    # 'Be concise, reply with one sentence.' is enough for some models (like openai) to use
    # the below tools appropriately, but others like anthropic and gemini require a bit more direction.
    system_prompt=(
        "Be concise, reply with one sentence."
        "Use the `get_lat_lng` tool to get the latitude and longitude of the locations, "
        "then use the `get_weather` tool to get the weather."
    ),
    deps_type=Deps,
    retries=2,
    instrument=True,
)
@weather_agent.tool
async def get_lat_lng(
    ctx: RunContext[Deps], location_description: str
) -> dict[str, float]:
    """Get the latitude and longitude of a location.
    Args:
        ctx: The context.
        location_description: A description of a location.
    """
    if ctx.deps.geo_api_key is None:
        return {"lat": 51.1, "lng": -0.1}
    params = {
        "q": location_description,
        "api_key": ctx.deps.geo_api_key,
    }
    r = await ctx.deps.client.get("https://geocode.maps.co/search", params=params)
    r.raise_for_status()
    data = r.json()
    if data:
        return {"lat": data[0]["lat"], "lng": data[0]["lon"]}
    else:
        raise ModelRetry("Could not find the location")
@weather_agent.tool
async def get_weather(ctx: RunContext[Deps], lat: float, lng: float) -> dict[str, Any]:
    """Get the weather at a location.
    Args:
        ctx: The context.
        lat: Latitude of the location.
        lng: Longitude of the location.
    """
    if ctx.deps.weather_api_key is None:
        return {"temperature": "21 °C", "description": "Sunny"}
    params = {
        "apikey": ctx.deps.weather_api_key,
        "location": f"{lat},{lng}",
        "units": "metric",
    }
    r = await ctx.deps.client.get(
        "https://api.tomorrow.io/v4/weather/realtime", params=params
    )
    r.raise_for_status()
    data = r.json()
    values = data["data"]["values"]
    # https://docs.tomorrow.io/reference/data-layers-weather-codes
    code_lookup = {
        1000: "Clear, Sunny",
        1100: "Mostly Clear",
        1101: "Partly Cloudy",
        1102: "Mostly Cloudy",
        1001: "Cloudy",
        2000: "Fog",
        2100: "Light Fog",
        4000: "Drizzle",
        4001: "Rain",
        4200: "Light Rain",
        4201: "Heavy Rain",
        5000: "Snow",
        5001: "Flurries",
        5100: "Light Snow",
        5101: "Heavy Snow",
        6000: "Freezing Drizzle",
        6001: "Freezing Rain",
        6200: "Light Freezing Rain",
        6201: "Heavy Freezing Rain",
        7000: "Ice Pellets",
        7101: "Heavy Ice Pellets",
        7102: "Light Ice Pellets",
        8000: "Thunderstorm",
    }
    return {
        "temperature": f'{values["temperatureApparent"]:0.0f}°C',
        "description": code_lookup.get(values["weatherCode"], "Unknown"),
    }
async def main():
    async with AsyncClient() as client:
        weather_api_key = os.getenv("WEATHER_API_KEY")
        geo_api_key = os.getenv("GEO_API_KEY")
        deps = Deps(
            client=client, weather_api_key=weather_api_key, geo_api_key=geo_api_key
        )
        result = await weather_agent.run(
            "What is the weather like in London and in Wiltshire?", deps=deps
        )
        print("Response:", result.output)
# If you are running this on a notebook
await main()
# Uncomment this is you are using an IDE or Python script.
# asyncio.run(main())
通常どおり PydanticAI を使用します (エージェント、ツール、オーケストレーション)。トレースは、関連するエクスペリメントに表示されます。
MCP サーバーに接続する
以下の例は、MLflow トレースを有効にして PydanticAI を使用して MCP サーバーを実行する方法を示しています。すべてのツール呼び出しおよびリスト操作は、UI のトレース・スパンとして自動的にキャプチャーされます。
import mlflow
import asyncio
mlflow.set_tracking_uri("http://localhost:5000")
mlflow.set_experiment("MCP Server")
mlflow.pydantic_ai.autolog()
from pydantic_ai import Agent
from pydantic_ai.mcp import MCPServerStdio
server = MCPServerStdio(
    "deno",
    args=[
        "run",
        "-N",
        "-R=node_modules",
        "-W=node_modules",
        "--node-modules-dir=auto",
        "jsr:@pydantic/mcp-run-python",
        "stdio",
    ],
)
agent = Agent("openai:gpt-4o", mcp_servers=[server], instrument=True)
async def main():
    async with agent.run_mcp_servers():
        result = await agent.run("How many days between 2000-01-01 and 2025-03-18?")
    print(result.output)
    # > There are 9,208 days between January 1, 2000, and March 18, 2025.
# If you are running this on a notebook
await main()
# Uncomment this is you are using an IDE or Python script.
# asyncio.run(main())
トークン使用状況の追跡
MLflow 3.2.0+トークン使用量の合計をトレース情報に記録し、呼び出しごとを SPAN 属性に記録します。
import mlflow
last_trace_id = mlflow.get_last_active_trace_id()
trace = mlflow.get_trace(trace_id=last_trace_id)
print(trace.info.token_usage)
for span in trace.data.spans:
    usage = span.get_attribute("mlflow.chat.tokenUsage")
    if usage:
        print(span.name, usage)
自動トレースを無効にする
mlflow.pydantic_ai.autolog(disable=True)で無効にするか、mlflow.autolog(disable=True)でグローバルに無効にします。