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

# 追踪 LiveKit 应用

LangSmith 可以通过 OpenTelemetry 工具捕获 [LiveKit Agents](https://docs.livekit.io/agents/) 生成的追踪数据。本指南将展示如何自动捕获来自 LiveKit 语音 AI 智能体的追踪数据，并将其发送到 LangSmith 进行监控和分析。

完整实现请参考 [演示仓库](https://github.com/langchain-ai/voice-agents-tracing)。

## 安装

安装所需的包：

<CodeGroup>
  ```bash pip theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  pip install langsmith livekit livekit-agents livekit-plugins-openai livekit-plugins-silero livekit-plugins-turn-detector opentelemetry-exporter-otlp python-dotenv
  ```

  ```bash uv theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  uv add langsmith livekit livekit-agents livekit-plugins-openai livekit-plugins-silero livekit-plugins-turn-detector opentelemetry-exporter-otlp python-dotenv
  ```
</CodeGroup>

## 快速入门教程

按照这个分步教程，创建一个带有 LiveKit 和 LangSmith 追踪功能的语音 AI 智能体。您将通过复制粘贴代码片段来构建一个完整的工作示例。

### 步骤 1：设置环境

在项目目录中创建一个 `.env` 文件：

```bash .env theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
OTEL_EXPORTER_OTLP_ENDPOINT=https://api.smith.langchain.com/otel
OTEL_EXPORTER_OTLP_HEADERS=x-api-key=<你的-langsmith-api-key>, Langsmith-Project=livekit-voice
LIVEKIT_URL=<你的-livekit-url>
LIVEKIT_API_KEY=<你的-livekit-api-key>
LIVEKIT_API_SECRET=<你的-livekit-api-secret>
OPENAI_API_KEY=<你的-openai-api-key>
```

### 步骤 2：下载跨度处理器

添加启用 LangSmith 追踪的 [自定义跨度处理器文件](https://github.com/langchain-ai/voice-agents-tracing/blob/main/livekit/langsmith_processor.py)。将其保存为项目目录中的 `langsmith_processor.py`。

<Accordion title="跨度处理器的作用是什么？">
  跨度处理器用 LangSmith 兼容的属性来丰富 LiveKit Agents 的 OpenTelemetry 跨度，以便您的追踪数据能在 LangSmith 中正确显示。

  **主要功能：**

  * 将 LiveKit 跨度类型（stt、llm、tts、agent、session、job）转换为 LangSmith 格式。
  * 为消息可视化添加 `gen_ai.prompt.*` 和 `gen_ai.completion.*` 属性。
  * 跨对话轮次跟踪和聚合对话消息。
  * 使用多种提取策略来处理各种 LiveKit 属性格式。

  当您在代码中导入该处理器时，它会自动激活。
</Accordion>

### 步骤 3：创建您的语音智能体文件

创建一个名为 `agent.py` 的新文件，并添加以下代码。我们将分部分构建它，以便您可以复制粘贴每个部分。

#### 第 1 部分：导入依赖项并设置追踪

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import sys
import os
from pathlib import Path
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()

# 导入 LiveKit 组件
from livekit import agents
from livekit.agents import AgentServer, AgentSession, Agent
from livekit.agents.telemetry import set_tracer_provider
from livekit.plugins import silero
from livekit.plugins.turn_detector.multilingual import MultilingualModel
from opentelemetry.sdk.trace import TracerProvider

# 导入跨度处理器以启用 LangSmith 追踪
from langsmith_processor import LangSmithSpanProcessor

# 设置 LangSmith 追踪
def setup_langsmith():
    """设置 OpenTelemetry 追踪以将跨度导出到 LangSmith。"""
    endpoint = os.getenv("OTEL_EXPORTER_OTLP_ENDPOINT")
    headers = os.getenv("OTEL_EXPORTER_OTLP_HEADERS")

    if not endpoint or not headers:
        print("⚠️  警告：未设置 OTEL 环境变量。追踪已禁用。")
        return

    # 创建带有自定义跨度处理器的追踪器提供者
    trace_provider = TracerProvider()
    trace_provider.add_span_processor(LangSmithSpanProcessor())

    # 设置为 LiveKit 的追踪器提供者
    set_tracer_provider(trace_provider)
    print("✅ LangSmith 追踪已启用")

# 在创建智能体之前启用追踪
setup_langsmith()
```

#### 第 2 部分：定义您的智能体

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
class Assistant(Agent):
    def __init__(self) -> None:
        super().__init__(
            instructions="""您是一个乐于助人的语音 AI 助手。
            您热切地帮助用户解答问题。
            保持回答简洁且对话式。""",
        )
```

#### 第 3 部分：设置智能体服务器

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
server = AgentServer()

@server.rtc_session()
async def my_agent(ctx: agents.JobContext):
    # 创建带有 STT、LLM、TTS 和 VAD 的智能体会话
    session = AgentSession(
        stt="deepgram/nova-2:en",
        llm="openai/gpt-4.1-mini",
        tts=openai.TTS(model="tts-1", voice="alloy"),
        vad=silero.VAD.load(),
        turn_detection=MultilingualModel(),
    )

    # 启动会话
    await session.start(
        room=ctx.room,
        agent=Assistant(),
    )

if __name__ == "__main__":
    # 在控制台模式下运行以进行本地测试
    sys.argv = [sys.argv[0], "console"]
    agents.cli.run_app(server)
```

### 步骤 4：运行您的智能体

在控制台模式下运行您的语音智能体以进行本地测试：

```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
python agent.py console
```

您的智能体将启动并连接到 LiveKit。通过麦克风说话，所有追踪数据将自动出现在 LangSmith 中。以下是 LangSmith 中追踪数据的示例：[LangSmith 中的 LiveKit 追踪](https://smith.langchain.com/public/0f583c03-6d2a-4a2c-a043-9588e387cb55/r)

查看完整的 [agent.py 代码](https://github.com/langchain-ai/voice-agents-tracing/blob/main/livekit/agent.py)。

## 高级用法

### 自定义元数据和标签

您可以使用跨度属性向追踪数据添加自定义元数据：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from opentelemetry import trace

class Assistant(Agent):
    def __init__(self) -> None:
        super().__init__(
            instructions="您是一个乐于助人的助手。",
        )

        # 获取当前跨度并添加自定义属性
        tracer = trace.get_tracer(__name__)
        span = trace.get_current_span()
        if span:
            span.set_attribute("langsmith.metadata.agent_type", "voice_assistant")
            span.set_attribute("langsmith.metadata.version", "1.0")
            span.set_attribute("langsmith.span.tags", "livekit,voice-ai,production")
```

## 故障排除

### 跨度未出现在 LangSmith 中

如果追踪数据未显示在 LangSmith 中：

1. **验证环境变量**：确保 `.env` 文件中正确设置了 `OTEL_EXPORTER_OTLP_ENDPOINT` 和 `OTEL_EXPORTER_OTLP_HEADERS`。
2. **检查设置顺序**：确保在创建 `AgentServer` **之前** 调用 `setup_langsmith()`。
3. **检查 API 密钥**：确认您的 LangSmith API 密钥具有写入权限。
4. **查找确认信息**：启动时应在控制台中看到 "✅ LangSmith 追踪已启用"。

### 消息未正确显示

如果对话消息未正确显示：

1. **检查跨度处理器**：确认 `langsmith_processor.py` 在您的项目目录中且导入正确。
2. **验证导入**：确保在您的 agent.py 中导入了 `LangSmithSpanProcessor`。
3. **启用调试日志**：在环境中设置 `LANGSMITH_PROCESSOR_DEBUG=true` 以查看详细日志。

### 连接问题

如果您的智能体无法连接到 LiveKit：

1. **验证 LiveKit URL**：检查 `.env` 文件中的 `LIVEKIT_URL` 是否正确设置。
2. **检查凭据**：确保 `LIVEKIT_API_KEY` 和 `LIVEKIT_API_SECRET` 正确。
3. **测试连接**：首先尝试使用 LiveKit CLI 连接到您的 LiveKit 服务器。
4. **控制台模式**：对于本地测试，始终使用：`python agent.py console`。

### 导入错误

如果遇到导入错误：

1. **安装依赖项**：运行步骤 1 中的完整 pip install 命令。
2. **检查 Python 版本**：确保您使用的是 Python 3.9 或更高版本。
3. **验证 langsmith\_processor**：确保 `langsmith_processor.py` 已下载并与 `agent.py` 位于同一目录。
4. **检查 LiveKit 插件**：确保您为 STT/LLM/TTS 提供商安装了正确的 LiveKit 插件。

### 智能体无响应

如果您的智能体已连接但无响应：

1. **检查 API 密钥**：验证您的 OpenAI API 密钥（或其他提供商密钥）是否正确。
2. **测试服务**：确保您的 STT、LLM 和 TTS 服务可访问。
3. **检查指令**：确保您的智能体具有正确的指令。
4. **查看日志**：在控制台输出中查找错误信息。

***

<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-with-livekit.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>
