使用 LangChain 构建和运行代理时,您需要了解它们的行为方式:哪些 工具 它们调用、生成什么提示,以及如何做出决策。使用 @[ 构建的 LangChain 代理create_agent] 自动支持通过 LangSmith进行追踪,这是一个用于捕获、调试、评估和监控 LLM 应用程序行为的平台。
追踪记录 记录代理执行的每一步,从初始用户输入到最终响应,包括所有工具调用、模型交互和决策点。这些执行数据帮助您调试问题、评估不同输入的性能,以及监控生产环境中的使用模式。
本指南向您展示如何为 LangChain 代理启用追踪并使用 LangSmith 分析其执行情况。
前提条件
在开始之前,请确保您具备以下条件:
- LangSmith 账户:在 smith.langchain.com.
- LangSmith API 密钥:按照 创建 API 密钥 guide.
启用追踪
所有 LangChain 代理自动支持 LangSmith 追踪。要启用它,请设置以下环境变量:
快速入门
无需额外代码即可将追踪记录到 LangSmith。只需像平常一样运行您的代理代码:
from langchain.agents import create_agent
def send_email(to: str, subject: str, body: str):
"""Send an email to a recipient."""
# ... email sending logic
return f"Email sent to {to}"
def search_web(query: str):
"""Search the web for information."""
# ... web search logic
return f"Search results for: {query}"
agent = create_agent(
model="gpt-5.5",
tools=[send_email, search_web],
system_prompt="You are a helpful assistant that can send emails and search the web."
)
# Run the agent - all steps will be traced automatically
response = agent.invoke({
"messages": [{"role": "user", "content": "Search for the latest AI news and email a summary to john@example.com"}]
})
默认情况下,追踪会记录到名为 default的项目中。要配置自定义项目名称,请参阅 记录到项目.