跟踪 Claude 代码

MLflow 跟踪 会自动跟踪使用 Claude 代理 SDK 创作的 Claude Code 对话和代理,捕获用户提示、AI 响应、工具使用情况、计时和会话元数据。

MLflow 支持用于 Claude Code 跟踪的两种方法:

  • CLI 跟踪:通过 MLflow CLI 配置跟踪以自动跟踪交互式 Claude Code 会话(MLflow 3.4+)
  • SDK 跟踪:使用 Claude 代理 SDK 以编程方式为 Python 应用程序启用跟踪(MLflow 3.5+)

要求

SDK 追踪

Claude Agent SDK 跟踪要求:

  • Claude 代理 SDK 0.1.0 或更高版本
  • 使用 Databricks Extras 的 MLflow 3.5 或更新版本
pip install --upgrade "mlflow[databricks]>=3.5" "claude-agent-sdk>=0.1.0"

CLI 跟踪

Claude Code CLI 跟踪需要以下条件:

  • Claude Code CLI 已安装,并可在你的 PATH 上作为 claude 使用
  • MLflow 3.4 或更高版本,附带 Databricks 附加功能
pip install --upgrade "mlflow[databricks]>=3.4"

将 “Claude Code” 追踪至 Databricks

SDK 追踪

  1. 设置 Databricks 和 Anthropic 的环境变量:

    export DATABRICKS_HOST="https://your-workspace.cloud.databricks.com"
    export DATABRICKS_TOKEN="your-personal-access-token"
    export ANTHROPIC_API_KEY="your-anthropic-api-key"
    

    对于生产环境,请使用 AI Gateway 或 Databricks 密钥 来安全地管理 API 密钥。

  2. 为 Claude 代理 SDK 启用自动记录以跟踪所有 Claude 代理 SDK 交互:

    注释

    MLflow 不支持跟踪对 query 的直接调用。 MLflow 仅支持跟踪使用 ClaudeSDKClient 的交互。

    import asyncio
    import mlflow.anthropic
    from claude_agent_sdk import ClaudeSDKClient
    
    # Enable autologging
    mlflow.anthropic.autolog()
    
    # Optionally configure MLflow experiment
    mlflow.set_experiment("my_claude_app")
    
    async def main():
       async with ClaudeSDKClient() as client:
          await client.query("What is the capital of France?")
    
          async for message in client.receive_response():
                print(message)
    
    if __name__ == "__main__":
       asyncio.run(main())
    

    若要禁用自动记录,请调用 mlflow.anthropic.autolog(disable=True)

  3. 在 Databricks 工作区的 MLflow 实验 UI 中查看跟踪数据。

CLI 跟踪

  1. 运行 mlflow autolog claude 以安装 MLflow Claude Code 插件并将 MLflow 配置 .claude/settings.json写入:

    # Set up tracing in the current directory, targeting Databricks
    mlflow autolog claude -u databricks -e <experiment-id>
    
    # Or target a different project directory
    mlflow autolog claude -d ~/my-project -u databricks -e <experiment-id>
    
    # Specify an experiment by name instead of ID
    mlflow autolog claude -u databricks -n "/Users/your-email@company.com/my-claude-traces"
    

    该命令会安装 mlflow-tracing Claude Code 插件,并将 MLflow 环境变量(MLFLOW_CLAUDE_TRACING_ENABLEDMLFLOW_TRACKING_URIMLFLOW_EXPERIMENT_ID)写入 env.claude/settings.json 块中。 该插件会自动采集跟踪数据。 无需手动配置挂钩。

    注释

    若要检查当前状态,请运行 mlflow autolog claude --status。 若要禁用跟踪,请运行 mlflow autolog claude --disable。 若要将配置写入 .claude/settings.local.json 而不是共享的 settings.json,请添加 --local 标志。

  2. 添加 Databricks 凭据。 Claude Code 插件会从 shell 环境、DATABRICKS_HOSTDATABRICKS_TOKEN 中读取 .claude/settings.local.json.claude/settings.json,并按上述先后顺序确定优先级。 如果您尚未在 shell 中导出它们,请将它们添加到 env.claude/settings.json 块中:

    {
      "env": {
        "MLFLOW_CLAUDE_TRACING_ENABLED": "true",
        "MLFLOW_TRACKING_URI": "databricks",
        "MLFLOW_EXPERIMENT_ID": "123456789",
        "DATABRICKS_HOST": "https://your-workspace.cloud.databricks.com",
        "DATABRICKS_TOKEN": "your-databricks-token"
      }
    }
    

    your-workspace.cloud.databricks.com 替换为您的 Databricks 工作区 URL,将your-databricks-token 替换为您的个人访问令牌

  3. 转到项目目录,并正常使用 Claude Code。 对话会自动记录至 Databricks:

    cd ~/my-project
    claude "help me refactor this Python function to be more efficient"
    
  4. 在 Databricks 工作区的 MLflow 实验 UI 中查看跟踪数据。

