追踪 LangChain Deep Agent

LangChain Deep Agent 是一个开源库,用于构建可以规划、研究和执行复杂任务的自主代理。Deep Agent 构建在 LangGraph 之上,提供了高级抽象,用于创建具有待办事项管理、文件操作和生成专业子代理等内置功能的复杂代理。
由于 Deep Agent 构建在 LangGraph 之上,因此通过 mlflow.langchain.autolog() 可以直接使用 MLflow 追踪。这会自动捕获整个代理执行过程,包括规划、工具调用和子代理交互。
python
import mlflow
mlflow.langchain.autolog()
开始使用
1
安装依赖项
bash
pip install deepagents tavily-python 'mlflow[genai]'
2
启动 MLflow 服务器
- 本地 (pip)
- 本地 (docker)
如果您有本地 Python 环境 >= 3.10,您可以使用 mlflow CLI 命令在本地启动 MLflow 服务器。
bash
mlflow server
MLflow 还提供了一个 Docker Compose 文件,用于启动带有 postgres 数据库和 minio 服务器的本地 MLflow 服务器。
bash
git clone --depth 1 --filter=blob:none --sparse https://github.com/mlflow/mlflow.git
cd mlflow
git sparse-checkout set docker-compose
cd docker-compose
cp .env.dev.example .env
docker compose up -d
有关更多详细信息,请参阅 说明,例如覆盖默认环境变量。
3
启用追踪并创建 Deep Agent
python
import os
from typing import Literal
import mlflow
from deepagents import create_deep_agent
from tavily import TavilyClient
# Enable auto-tracing for LangChain (and LangGraph-based frameworks like Deep Agent)
mlflow.langchain.autolog()
# Optional: Set a tracking URI and an experiment
mlflow.set_tracking_uri("https://:5000")
mlflow.set_experiment("Deep Agent")
# Initialize search provider
tavily_client = TavilyClient(api_key=os.environ["TAVILY_API_KEY"])
# Define your tool
def internet_search(
query: str,
max_results: int = 5,
topic: Literal["general", "news", "finance"] = "general",
include_raw_content: bool = False,
):
"""Run a web search to find relevant information."""
return tavily_client.search(
query,
max_results=max_results,
include_raw_content=include_raw_content,
topic=topic,
)
# Create agent with system instructions
research_instructions = """You are an expert researcher. Your job is to conduct
thorough research and then write a polished report. You have access to an internet
search tool as your primary means of gathering information."""
agent = create_deep_agent(tools=[internet_search], system_prompt=research_instructions)
# Invoke the agent
result = agent.invoke(
{
"messages": [
{
"role": "user",
"content": "What are the latest developments in AI agents?",
}
]
}
)
print(result["messages"][-1].content)
4
在 MLflow UI 中查看跟踪
浏览 MLflow UI,地址为 https://:5000(或您的 MLflow 服务器 URL),以查看追踪信息。追踪信息将捕获完整的代理执行过程,包括
- 规划和任务分解
- 工具调用(例如
internet_search) - 内部 LLM 调用
- 子代理生成(如果适用)
令牌使用跟踪
MLflow 会自动跟踪 Deep Agent 工作流中所有 LLM 调用的令牌使用情况。每次 LLM 调用的令牌使用情况记录在 mlflow.chat.tokenUsage 跨度属性中,整个追踪的总使用情况记录在 mlflow.trace.tokenUsage 元数据字段中。
python
import mlflow
mlflow.langchain.autolog()
# Execute the agent
result = agent.invoke(
{"messages": [{"role": "user", "content": "Summarize recent AI news"}]}
)
# Get the trace object
last_trace_id = mlflow.get_last_active_trace_id()
trace = mlflow.get_trace(trace_id=last_trace_id)
# Print the total token usage
total_usage = trace.info.token_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']}")
禁用自动追踪
可以通过调用 mlflow.langchain.autolog(disable=True) 或 mlflow.autolog(disable=True) 来全局禁用 Deep Agent 的自动追踪。