Skip to main content
在使用 LangChain 构建和运行代理时,您需要了解它们的行为:它们调用了哪些 工具、生成了哪些提示以及如何做出决策。使用 create_agent 构建的 LangChain 代理会自动支持通过 LangSmith 进行跟踪,这是一个用于捕获、调试、评估和监控 LLM 应用程序行为的平台。 跟踪 记录了代理执行的每一步,从初始用户输入到最终响应,包括所有工具调用、模型交互和决策点。这些执行数据有助于调试问题、评估不同输入的性能以及监控生产中的使用模式。 本指南将向您展示如何为 LangChain 代理启用跟踪,并使用 LangSmith 分析其执行情况。

前提条件

在开始之前,请确保您具备以下条件:

启用跟踪

所有 LangChain 代理都自动支持 LangSmith 跟踪。要启用它,请设置以下环境变量:
export LANGSMITH_TRACING=true
export LANGSMITH_API_KEY=<your-api-key>

快速入门

无需额外代码即可将跟踪记录到 LangSmith。只需像平常一样运行您的代理代码:
from langchain.agents import create_agent


def send_email(to: str, subject: str, body: str):
    """向收件人发送电子邮件。"""
    # ... 电子邮件发送逻辑
    return f"已发送电子邮件至 {to}"

def search_web(query: str):
    """在网络上搜索信息。"""
    # ... 网络搜索逻辑
    return f"搜索结果:{query}"

agent = create_agent(
    model="gpt-4.1",
    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"}]
})
By default, the trace will be logged to the project with the name default. To configure a custom project name, see Log to a project.

Trace selectively

You may opt to trace specific invocations or parts of your application using LangSmith’s tracing_context context manager:
import langsmith as ls

# This WILL be traced
with ls.tracing_context(enabled=True):
    agent.invoke({"messages": [{"role": "user", "content": "Send a test email to alice@example.com"}]})

# This will NOT be traced (if LANGSMITH_TRACING is not set)
agent.invoke({"messages": [{"role": "user", "content": "Send another email"}]})

Log to a project

You can set a custom project name for your entire application by setting the LANGSMITH_PROJECT environment variable:
export LANGSMITH_PROJECT=my-agent-project
You can set the project name programmatically for specific operations:
import langsmith as ls

with ls.tracing_context(project_name="email-agent-test", enabled=True):
    response = agent.invoke({
        "messages": [{"role": "user", "content": "Send a welcome email"}]
    })

Add metadata to traces

You can annotate your traces with custom metadata and tags:
response = agent.invoke(
    {"messages": [{"role": "user", "content": "Send a welcome email"}]},
    config={
        "tags": ["production", "email-assistant", "v1.0"],
        "metadata": {
            "user_id": "user_123",
            "session_id": "session_456",
            "environment": "production"
        }
    }
)
tracing_context also accepts tags and metadata for fine-grained control:
with ls.tracing_context(
    project_name="email-agent-test",
    enabled=True,
    tags=["production", "email-assistant", "v1.0"],
    metadata={"user_id": "user_123", "session_id": "session_456", "environment": "production"}):
    response = agent.invoke(
        {"messages": [{"role": "user", "content": "Send a welcome email"}]}
    )
This custom metadata and tags will be attached to the trace in LangSmith.
To learn more about how to use traces to debug, evaluate, and monitor your agents, see the LangSmith documentation.