Skip to content

当你使用 LangChain 构建和运行智能体时,你需要了解它们的行为:它们调用了哪些工具,生成了什么提示词,以及它们如何做出决策。使用 create_agent 构建的 LangChain 智能体会自动支持通过 LangSmith 进行追踪,LangSmith 是一个用于捕获、调试、评估和监控 LLM 应用行为的平台。

当你使用 LangChain 构建和运行智能体时,你需要了解它们的行为:它们调用了哪些工具,生成了什么提示词,以及它们如何做出决策。使用 createAgent 构建的 LangChain 智能体会自动支持通过 LangSmith 进行追踪,LangSmith 是一个用于捕获、调试、评估和监控 LLM 应用行为的平台。

追踪 会记录智能体执行的每一步,从初始用户输入到最终响应,包括所有工具调用、模型交互和决策点。这些执行数据可以帮助你调试问题、评估不同输入下的性能,并在生产环境中监控使用模式。

本指南将向你展示如何为你的 LangChain 智能体启用追踪,并使用 LangSmith 分析它们的执行过程。

前提条件

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

启用追踪

所有 LangChain 智能体都自动支持 LangSmith 追踪。要启用它,请设置以下环境变量:

bash
export LANGSMITH_TRACING=true
export LANGSMITH_API_KEY=<your-api-key>

快速开始

无需额外代码即可将追踪记录到 LangSmith。只需像往常一样运行你的智能体代码:

python
from langchain.agents import create_agent

def send_email(to: str, subject: str, body: str):
    """Send an email to a recipient."""
    # ... 邮件发送逻辑
    return f"Email sent to {to}"

def search_web(query: str):
    """Search the web for information."""
    # ... 网络搜索逻辑
    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."
)

# 运行智能体 - 所有步骤都会被自动追踪
response = agent.invoke({
    "messages": [{"role": "user", "content": "Search for the latest AI news and email a summary to john@example.com"}]
})
ts
import { createAgent } from "@langchain/agents";

function sendEmail(to: string, subject: string, body: string): string {
    // ... 邮件发送逻辑
    return `Email sent to ${to}`;
}

function searchWeb(query: string): string {
    // ... 网络搜索逻辑
    return `Search results for: ${query}`;
}

const agent = createAgent({
    model: "gpt-5.5",
    tools: [sendEmail, searchWeb],
    systemPrompt: "You are a helpful assistant that can send emails and search the web."
});

// 运行智能体 - 所有步骤都会被自动追踪
const response = await agent.invoke({
    messages: [{ role: "user", content: "Search for the latest AI news and email a summary to john@example.com" }]
});

默认情况下,追踪会记录到名为 default 的项目中。要配置自定义项目名称,请参见记录到项目

Trace selectively

You may opt to trace specific invocations or parts of your application using LangSmith's tracing_context context manager:

python
import langsmith as ls

# 这将被追踪
with ls.tracing_context(enabled=True):
    agent.invoke({"messages": [{"role": "user", "content": "Send a test email to alice@example.com"}]})

# 这不会被追踪(如果未设置 LANGSMITH_TRACING)
agent.invoke({"messages": [{"role": "user", "content": "Send another email"}]})

Log to a project

Statically

You can set a custom project name for your entire application by setting the LANGSMITH_PROJECT environment variable:

bash
export LANGSMITH_PROJECT=my-agent-project

Dynamically

You can set the project name programmatically for specific operations:

python
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:

python
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:

python
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.

TIP

To learn more about how to use traces to debug, evaluate, and monitor your agents, see the LangSmith documentation.

Trace selectively

You may opt to trace specific invocations or parts of your application using LangSmith's tracing_context context manager:

ts
import { LangChainTracer } from "@langchain/core/tracers/tracer_langchain";

// 这将被追踪
const tracer = new LangChainTracer();
await agent.invoke(
  {
    messages: [{role: "user", content: "Send a test email to alice@example.com"}]
  },
  { callbacks: [tracer] }
);

// 这不会被追踪(如果未设置 LANGSMITH_TRACING)
await agent.invoke(
  {
    messages: [{role: "user", content: "Send another email"}]
  }
);

Log to a project

Statically

You can set a custom project name for your entire application by setting the LANGSMITH_PROJECT environment variable:

bash
export LANGSMITH_PROJECT=my-agent-project

Dynamically

You can set the project name programmatically for specific operations:

ts
import { LangChainTracer } from "@langchain/core/tracers/tracer_langchain";

const tracer = new LangChainTracer({ projectName: "email-agent-test" });
await agent.invoke(
  {
    messages: [{role: "user", content: "Send a test email to alice@example.com"}]
  },
  { callbacks: [tracer] }
);

Add metadata to traces

You can annotate your traces with custom metadata and tags:

ts
import { LangChainTracer } from "@langchain/core/tracers/tracer_langchain";

const tracer = new LangChainTracer({ projectName: "email-agent-test" });
await agent.invoke(
  {
    messages: [{role: "user", content: "Send a test email to alice@example.com"}]
  },
  {
    tags: ["production", "email-assistant", "v1.0"],
    metadata: {
      userId: "user123",
      sessionId: "session456",
      environment: "production"
    }
  },
);

This custom metadata and tags will be attached to the trace in LangSmith.

TIP

To learn more about how to use traces to debug, evaluate, and monitor your agents, see the LangSmith documentation.