> ## Documentation Index
> Fetch the complete documentation index at: https://nvd-54.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# LangSmith 可观测性

当你使用 LangChain 构建和运行智能体时，你需要了解它们的行为：它们调用了哪些[工具](/oss/javascript/langchain/tools)、生成了什么提示词以及它们如何做出决策。使用 [`createAgent`](https://reference.langchain.com/javascript/langchain/index/createAgent) 构建的 LangChain 智能体通过 [LangSmith](/langsmith/home) 自动支持追踪，LangSmith 是一个用于捕获、调试、评估和监控 LLM 应用行为的平台。

[*追踪*](/langsmith/observability-concepts#traces)记录智能体执行的每一步，从初始用户输入到最终响应，包括所有工具调用、模型交互和决策点。这些执行数据帮助你调试问题、评估不同输入的性能，并监控生产中的使用模式。

本指南向你展示如何为 LangChain 智能体启用追踪并使用 LangSmith 分析其执行。

## 前提条件

开始之前，请确保你具备以下条件：

* **LangSmith 账户**：在 [smith.langchain.com](https://smith.langchain.com?utm_source=docs\&utm_medium=cta\&utm_campaign=langsmith-signup\&utm_content=oss-langchain-observability) 注册（免费）或登录。
* **LangSmith API 密钥**：按照[创建 API 密钥](/langsmith/create-account-api-key)指南操作。

## 启用追踪

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

```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
export LANGSMITH_TRACING=true
export LANGSMITH_API_KEY=<your-api-key>
```

## 快速入门

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

```ts theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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.4",
    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: "搜索最新的 AI 新闻并将摘要发送到 john@example.com" }]
});
```

默认情况下，追踪将记录到名为 `default` 的项目中。要配置自定义项目名称，请参阅[记录到项目](/langsmith/log-traces-to-project)。

## Trace selectively

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

```ts theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import { LangChainTracer } from "@langchain/core/tracers/tracer_langchain";

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

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

## Log to a project

<Accordion title="Statically">
  You can set a custom project name for your entire application by setting the `LANGSMITH_PROJECT` environment variable:

  ```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  export LANGSMITH_PROJECT=my-agent-project
  ```
</Accordion>

<Accordion title="Dynamically">
  You can set the project name programmatically for specific operations:

  ```ts theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  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] }
  );
  ```
</Accordion>

## Add metadata to traces

You can annotate your traces with custom metadata and tags:

```ts theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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>
  要了解更多关于 how to use traces to debug, evaluate, and monitor your agents, see the [LangSmith documentation](/langsmith/home).
</Tip>

***

<div className="source-links">
  <Callout icon="terminal-2">
    [连接这些文档](/use-these-docs)到 Claude、VSCode 等，通过 MCP 获取实时答案。
  </Callout>

  <Callout icon="edit">
    [在 GitHub 上编辑此页面](https://github.com/langchain-ai/docs/edit/main/src/oss/langchain/observability.mdx)或[提交 Issue](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
