如其他指南所述,可通过以下环境变量配置是否启用追踪、API 端点、API Key 与追踪项目:
  • LANGSMITH_TRACING
  • LANGSMITH_API_KEY
  • LANGSMITH_ENDPOINT
  • LANGSMITH_PROJECT
如果需要使用自定义配置追踪、所处环境不支持常规环境变量(例如 Cloudflare Workers),或纯粹不想依赖环境变量,可以直接在代码中配置 LangSmith 追踪。
由于大家希望使用 trace 上下文管理器更精细地控制追踪,我们在 Python SDK 0.1.95 版本中更改了 with trace 的行为,使其遵循 LANGSMITH_TRACING 环境变量。详情参见发行说明。不设置环境变量时,推荐使用 with tracing_context 上下文管理器来启用/禁用追踪,示例如下。
  • Python:推荐使用 tracing_context 上下文管理器,既适用于 traceable 装饰的代码,也适用于 trace 上下文中的代码。
  • TypeScript:可以在 traceable 装饰器中同时传入 client 与 tracingEnabled 标记。
import openai
from langsmith import Client, tracing_context, traceable
from langsmith.wrappers import wrap_openai

langsmith_client = Client(
  api_key="YOUR_LANGSMITH_API_KEY",  # 可以从密钥管理器中获取
  api_url="https://api.smith.langchain.com",  # 自托管或欧盟区请按需调整
  workspace_id="YOUR_WORKSPACE_ID", # 针对多个工作区的 API key 必须填写
)

client = wrap_openai(openai.Client())

@traceable(run_type="tool", name="Retrieve Context")
def my_tool(question: str) -> str:
  return "During this morning's meeting, we solved all world conflict."

@traceable
def chat_pipeline(question: str):
  context = my_tool(question)
  messages = [
      { "role": "system", "content": "You are a helpful assistant. Please respond to the user's request only based on the given context." },
      { "role": "user", "content": f"Question: {question}\nContext: {context}"}
  ]
  chat_completion = client.chat.completions.create(
      model="gpt-4o-mini", messages=messages
  )
  return chat_completion.choices[0].message.content

# Can set to False to disable tracing here without changing code structure
with tracing_context(enabled=True):
  # 使用 langsmith_extra 传入自定义 client
  chat_pipeline("Can you summarize this morning's meetings?", langsmith_extra={"client": langsmith_client})
如果更喜欢视频教程,可参阅 LangSmith 入门课程中的 替代追踪方式视频
Connect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.