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

# 追踪 Deep Agents 应用

[`deepagents`](/oss/python/deepagents/overview) 是一个基于 LangGraph 构建的开源智能体框架，专为需要规划、工具使用和子智能体委派的复杂多步骤任务而设计。Deep Agents 支持原生的 LangSmith 追踪功能。

本指南将向您展示如何为 Deep Agents 启用 LangSmith 追踪，在 LangSmith UI 中查看追踪记录，以及（可选）为更高级的用例自定义追踪配置。

## 安装

在您的 Python 环境中安装 `deepagents`：

<CodeGroup>
  ```bash pip theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  pip install deepagents
  ```

  ```bash uv theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  uv add deepagents
  ```
</CodeGroup>

`deepagents` 需要：

* Python 3.11+。
* 支持工具调用的 LLM（例如，OpenAI 或 Anthropic 模型）。
* 对于追踪功能，需要一个 [LangSmith 账户和 API 密钥](/langsmith/create-account-api-key)（免费注册）。

<Note>
  您不需要安装 `langsmith` Python 包来追踪 Deep Agents。`deepagents` 基于 LangGraph 构建，后者包含了原生的 LangSmith 追踪支持。只要设置了 LangSmith 环境变量，追踪记录就会自动发送。

  只有在您需要[对追踪进行编程控制](#customize-langsmith-tracing)时（例如，使用 `tracing_context`、添加自定义元数据或从 Python 查询运行记录），才需要安装 `langsmith` 包。
</Note>

## 设置

您可以在 [LangSmith UI](https://smith.langchain.com) 的 **Settings** 下找到您的 LangSmith API 密钥和项目名称：

```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
export LANGSMITH_API_KEY=<您的-langsmith-api-密钥>
export LANGSMITH_TRACING=true
export LANGSMITH_PROJECT=<您的项目名称>
```

## 创建追踪记录

一旦通过环境变量启用追踪，Deep Agents 将自动向 LangSmith 发送追踪记录。例如：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from typing import Dict, Any, List

from deepagents import create_deep_agent


def compute_compound_interest(
    principal: float,
    annual_rate: float,
    years: int,
    compounds_per_year: int,
) -> Dict[str, Any]:
    """计算复利并返回期末余额和赚取的利息。"""
    r = annual_rate
    n = compounds_per_year
    t = years
    amount = principal * (1 + r / n) ** (n * t)
    interest = amount - principal
    return {
        "principal": principal,
        "annual_rate": annual_rate,
        "years": years,
        "compounds_per_year": n,
        "ending_balance": round(amount, 2),
        "interest_earned": round(interest, 2),
    }


def yearly_balance_schedule(
    principal: float,
    annual_rate: float,
    years: int,
    compounds_per_year: int,
) -> List[Dict[str, Any]]:
    """返回投资的逐年余额计划表。"""
    r = annual_rate
    n = compounds_per_year
    schedule: List[Dict[str, Any]] = []

    for year in range(1, years + 1):
        amount = principal * (1 + r / n) ** (n * year)
        schedule.append(
            {
                "year": year,
                "ending_balance": round(amount, 2),
                "interest_earned": round(amount - principal, 2),
            }
        )

    return schedule


agent = create_deep_agent(
    tools=[compute_compound_interest, yearly_balance_schedule],
    system_prompt=(
        "你是一个细心的助手。"
        "使用工具进行计算和结构化输出。"
        "返回简洁的最终答案。"
    ),
)

result = agent.invoke(
    {
        "messages": [
            {
                "role": "user",
                "content": (
                    "我有 2,500 美元投资，年利率 6%，按月复利，投资 5 年。\n"
                    "1) 计算期末余额和赚取的总利息。\n"
                    "2) 生成逐年期末余额计划表。\n"
                    "然后用 3 个要点总结关键信息。\n\n"
                    "使用 compounds_per_year=12。"
                ),
            }
        ]
    }
)

print(result)
```

## 查看追踪记录

### 详情视图

点击追踪记录，并在右上角切换到 **Details** 视图。您在 [LangSmith UI](https://smith.langchain.com) 中的追踪树将看起来像[这样](https://smith.langchain.com/public/ec82be64-b158-425e-a959-924be16b8588/r)，并具有以下结构：

* 智能体运行（顶层）代表完整的 Deep Agents 调用。
* LLM 调用：智能体分析用户请求并决定使用哪些工具。
* 工具运行：`compute_compound_interest`：
  * 显示工具输入（例如，本金、年利率、年限和每年复利次数）。
  * 显示结构化输出，包括期末余额和赚取的总利息。
* LLM 调用：解释计算结果并确定下一步。
* 工具运行：`yearly_balance_schedule`：
  * 显示用于生成计划表的输入。
  * 返回逐年细分的期末余额和赚取的利息。
* 最终的 LLM 响应：为用户总结结果。

生成的追踪记录包含多个嵌套的跨度，这使您可以在 LangSmith UI 中跟踪智能体的规划、计算步骤和解释流程。

### 消息视图

LangSmith UI 中的 **Messages** 视图显示了用户与智能体之间简化的对话历史。此视图从顶层追踪中提取消息（包括用户的初始请求、工具调用和智能体的最终响应），并以类似聊天的格式呈现它们。

## 自定义 LangSmith 追踪

默认情况下，当通过环境变量启用 LangSmith 追踪时，Deep Agents 的追踪记录会自动发送。您可以直接使用 [LangSmith SDK](https://reference.langchain.com/python/langsmith/observability/sdk/) 来自定义追踪，例如将追踪范围限定在部分代码、附加标签或元数据，或覆盖项目名称。

如果您想执行以下操作，请安装并使用 `langsmith`：

* 仅追踪特定的智能体调用。
* 添加自定义标签或元数据以便在 UI 中筛选。
* 在运行时覆盖项目名称。

<CodeGroup>
  ```bash pip theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  pip install langsmith
  ```

  ```bash uv theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  uv add langsmith
  ```
</CodeGroup>

此示例调用了同一个深度智能体两次：

* 第一次调用未被追踪，因为它运行在 `tracing_context` 之外。
* 第二次调用被追踪，因为它运行在 `tracing_context(enabled=True, ...)` 内部。

您可以选择性地仅追踪工作流的一部分，而无需通过 `LANGSMITH_TRACING=true` 为整个进程启用全局追踪：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from typing import Dict, Any, List

import langsmith as ls
from deepagents import create_deep_agent


def compute_compound_interest(
    principal: float,
    annual_rate: float,
    years: int,
    compounds_per_year: int,
) -> Dict[str, Any]:
    """计算复利并返回期末余额和赚取的利息。"""
    r = annual_rate
    n = compounds_per_year
    t = years
    amount = principal * (1 + r / n) ** (n * t)
    interest = amount - principal
    return {
        "principal": principal,
        "annual_rate": annual_rate,
        "years": years,
        "compounds_per_year": n,
        "ending_balance": round(amount, 2),
        "interest_earned": round(interest, 2),
    }


def yearly_balance_schedule(
    principal: float,
    annual_rate: float,
    years: int,
    compounds_per_year: int,
) -> List[Dict[str, Any]]:
    """返回投资的逐年余额计划表。"""
    r = annual_rate
    n = compounds_per_year
    schedule: List[Dict[str, Any]] = []

    for year in range(1, years + 1):
        amount = principal * (1 + r / n) ** (n * year)
        schedule.append(
            {
                "year": year,
                "ending_balance": round(amount, 2),
                "interest_earned": round(amount - principal, 2),
            }
        )

    return schedule


agent = create_deep_agent(
    tools=[compute_compound_interest, yearly_balance_schedule],
    system_prompt=(
        "你是一个细心的助手。"
        "使用工具进行计算和结构化输出。"
        "返回简洁的最终答案。"
    ),
)

# ----------------------------
# 未被追踪的调用
# ----------------------------
agent.invoke(
    {
        "messages": [
            {
                "role": "user",
                "content": (
                    "我有 2,500 美元投资，年利率 6%，按月复利，投资 5 年。"
                    "计算期末余额和赚取的总利息。"
                    "使用 compounds_per_year=12。"
                ),
            }
        ]
    }
)

# ----------------------------
# 被追踪的调用
# ----------------------------
with ls.tracing_context(
    enabled=True,
    project_name="deepagents-demo",
    tags=["deepagents", "scoped-tracing"],
    metadata={"example": "partial-workflow"},
):
    agent.invoke(
        {
            "messages": [
                {
                    "role": "user",
                    "content": (
                        "我有 2,500 美元投资，年利率 6%，按月复利，投资 5 年。\n"
                        "1) 计算期末余额和赚取的总利息。\n"
                        "2) 生成逐年期末余额计划表。\n"
                        "然后用 3 个要点总结关键信息。\n\n"
                        "使用 compounds_per_year=12。"
                    ),
                }
            ]
        }
    )
```

`tracing_context` 代码块启用追踪，并配置追踪记录在 LangSmith 中的记录和组织方式：

* `enabled=True` 显式启用该代码块期间的追踪，即使 `LANGSMITH_TRACING` 未设置或设置为 `false`。
* `project_name="deepagents-demo"` 将此代码块中的追踪记录路由到指定的 [LangSmith 项目](/langsmith/log-traces-to-project)。这会覆盖在上下文中创建的运行的 `LANGSMITH_PROJECT`。
* `tags=[...]` 将标签附加到被追踪的运行上。[标签](/langsmith/add-metadata-tags)会出现在 [LangSmith UI](https://smith.langchain.com) 中，您可以用它们来筛选和分组追踪记录。
* `metadata={...}` 附加任意的结构化元数据（例如，环境、实验名称或功能标志）。

在此示例中，智能体被调用了两次，但只有 `tracing_context` 内部的调用被记录。这演示了如何选择性地追踪 Deep Agents 工作流的特定部分，而无需为整个进程启用全局追踪。

***

<div className="source-links">
  <Callout icon="edit">
    [Edit this page on GitHub](https://github.com/langchain-ai/docs/edit/main/src/i18n\zh-CN\langsmith\trace-deep-agents.mdx) or [file an issue](https://github.com/langchain-ai/docs/issues/new/choose).
  </Callout>

  <Callout icon="terminal-2">
    [Connect these docs](/use-these-docs) to Claude, VSCode, and more via MCP for real-time answers.
  </Callout>
</div>
