Skip to content

LangSmith 集成指南

LangSmith 是 LangChain 提供的 LLM 应用追踪、调试和监控平台。本文档说明如何在项目中使用 LangSmith。

1. 注册 LangSmith 账号

  1. 访问 LangSmith 官网
  2. 点击 "Sign Up" 注册账号(支持 GitHub/Google 登录)
  3. 登录后进入 Dashboard

2. 获取 API Key

Dashboard → Settings → API Keys → Create API Key

创建后复制 API Key(格式:lsv2_pt_xxxxxxxxxxxxx

3. 配置环境变量

.env 文件中添加:

bash
# LangSmith 配置
LANGCHAIN_TRACING_V2=true
LANGCHAIN_API_KEY=lsv2_pt_xxxxxxxxxxxxx
LANGCHAIN_PROJECT=langchain-platform-luca
# LANGCHAIN_ENDPOINT=https://api.smith.langchain.com  # 可选,默认值
环境变量说明必填
LANGCHAIN_TRACING_V2启用 LangSmith 追踪
LANGCHAIN_API_KEYLangSmith API Key
LANGCHAIN_PROJECT项目名称(在 LangSmith 中分组显示)否(默认 default
LANGCHAIN_ENDPOINTAPI 端点否(默认官方端点)

4. 自动追踪

LangSmith 与 LangChain/LangGraph 自动集成,设置环境变量后:

  • ✅ 所有 LLM 调用自动追踪
  • ✅ Chain 调用自动追踪
  • ✅ Graph 调用自动追踪
  • ✅ Token 使用量自动统计
  • ✅ 延迟自动记录

5. 自定义追踪(可选)

5.1 自定义 Run 名称

python
from services.langgraph_chat import get_chat_service

chat_service = get_chat_service()

# 普通调用
result = chat_service.chat(
    thread_id="conv_123",
    prompt="你好",
    run_name="user-greeting-chat"  # 自定义 run 名称
)

# 流式调用
for chunk in chat_service.chat_stream(
    thread_id="conv_123",
    prompt="你好",
    run_name="user-greeting-stream"  # 自定义 run 名称
):
    print(chunk, end="")

5.2 自定义 Tags

Tags 用于在 LangSmith 中筛选和分析调用:

python
# 在 routes/chat.py 中可以添加业务 tags
tags = [
    "chat",
    "stream",
    f"model:{model}",
    f"user:{user_id}",
    f"conversation:{conversation_id}"
]

5.3 追踪示例

python
from langchain_core.tracers.context import collect_runs

# 收集当前上下文中的所有 runs
with collect_runs() as runs:
    result = chat_service.chat(
        thread_id="conv_123",
        prompt="你好"
    )

# 获取 run ID
for run in runs:
    print(f"Run ID: {run.id}")
    print(f"Run URL: https://smith.langchain.com/runs/{run.id}")

6. 在 LangSmith 中查看

启动应用后,访问 LangSmith Dashboard

  1. 选择项目 langchain-platform-luca
  2. 查看 Runs 列表
  3. 点击任意 Run 查看详情:
    • Input/Output
    • Token 使用量
    • 延迟
    • 调用链路(Trace)

7. 常见用途

7.1 调试

  • 查看完整的 Prompt 内容
  • 检查 LLM 响应
  • 分析 Token 使用

7.2 性能分析

  • 查看 P50/P95/P99 延迟
  • 识别慢查询
  • 优化 Prompt 长度

7.3 成本追踪

  • 统计 Token 消耗
  • 按模型/用户/功能分组
  • 设置预算告警

7.4 质量评估

  • 创建测试集
  • 运行评估
  • 比较不同模型/版本

8. 代码集成位置

文件说明
services/langgraph_chat.pyLangSmith 配置和追踪逻辑
.env环境变量配置

9. 相关链接