高级:使用评估进行 SDK 跟踪

可以将 SDK 跟踪与 MLflow 的 GenAI 评估框架配合使用:

import asyncio
import pandas as pd
from claude_agent_sdk import ClaudeSDKClient

import mlflow.anthropic
from mlflow.genai import evaluate, scorer
from mlflow.genai.judges import make_judge

mlflow.anthropic.autolog()

async def run_agent(query: str) -> str:
   """Run Claude Agent SDK and return response"""
   async with ClaudeSDKClient() as client:
      await client.query(query)

      response_text = ""
      async for message in client.receive_response():
            response_text += str(message) + "\n\n"

      return response_text

def predict_fn(query: str) -> str:
   """Synchronous wrapper for evaluation"""
   return asyncio.run(run_agent(query))

relevance = make_judge(
   name="relevance",
   instructions=(
      "Evaluate if the response in {{ outputs }} is relevant to "
      "the question in {{ inputs }}. Return either 'pass' or 'fail'."
   ),
   model="openai:/gpt-4o",
)

# Create evaluation dataset
eval_data = pd.DataFrame(
   [
      {"inputs": {"query": "What is machine learning?"}},
      {"inputs": {"query": "Explain neural networks"}},
   ]
)

# Run evaluation with automatic tracing
mlflow.set_experiment("claude_evaluation")
evaluate(data=eval_data, predict_fn=predict_fn, scorers=[relevance])

Troubleshooting

SDK 追踪

缺少痕迹:

  • 在创建mlflow.anthropic.autolog()之前,需先调用验证ClaudeSDKClient
  • 检查是否正确设置了环境变量 (DATABRICKS_HOSTDATABRICKS_TOKEN
  • 验证 Databricks 令牌是否已过期

CLI 跟踪

请验证项目是否已启用 CLI 追踪功能:

mlflow autolog claude --status

这会显示当前跟踪配置,以及它是否对 Claude Code CLI 处于活动状态。

跟踪不起作用:

  • 验证你是否在配置的目录中
  • 检查.claude/settings.json是否存在,并且在MLFLOW_CLAUDE_TRACING_ENABLED块中包含MLFLOW_TRACKING_URIMLFLOW_EXPERIMENT_IDenv
  • mlflow-tracing确认插件已安装:claude plugin list
  • .claude/mlflow/claude_tracing.log 查看日志

缺少痕迹:

  • 检查你的配置中 MLFLOW_CLAUDE_TRACING_ENABLED 是否为 true
  • 验证跟踪 URI 是否可访问
  • .claude/mlflow/claude_tracing.log 查看日志

Databricks 连接问题:

  • 请确认 MLFLOW_TRACKING_URIDATABRICKS_HOSTDATABRICKS_TOKEN 已设置,无论是在 shell 环境中,还是在 env(或 .claude/settings.json)的 .claude/settings.local.json 块中。
  • 检查您的 Databricks 令牌是否已失效
  • 验证工作区 URL 是否正确(例如 https://your-workspace.cloud.databricks.com