跳到主要内容
可观测性对于了解您的代理在生产中的行为至关重要。通过 LangChain 的 create_agent,您可以通过 LangSmith 获得内置的可观测性——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

# 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"}]})

记录到项目

您可以通过设置 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 也接受标签和元数据以进行精细控制
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 文档

以编程方式连接这些文档到 Claude、VSCode 等,通过 MCP 获取实时答案。
© . This site is unofficial and not affiliated with LangChain, Inc.