> ## Documentation Index
> Fetch the complete documentation index at: https://langchain.idochub.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# 可观测性

<Warning>
  **Alpha 版本提示：** 本文档涵盖的是 **v1-alpha** 版本。内容尚不完整，且可能随时变更。

  如需查阅最新稳定版本，请参阅 v0 版本的 [LangChain Python 文档](https://python.langchain.com/docs/introduction/) 或 [LangChain JavaScript 文档](https://js.langchain.com/docs/introduction/)。
</Warning>

可观测性对于理解你的智能体在生产环境中的行为至关重要。借助 LangChain 的 `create_agent()`，你可以通过 [LangSmith](https://smith.langchain.com/) 获得内置的可观测性——一个用于追踪、调试、评估和监控 LLM 应用的强大平台。

追踪记录会捕获智能体执行的每一步，从初始用户输入到最终响应，包括所有的工具调用、模型交互和决策点。这使你能够调试智能体、评估性能并监控使用情况。

## 前置条件

开始之前，请确保你具备以下内容：

* 一个 [LangSmith 账户](https://smith.langchain.com/)（免费注册）

## 启用追踪

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

```bash theme={null}
export LANGSMITH_TRACING=true
export LANGSMITH_API_KEY=<your-api-key>
```

<Info>
  你可以在 [LangSmith 设置](https://smith.langchain.com/settings) 中获取你的 API key。
</Info>

## 快速开始

无需额外代码即可将追踪记录写入 LangSmith。像平常一样运行你的智能体代码即可：

```python theme={null}
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="openai:gpt-4o",
    tools=[send_email, search_web],
    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` 的项目。要配置自定义项目名，请参阅[写入到项目](#log-to-a-specific-project)。

## 选择性追踪

你可以使用 LangSmith 的 `tracing_context` 上下文管理器，对特定的调用或应用的部分进行选择性追踪：

```python theme={null}
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"}]})
```

## 写入到项目

<Accordion title="静态方式">
  你可以通过设置 `LANGSMITH_PROJECT` 环境变量，为整个应用设置自定义项目名：

  ```bash theme={null}
  export LANGSMITH_PROJECT=my-agent-project
  ```
</Accordion>

<Accordion title="动态方式">
  你可以在程序中为特定操作设置项目名：

  ```python theme={null}
  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"}]
      })
  ```
</Accordion>

## 为追踪记录添加元数据

你可以为追踪记录添加自定义元数据和标签：

```python theme={null}
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` 也接受标签和元数据，以实现更精细的控制：

```python theme={null}
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 中的追踪记录。

<Tip>
  要了解更多如何使用追踪来调试、评估和监控你的智能体，请参阅 [LangSmith 文档](/langsmith/home)。
</Tip>
