> ## 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.

# 追踪 DeepSeek 应用

[DeepSeek](https://deepseek.com/) 提供高性能、兼容 OpenAI 的语言模型，包括 `deepseek-chat`（用于通用对话）和 `deepseek-reasoner`（用于高级推理任务）。使用 LangSmith 可以捕获输入、输出和元数据的结构化追踪，从而调试、监控和评估你的 LLM 应用。

本指南将展示如何在 Python 和 TypeScript 中将 DeepSeek 与 LangSmith 集成，使用 LangSmith 的 [`@traceable`](https://reference.langchain.com/python/langsmith/run_helpers/traceable)（Python）和 [`traceable(...)`](https://reference.langchain.com/javascript/modules/langsmith.html)（TypeScript）工具自动记录 LLM 调用。

## 安装

安装 [OpenAI](https://platform.openai.com/docs/libraries) 和 LangSmith：

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

  ```bash uv theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  uv add openai langsmith
  ```

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

DeepSeek 提供 [兼容 OpenAI 的 API](https://api-docs.deepseek.com/)，这意味着你可以使用 OpenAI SDK 与 DeepSeek 模型交互。唯一的区别是，你需要将客户端配置为指向 DeepSeek 的基础 URL（`https://api.deepseek.com/v1`），而不是 OpenAI 的端点。

## 设置

设置你的 [API 密钥](/langsmith/create-account-api-key) 和项目名称：

```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
export LANGSMITH_API_KEY="your-langsmith-api-key"
export LANGSMITH_TRACING="true"
export LANGSMITH_PROJECT="deepseek-integration"
export DEEPSEEK_API_KEY="your-deepseek-api-key"
```

* 确保你已从 [DeepSeek 账户](https://platform.deepseek.com/) 获取 DeepSeek API 密钥。
* 设置 `LANGSMITH_TRACING=true` 并提供你的 LangSmith API 密钥（`LANGSMITH_API_KEY`）以激活自动追踪记录。
* 指定一个 [`LANGSMITH_PROJECT`](/langsmith/log-traces-to-project) 名称以按项目组织追踪；如果未设置，追踪将进入默认项目（名为 "default"）。
* `LANGSMITH_TRACING` 标志必须为 true 才能记录任何追踪。

## 配置追踪

1. 使用 LangSmith 对 DeepSeek API 调用进行插桩。在你的脚本中，创建一个配置为使用 DeepSeek API 端点的 OpenAI 客户端，并将调用包装在一个被追踪的函数中：

   <CodeGroup>
     ```python Python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
     import os
     from openai import OpenAI
     from langsmith import traceable

     # 创建指向 DeepSeek 的客户端
     client = OpenAI(
         api_key=os.environ["DEEPSEEK_API_KEY"],
         base_url="https://api.deepseek.com/v1"
     )

     @traceable(
         run_type="llm",
         name="DeepSeek Chat Completion",
         metadata={"ls_provider": "deepseek", "ls_model_name": "deepseek-chat"},
     )
     def call_deepseek(messages: list[dict]):
         response = client.chat.completions.create(
             model="deepseek-chat",
             messages=messages
         )
         return response.choices[0].message

     if __name__ == "__main__":
         messages = [
             {"role": "system", "content": "You are a helpful assistant that translates English to French."},
             {"role": "user", "content": "I love programming."}
         ]
         result = call_deepseek(messages=messages)
         print("Model reply:", result.content)
     ```

     ```typescript TypeScript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
     import { config } from "dotenv";
     import OpenAI from "openai";
     import { traceable } from "langsmith/traceable";

     config(); // 从 .env 加载环境变量

     const openai = new OpenAI({
     apiKey: process.env.DEEPSEEK_API_KEY,
     baseURL: "https://api.deepseek.com/v1"
     });

     type ChatMessage = {
     role: "system" | "user" | "assistant";
     content: string;
     };

     const callDeepSeek = traceable(
     async (messages: ChatMessage[]) => {
         const response = await openai.chat.completions.create({
         model: "deepseek-chat",
         messages
         });

         return response.choices[0].message;
     },
     {
         name: "DeepSeek Chat Completion",
         run_type: "llm",
         metadata: {
         ls_provider: "deepseek",
         ls_model_name: "deepseek-chat"
         }
     }
     );

     (async () => {
     const messages: ChatMessage[] = [
         {
         role: "system",
         content: "You are a helpful assistant that translates English to French."
         },
         {
         role: "user",
         content: "I love programming."
         }
     ];

     const result = await callDeepSeek(messages);
     console.log("Model reply:", result.content);
     })();

     ```
   </CodeGroup>

   在此示例中，你使用 OpenAI SDK 与 [DeepSeek 的 API](https://api-docs.deepseek.com/) 交互。OpenAI 客户端配置了 `base_url="https://api.deepseek.com/v1"`，以将请求路由到 DeepSeek 的端点，同时保持与 OpenAI 兼容的语法。

   `@traceable` 装饰器（Python）或 `traceable` 函数（TypeScript）包装了你的函数，以便每次调用都被记录为类型为 `"llm"` 的追踪运行。`metadata` 参数为追踪添加了以下标签：

   * `ls_provider`：标识提供商（DeepSeek），用于筛选追踪。
   * `ls_model_name`：指定用于成本跟踪和分析的模型。

   该函数返回完整的消息对象（`response.choices[0].message`），其中包括响应内容以及角色和任何其他字段的元数据。LangSmith 会自动捕获：

   * 发送到模型的输入消息。
   * 模型的完整响应（内容、角色等）。
   * 模型名称和令牌使用统计。
   * 执行时间和任何错误。

2. 执行你的脚本以生成追踪：

   <CodeGroup>
     ```bash Python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
     python deepseek_trace.py
     ```

     ```bash TypeScript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
     node deepseek_trace.js
     ```
   </CodeGroup>

   函数调用将访问 DeepSeek 的 API，并且由于 `@traceable`/`traceable` 包装器，LangSmith 会将此调用的输入和输出记录为新的追踪。你将在控制台看到模型的响应，并在 [LangSmith UI](https://smith.langchain.com) 中看到相应的运行记录。

## 在 LangSmith 中查看追踪

运行示例后，你可以在 [LangSmith UI](https://smith.langchain.com) 中检查记录的追踪：

1. 打开 LangSmith UI 并登录你的账户。
2. 选择你用于此集成的项目（例如，在 `LANGSMITH_PROJECT` 中设置的名称，如果未设置，则为 "default"）。
3. 找到与你的 DeepSeek API 调用对应的追踪。它将通过函数名称（`DeepSeek Chat Completion`）标识。
4. 点击追踪以打开它。你将能够检查模型输入和输出，包括你发送的提示消息和 DeepSeek 的响应，以及时间信息（延迟）和令牌使用情况。

借助 LangSmith 的追踪功能，你可以完全了解 DeepSeek 调用——从而调试 DeepSeek 模型的行为、监控性能（响应时间和令牌使用情况），并比较不同参数的运行。

## 成本跟踪

尽管 DeepSeek 模型是开放权重的，但使用托管的 DeepSeek API 可能会根据你的计划产生基于使用量的费用。

LangSmith 可以通过估计令牌使用量并应用特定于模型的定价，自动将成本与追踪的 LLM 调用关联起来。在追踪 DeepSeek API 调用时，LangSmith 使用记录的提示和响应消息来计算令牌数量，并将成本信息附加到每个运行中。

要为 LLM 调用启用自动成本跟踪，请参阅 [基于令牌数量自动跟踪成本](/langsmith/cost-tracking#llm-calls:-automatically-track-costs-based-on-token-counts)。

启用后，成本将直接显示在 LangSmith UI 中每个追踪的 DeepSeek 运行旁边，使你能够监控使用情况并比较不同时间的实验。

***

<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-deepseek.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>
