LangSmith 可以捕获由 LiveKit Agents 生成的追踪。 本指南将展示如何从您的 LiveKit 语音 AI 代理自动捕获追踪并将其发送到 LangSmith 进行监控和分析。
有关追踪语音代理的高级指导原则,请参阅 语音追踪基础.
有关完整实现,请参阅 语音演示仓库.
安装
安装所需的包:
pip install langsmith livekit livekit-agents livekit-plugins-openai livekit-plugins-silero livekit-plugins-turn-detector opentelemetry-exporter-otlp python-dotenv
uv add langsmith livekit livekit-agents livekit-plugins-openai livekit-plugins-silero livekit-plugins-turn-detector opentelemetry-exporter-otlp python-dotenv
快速入门教程
按照此分步教程创建带有 LiveKit 和 LangSmith 追踪的语音 AI 代理。您将通过复制和粘贴代码片段来构建一个完整的可工作示例。
步骤 1:设置您的环境
在您的项目目录中创建一个 .env 文件:
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:下载跨度处理器
LiveKit 发出 OpenTelemetry 跨度,但大部分有用数据位于 LiveKit 特定属性中,LangSmith 默认无法识别这些属性。自定义跨度处理器会转换这些属性,以便您的追踪在 LangSmith 中正确呈现。
添加 自定义跨度处理器文件 并将其保存为 langsmith_processor.py 在您的项目目录中。
What does the span processor do?
跨度处理器使用与 LangSmith 兼容的属性丰富 LiveKit Agents 的 OpenTelemetry 跨度,以便您的追踪在 LangSmith 中正确显示。
关键功能:
- - 将 LiveKit 跨度类型(stt、llm、tts、agent、session、job)转换为 LangSmith 格式。
- - 添加
gen_ai.prompt.*和gen_ai.completion.*属性用于消息可视化。 - - 将 LiveKit 的指标(首次令牌时间、首次字节时间、端到端延迟以及其他
lk.*分析数据)作为运行元数据公开。 - - 跨对话追踪和聚合对话消息。
- - 渲染整个对话转录并将通话录音附加到根运行。
它只重塑其识别为 LiveKit 的跨度;任何其他跨度(例如,嵌套的 LangChain 或 LangGraph 运行)都会原样通过。处理器在您导入代码时激活。
步骤 3:创建您的语音代理文件
创建一个名为 agent.py 的新文件并添加以下代码。我们将逐步构建它,以便您可以复制和粘贴每个部分。
第 1 部分:导入依赖项并设置追踪
from pathlib import Path
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Import LiveKit components
from livekit import agents
from livekit.agents import AgentServer, AgentSession, Agent
from livekit.agents.telemetry import set_tracer_provider
from livekit.plugins import openai, silero
from livekit.plugins.turn_detector.multilingual import MultilingualModel
from opentelemetry.sdk.trace import TracerProvider
# Import span processor to enable LangSmith tracing
from langsmith_processor import LangSmithSpanProcessor
# Set up LangSmith tracing
def setup_langsmith():
"""Setup OpenTelemetry tracing to export spans to LangSmith."""
endpoint = os.getenv("OTEL_EXPORTER_OTLP_ENDPOINT")
headers = os.getenv("OTEL_EXPORTER_OTLP_HEADERS")
if not endpoint or not headers:
print("⚠️ Warning: OTEL environment variables not set. Tracing disabled.")
return
# Create tracer provider with custom span processor
trace_provider = TracerProvider()
trace_provider.add_span_processor(LangSmithSpanProcessor())
# Set as LiveKit's tracer provider
set_tracer_provider(trace_provider)
print("✅ LangSmith tracing enabled")
# Enable tracing before creating agents
setup_langsmith()
第 2 部分:定义您的代理
class Assistant(Agent):
def __init__(self) -> None:
super().__init__(
instructions="""You are a helpful voice AI assistant.
You eagerly assist users with their questions.
Keep responses concise and conversational.""",
)
第 3 部分:设置代理服务器
server = AgentServer()
@server.rtc_session()
async def my_agent(ctx: agents.JobContext):
# Create agent session with STT, LLM, TTS, and 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(),
)
# Start the session
await session.start(
room=ctx.room,
agent=Assistant(),
)
if __name__ == "__main__":
# Run in console mode for local testing
sys.argv = [sys.argv[0], "console"]
agents.cli.run_app(server)
步骤 4:运行您的代理
在控制台模式下运行您的语音代理以进行本地测试:
python agent.py console
您的代理将启动并连接到 LiveKit。通过麦克风说话,所有追踪将自动出现在 LangSmith 中。
查看完整的 agent.py 代码.
高级用法
追踪语音转语音模型
The previous example uses a cascade pipeline (separate STT, LLM, and TTS services). LiveKit also supports speech-to-speech models, where a single realtime model handles audio in and out. To trace one, build the session with a realtime model instead of the STT/LLM/TTS stack. The tracing setup is identical and the span processor is unchanged:
from livekit.plugins import openai as lk_openai
session = AgentSession(llm=lk_openai.realtime.RealtimeModel(voice="marin"))
附加对话音频
要在收听对话的同时查看其转录文本,请录制通话并将音频文件附加到根运行。录制播放给客户端的内容,以便录音反映实际听到的内容,包括任何因中断而被切断的语音。关于底层附件API,请参阅 通过追踪上传文件.
自定义元数据和标签
您可以使用span属性向追踪添加自定义元数据:
from opentelemetry import trace
class Assistant(Agent):
def __init__(self) -> None:
super().__init__(
instructions="You are a helpful assistant.",
)
# Get current span and add custom attributes
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中:
- **验证环境变量**:确保
OTEL_EXPORTER_OTLP_ENDPOINT和OTEL_EXPORTER_OTLP_HEADERS在您的中正确设置.envfile. - **检查设置顺序**:确保
setup_langsmith()被调用 **在** 创建AgentServer. - **检查API密钥**:确认您的LangSmith API密钥具有写入权限。
- **查找确认信息**:启动时,您应在控制台中看到"✅ LangSmith tracing enabled"。
消息未正确显示
如果对话消息未正确显示:
- **检查span处理器**:验证
langsmith_processor.py在您的项目目录中且导入正确。 - **验证导入**:确保
LangSmithSpanProcessor在您的agent.py中导入。 - **启用调试日志**:设置
LANGSMITH_PROCESSOR_DEBUG=true在您的环境中以查看详细日志。
连接问题
如果您的代理无法连接到LiveKit:
- **验证LiveKit URL**:检查
LIVEKIT_URL在您的中正确设置.envfile. - **检查凭据**:确保
LIVEKIT_API_KEY和LIVEKIT_API_SECRET正确。 - **测试连接**:首先尝试使用LiveKit CLI连接到您的LiveKit服务器。
- **控制台模式**:对于本地测试,始终使用:
python agent.py console.
导入错误
如果遇到导入错误:
- **安装依赖项**:运行第1步中的完整pip install命令。
- **检查Python版本**:确保您使用的是Python 3.9或更高版本。
- **验证langsmith_处理器**:确保
langsmith_processor.py已下载且位于同一目录中agent.py. - **检查 LiveKit 插件**: Ensure you have the correct LiveKit plugins installed for your STT/LLM/TTS providers.
代理无响应
如果您的代理已连接但无响应:
- **检查 API 密钥**:验证您的 OpenAI API 密钥(或其他提供商密钥)是否正确。
- **测试服务**:确保您的 STT、LLM 和 TTS 服务可访问。
- **检查指令**:确保您的代理有正确的指令。
- **查看日志**:在控制台输出中查找错误。