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

# 追踪 LiteLLM 应用

[LiteLLM](https://www.litellm.ai/) 提供了一个统一的接口，用于通过一致的 OpenAI 兼容 API 调用 LLM 提供商。它既可以作为 [Python SDK](https://docs.litellm.ai/docs/#litellm-python-sdk) 直接嵌入到你的应用中，也可以作为 [代理服务器](https://docs.litellm.ai/docs/simple_proxy) 为客户端应用暴露一个 OpenAI 兼容的端点。

本指南将向你展示如何使用以下方式通过 LangSmith 追踪 LiteLLM 调用：

* 使用 [LangSmith SDK](#use-langsmith_tracing-and-traceable) (`@traceable`) 进行应用级追踪。
* 使用 [LiteLLM 内置的 langsmith 回调](#log-litellm-call-with-the-langsmith-callback) 进行模型级日志记录。
* 使用 [LiteLLM 代理](#use-the-litellm-proxy) 进行网关级追踪。

## 安装

使用 LiteLLM Python SDK 或 LiteLLM 代理时，请安装以下内容：

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

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

本指南中的示例使用 OpenAI 模型，但你可以为你的用例安装必要的提供商。

## 使用 LiteLLM Python SDK

LiteLLM 支持两种将追踪发送到 LangSmith 的方式，它们在不同的层面上运行：

* [LangSmith SDK 追踪](#use-langsmith_tracing-and-traceable)：通过设置 `LANGSMITH_TRACING=true` 启用应用级追踪。当你想追踪更广泛的业务逻辑、多步骤管道或使用 `@traceable` 创建的 span 时，这很有用。
* LiteLLM 内置的 [`langsmith` 回调](#log-litellm-call-with-the-langsmith-callback)：直接从 LiteLLM 记录模型调用。当你想专门追踪 LiteLLM 请求或运行异步应用时，推荐使用此方式。

<Note>
  避免为相同的 LiteLLM 调用同时启用 LiteLLM 的 `langsmith` 回调和 LangSmith 追踪，因为这可能导致重复的追踪。
</Note>

### 使用 `LANGSMITH_TRACING` 和 `traceable`

你可以将 `LANGSMITH_TRACING=true` 与 `@traceable` 一起使用，以在 LangSmith 中获得可预测的追踪。这种方法确保 **输入** 和 **输出** 列反映你的函数参数和返回值，允许你保留完整的消息结构（包括 `role` 和 `content`）。它在简单的同步脚本中也能可靠地工作，无需 asyncio 事件循环或额外的回调配置。

1. 设置以下环境变量，为 LiteLLM Python SDK 用法启用 LangSmith 追踪：

   ```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
   export LANGSMITH_API_KEY="your_api_key"
   export LANGSMITH_PROJECT="litellm-integration"
   export LANGSMITH_TRACING="true"
   ```

   在 [LangSmith UI](https://smith.langchain.com) 中创建 LangSmith [API 密钥](/langsmith/create-account-api-key)。

   根据你使用的提供商，你还需要设置 API 密钥：

   ```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
   export OPENAI_API_KEY="your_openai_key"
   ```

2. 将以下代码添加到你的脚本文件中：

   ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
   from langsmith import traceable
   from litellm import completion

   @traceable(name="LiteLLM Chat Completion")
   def run(messages):
       response = completion(
           model="gpt-4o",
           messages=messages,
       )
       # 返回助手消息，以便 LangSmith UI 显示 role + content
       return response["choices"][0]["message"]

   messages = [
       {"role": "user", "content": "Explain observability in LLM systems."}
   ]

   result = run(messages)
   print(result["content"])
   ```

   `@traceable` 将你的函数作为 LangSmith 运行进行检测。当设置 `LANGSMITH_TRACING=true` 时，LangSmith 会自动：

   * 在函数被调用时创建一个运行。
   * 将函数参数记录为运行输入。
   * 执行函数体（包括 LiteLLM 调用）。
   * 将函数的返回值记录为运行输出。
   * 捕获计时、错误和嵌套的 span（如果有）。

   在此示例中，`messages` 参数成为追踪输入，返回的助手消息对象成为追踪输出。LiteLLM 调用本身正常运行——`@traceable` 通过可观测性包装它，而不是修改其行为。这种方法追踪的是你的应用逻辑，而不仅仅是模型调用。

   <Tip>
     有关使用 `@traceable` 的更多通用示例，请参阅 [自定义检测](/langsmith/annotate-code#use-@traceable-/-traceable) 页面。
   </Tip>

### 使用 `langsmith` 回调记录 LiteLLM 调用

LiteLLM 可以使用其内置的 [回调系统](https://docs.litellm.ai/docs/observability/callbacks) 直接将追踪发送到 LangSmith。当你在异步 Python 服务中运行 LiteLLM，并且希望 LiteLLM 本身发出模型级日志时，这很有用。

LiteLLM 回调在异步环境中运行。使用 `litellm.acompletion()` 进行异步调用时，你可以启用 `langsmith` 回调来记录成功的模型调用。

<Tip>
  此方法最适合异步应用。对于简单的同步脚本，请使用 [上一节](#use-langsmith_tracing-and-traceable) 中显示的 `@traceable` 方法。
</Tip>

1. 设置以下环境变量：

   ```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
   export LANGSMITH_API_KEY="your_api_key"
   export LANGSMITH_PROJECT="litellm-integration"
   ```

   在 [LangSmith UI](https://smith.langchain.com) 中创建 LangSmith [API 密钥](/langsmith/create-account-api-key)。

   根据你使用的提供商，你还需要设置 API 密钥：

   ```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
   export OPENAI_API_KEY="your_openai_key"
   ```

2. 要在最小脚本中运行此操作：

   * 使用 `acompletion()`（异步 API）。
   * 使用 `asyncio.run(...)` 运行以创建事件循环。
   * 设置 `langsmith_batch_size = 1` 以立即刷新。

   ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
   import asyncio
   import litellm
   from litellm import acompletion

   # 启用 LiteLLM → LangSmith 回调
   litellm.success_callback = ["langsmith"]

   # 对于短期运行的脚本，立即发送而不是等待批量刷新
   litellm.langsmith_batch_size = 1

   async def main():
       response = await acompletion(
           model="gpt-4o",
           messages=[
               {"role": "user", "content": "Explain observability in LLM systems."}
           ],
       )

       # 打印助手消息内容以进行本地验证
       print(response["choices"][0]["message"]["content"])

       # 在进程退出前留出时间让后台记录器刷新
       await asyncio.sleep(1)

   if __name__ == "__main__":
       asyncio.run(main())
   ```

   该回调将 LiteLLM 的模型请求和响应数据直接发送到 LangSmith，包括提供商元数据和令牌使用情况。由于 LiteLLM 控制有效负载，与 `@traceable` 示例相比，**输入** 和 **输出** 列可能包含额外的元数据。

## 使用 LiteLLM 代理

LiteLLM 代理作为独立服务器运行，并暴露一个 OpenAI 兼容的 API。

1. 要让代理直接将请求记录到 LangSmith，请在 `config.yaml` 中配置回调：

   ```yaml theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
   model_list:
     - model_name: gpt-4o
       litellm_params:
         model: openai/gpt-4o

   litellm_settings:
     callbacks: ["langsmith"]
   ```

2. 在你的代理环境中设置环境变量：

   ```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
   export LANGSMITH_API_KEY="your_api_key"
   export LANGSMITH_PROJECT="litellm-proxy"
   export OPENAI_API_KEY="your_openai_key"
   ```

   <Note>
     LiteLLM 代理作为单独的服务运行。如果你在代理级别启用 LangSmith 追踪，必须在代理的运行时环境中配置 `LANGSMITH_API_KEY` 和相关环境变量。这些设置不会与你的应用进程共享。
   </Note>

3. 启动代理：

   ```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
   litellm --config config.yaml
   ```

   默认情况下，代理在 `http://localhost:4000/v1` 运行。你的应用使用任何 OpenAI 兼容客户端（Python、JavaScript、curl 等）调用它。

   启用 `callbacks: ["langsmith"]` 后，代理会将模型请求和响应数据直接发送到 LangSmith。客户端应用中无需进行追踪配置。

4. 从另一个终端窗口调用代理：

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

     client = OpenAI(
         base_url="http://localhost:4000/v1",
         api_key="anything"  # 代理可能需要密钥，但默认情况下不验证
     )

     response = client.chat.completions.create(
         model="gpt-4o",
         messages=[
             {"role": "user", "content": "What is LiteLLM?"}
         ],
     )

     print(response.choices[0].message.content)
     ```

     ```javascript JavaScript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
     import OpenAI from "openai";

     const client = new OpenAI({
     apiKey: "anything",
     baseURL: "http://localhost:4000/v1",
     });

     const response = await client.chat.completions.create({
     model: "gpt-4o",
     messages: [
         { role: "user", content: "Explain LiteLLM tracing." }
     ],
     });

     console.log(response.choices[0].message.content);
     ```
   </CodeGroup>

   客户端发送正常的聊天补全请求，代理处理提供商路由和响应格式化。

## 后续步骤

* [在 LangSmith 中查看追踪](/langsmith/filter-traces-in-application)
* [添加自定义元数据](/langsmith/ls-metadata-parameters)
* [过滤和采样追踪](/langsmith/sample-traces)

***

<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/langsmith/trace-litellm.mdx) 或 [提交问题](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
