可观测性对于理解智能体在生产环境中的行为至关重要。使用 LangChain 的 create_agent,您可以通过 LangSmith 获得内置的可观测性 - 这是一个用于跟踪、调试、评估和监控 LLM 应用程序的强大平台。 跟踪捕获智能体采取的每一步,从初始用户输入到最终响应,包括所有工具调用、模型交互和决策点。这使您能够调试智能体、评估性能和监控使用情况。

先决条件

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

启用跟踪

所有 LangChain 智能体都自动支持 LangSmith 跟踪。要启用它,请设置以下环境变量:
export LANGSMITH_TRACING=true
export LANGSMITH_API_KEY=<your-api-key>
您可以从您的 LangSmith 设置获取 API 密钥。

快速开始

无需额外代码即可将跟踪记录到 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-4o",
    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 的项目。要配置自定义项目名称,请参阅记录到项目

选择性跟踪

您可以选择使用 LangSmith 的 tracing_context 上下文管理器跟踪应用程序的特定调用或部分:
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"}]})

记录到项目

您可以通过设置 LANGSMITH_PROJECT 环境变量为整个应用程序设置自定义项目名称:
export LANGSMITH_PROJECT=my-agent-project
您可以为特定操作以编程方式设置项目名称:
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"}]
    })

向跟踪添加元数据

您可以使用自定义元数据和标签注释您的跟踪:
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"}]}
    )
此自定义元数据和标签将附加到 LangSmith 中的跟踪。
要了解有关如何使用跟踪来调试、评估和监控智能体的更多信息,请参阅 LangSmith 文档

Connect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.