追踪 Claude Code

MLflow 追踪为 Claude Code 提供自动追踪功能
- CLI 追踪:自动追踪交互式 Claude Code CLI 对话
- SDK 追踪:追踪 Python 应用程序中 Claude Agent SDK 的使用情况
设置自动追踪后,MLflow 将自动捕获您的 Claude Code 对话追踪并将其记录到活动的 MLflow 实验中。该追踪会自动捕获信息,例如
- 用户提示和助手回复
- 工具使用情况(文件操作、代码执行、网络搜索等)
- 对话时间和持续时间
- 工具执行结果
- Token 用量(输入、输出和总 Token 数)
- 会话元数据,包括工作目录和用户
设置
Claude Code 追踪可以通过 CLI 命令(用于交互式使用)或 Python SDK 导入(用于编程使用)进行配置。
- CLI 追踪
- SDK 追踪
CLI 追踪设置
使用 CLI 追踪以自动捕获您的交互式 Claude Code CLI 对话。
要求
- MLflow >= 3.4 (
pip install 'mlflow[genai]>=3.4') - Claude Code CLI已安装并配置
基本设置
bash
# Set up tracing in current directory
mlflow autolog claude
# Set up tracing in specific directory
mlflow autolog claude ~/my-project
# Check tracing status
mlflow autolog claude --status
# Disable tracing
mlflow autolog claude --disable
配置示例
bash
# Set up with custom tracking URI
mlflow autolog claude -u file://./custom-mlruns
mlflow autolog claude -u sqlite:///mlflow.db
# Set up with Databricks backend and a specific experiment ID
mlflow autolog claude -u databricks -e 123456789
# Set up with specific experiment
mlflow autolog claude -n "My AI Project"
工作原理
- 设置阶段:
mlflow autolog claude命令会在项目目录中的.claude/settings.json文件中配置 Claude Code 钩子 - 自动追踪:当您在配置的目录中使用
claude命令时,您的对话将被自动追踪 - 查看结果:使用 MLflow UI 探索您的追踪
基本示例
bash
# Set up tracing in your project
mlflow autolog claude ~/my-project
# Navigate to project directory
cd ~/my-project
# Use Claude Code normally - tracing happens automatically
claude "help me refactor this Python function to be more efficient"
# View traces in MLflow UI
mlflow server
SDK 追踪设置
在构建以编程方式使用 Claude Agent SDK 的应用程序时,使用 SDK 追踪。
要求
- MLflow >= 3.5 (
pip install 'mlflow[genai]>=3.5') - Claude Agent SDK >= 0.1.0 (
pip install claude-agent-sdk >= 0.1.0)
基本设置
python
import mlflow.anthropic
# Enable automatic tracing for Claude Agent SDK
mlflow.anthropic.autolog()
启用后,所有 Claude Agent SDK 交互都将被自动追踪。
注意
只有 ClaudeSDKClient 支持追踪。直接调用 query 不会被追踪!
完整示例
python
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 GenAI 评估进行 Claude 追踪
您也可以将 SDK 追踪与 MLflow 的 GenAI 评估框架一起使用
python
import asyncio
import pandas as pd
from claude_agent_sdk import ClaudeSDKClient
from typing import Literal
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'."
),
feedback_value_type=Literal["pass", "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])
Token 用量
MLflow 会自动跟踪 Claude Code 对话中每次 LLM 调用的 Token 用量。每次 LLM 调用的 Token 用量记录在 mlflow.chat.tokenUsage 属性中。整个追踪的总 Token 用量可在追踪信息对象的 token_usage 字段中找到。
python
import mlflow
# Get a Claude Code trace by its trace ID
trace = mlflow.get_trace("<your-trace-id>")
# Print the total token usage
total_usage = trace.info.token_usage
if total_usage:
print("== Total token usage: ==")
print(f" Input tokens: {total_usage['input_tokens']}")
print(f" Output tokens: {total_usage['output_tokens']}")
print(f" Total tokens: {total_usage['total_tokens']}")
# Print the token usage for each LLM call
print("\n== Detailed usage for each LLM call: ==")
for span in trace.data.spans:
if usage := span.get_attribute("mlflow.chat.tokenUsage"):
print(f"{span.name}:")
print(f" Input tokens: {usage['input_tokens']}")
print(f" Output tokens: {usage['output_tokens']}")
print(f" Total tokens: {usage['total_tokens']}")
bash
== Total token usage: ==
Input tokens: 1250
Output tokens: 340
Total tokens: 1590
== Detailed usage for each LLM call: ==
llm_call_1:
Input tokens: 500
Output tokens: 120
Total tokens: 620
llm_call_2:
Input tokens: 750
Output tokens: 220
Total tokens: 970
故障排除
- CLI 追踪
- SDK 追踪
检查 CLI 状态
bash
mlflow autolog claude --status
这显示了
- 是否启用了追踪
- 当前的追踪 URI
- 配置的实验
- 任何配置问题
常见的 CLI 问题
追踪不工作
- 确保您在配置的目录中
- 检查
.claude/settings.json是否存在 - 在
.claude/mlflow/claude_tracing.log中查看日志
缺少追踪
- 检查配置中是否设置了
MLFLOW_CLAUDE_TRACING_ENABLED=true - 验证追踪 URI 是否可访问
- 在
.claude/mlflow/claude_tracing.log中查看日志
禁用 CLI 追踪
要停止自动 CLI 追踪
bash
mlflow autolog claude --disable
这会从 .claude/settings.json 中移除钩子,但会保留现有追踪。