Skip to main content

不设置环境变量进行追踪

与其他指南中提到的相同,以下环境变量允许您配置是否启用追踪、API 端点、API 密钥以及追踪项目:

  • LANGSMITH_TRACING
  • LANGSMITH_API_KEY
  • LANGSMITH_ENDPOINT
  • LANGSMITH_PROJECT

在某些环境中,无法设置环境变量。在这些情况下,您可以以编程方式设置跟踪配置。

最近更改的行为

由于多次收到关于使用 trace 上下文管理器实现更细粒度追踪控制的请求, 我们更改了行为,使 with trace 在 Python SDK 的 0.1.95 版本中遵循 LANGSMITH_TRACING 环境变量。您可以在 发布说明 中找到更多详细信息。 禁用/启用追踪而不设置环境变量的推荐方法是使用 with tracing_context 上下文管理器,如下面的示例所示。

在 Python 中推荐的做法是使用 tracing_context 上下文管理器。这适用于使用 traceable 注解的代码以及位于 trace 上下文管理器内的代码。

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
)

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}
Context: {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 课程介绍中的 替代追踪方式视频


此页面有帮助吗?


您可以留下详细的反馈 在 GitHub 上