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

# 追踪 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=<your-langsmith-api-key>, Langsmith-Project=livekit-voice
LIVEKIT_URL=<your-livekit-url>
LIVEKIT_API_KEY=<your-livekit-api-key>
LIVEKIT_API_SECRET=<your-livekit-api-secret>
OPENAI_API_KEY=<your-openai-api-key>
```

### 步骤 2：下载 span 处理器

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

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

  **主要功能：**

  * 将 LiveKit span 类型（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

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

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

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

    # 使用自定义 span 处理器创建 tracer provider
    trace_provider = TracerProvider()
    trace_provider.add_span_processor(LangSmithSpanProcessor())

    # 设置为 LiveKit 的 tracer provider
    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-5.4-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 中追踪的示例：[带有 LiveKit 的 LangSmith 追踪](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)。

## 高级用法

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

您可以使用 span 属性为追踪添加自定义元数据：

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

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

        # 获取当前 span 并添加自定义属性
        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")
```

## 故障排除

### Span 未出现在 LangSmith 中

如果追踪未显示在 LangSmith 中：

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

### 消息显示不正确

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

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

### 连接问题

如果您的代理无法连接到 LiveKit：

1. **验证 LiveKit URL**：检查 `LIVEKIT_URL` 在您的 `.env` 文件中设置正确。
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. **检查指令**：确保您的 Agent 具有正确的指令。
4. **查看日志**：在控制台输出中查找错误。

***

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

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