以下环境变量允许您配置追踪启用、API端点、API密钥和追踪项目:
- -
LANGSMITH_TRACING - -
LANGSMITH_API_KEY - -
LANGSMITH_ENDPOINT - -
LANGSMITH_PROJECT
如果您需要使用自定义配置追踪运行,在不支持典型环境变量的环境中工作(如Cloudflare Workers),或不愿依赖环境变量,LangSmith允许您以编程方式配置追踪。
- - Python:在Python中实现这一目标的推荐方式是使用
tracing_context上下文管理器。这适用于使用traceable装饰器注释的代码以及trace上下文管理器中的代码。 - - TypeScript:您可以同时传递客户端和
tracingEnabled标志到traceabledecorator.
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 regional SaaS
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-5.4-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})
const client = new Client({
apiKey: "YOUR_API_KEY", // This can be retrieved from a secrets manager
apiUrl: "https://api.smith.langchain.com", // Update appropriately for self-hosted installations or regional SaaS
});
const openai = wrapOpenAI(new OpenAI());
const tool = traceable((question: string) => {
return "During this morning's meeting, we solved all world conflict.";
}, { name: "Retrieve Context", runType: "tool" });
const pipeline = traceable(
async (question: string) => {
const context = await tool(question);
const completion = await openai.chat.completions.create({
model: "gpt-5.4-mini",
messages: [
{ role: "system" as const, content: "You are a helpful assistant. Please respond to the user's request only based on the given context." },
{ role: "user" as const, content: `Question: ${question}\nContext: ${context}`}
]
});
return completion.choices[0].message.content;
},
{ name: "Chat", client, tracingEnabled: true }
);
await pipeline("Can you summarize this morning's meetings?");
如果您偏好视频教程,请查看 追踪替代方法视频 来自LangSmith入门课程。
相关
如需根据运行时条件(如客户端要求、数据敏感性或合规策略)动态启用或禁用追踪,请参阅 条件追踪 获取示例。