跳到主要内容
如其他指南所述,以下环境变量允许您配置启用追踪、API 端点、API 密钥和追踪项目
  • LANGSMITH_TRACING
  • LANGSMITH_API_KEY
  • LANGSMITH_ENDPOINT
  • LANGSMITH_PROJECT
如果您需要使用自定义配置追踪运行,在不支持典型环境变量的环境中工作(例如 Cloudflare Workers),或者只是不想依赖环境变量,LangSmith 允许您以编程方式配置追踪。
由于收到许多关于使用 trace 上下文管理器进行更精细控制追踪的需求,我们改变了 with trace 的行为,以在 Python SDK 0.1.95 版本中遵循 LANGSMITH_TRACING 环境变量。您可以在发行说明中找到更多详细信息。在不设置环境变量的情况下禁用/启用追踪的推荐方法是使用 with tracing_context 上下文管理器,如下面的示例所示。
  • Python:在 Python 中执行此操作的推荐方法是使用 tracing_context 上下文管理器。这适用于使用 traceable 注解的代码和 trace 上下文管理器中的代码。
  • TypeScript:您可以将客户端和 tracingEnabled 标志都传递给 traceable 装饰器。
import openai
from langsmith import Client, tracing_context, traceable
from langsmith.wrappers import wrap_openai

langsmith_client = Client(
  api_key="YOUR_LANGSMITH_API_KEY",  # This can be retrieved from a secrets manager
  api_url="https://api.smith.langchain.com",  # Update appropriately for self-hosted installations or the EU region
  workspace_id="YOUR_WORKSPACE_ID", # Must be specified for API keys scoped to multiple workspaces
)

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):
  # Use langsmith_extra to pass in a custom client
  chat_pipeline("Can you summarize this morning's meetings?", langsmith_extra={"client": langsmith_client})
如果您喜欢视频教程,请查看 LangSmith 简介课程中的替代追踪方式视频
以编程方式连接这些文档到 Claude、VSCode 等,通过 MCP 获取实时答案。
© . This site is unofficial and not affiliated with LangChain, Inc.