无需设置环境变量即可跟踪
如其他指南中所述,以下环境变量可用于配置是否启用追踪、API 端点、API 密钥以及追踪项目:
LANGSMITH_TRACINGLANGSMITH_API_KEYLANGSMITH_ENDPOINTLANGSMITH_PROJECT
在某些环境中,无法设置环境变量。在这种情况下,您可以通过编程方式设置跟踪配置。
最近更改的行为
由于许多用户要求对使用 trace 上下文管理器的追踪功能进行更精细的控制,
我们更改了其行为:自 Python SDK 版本 0.1.95 起,with trace 将遵循 LANGSMITH_TRACING 环境变量。更多详情请参阅 发布说明。
推荐的在不设置环境变量的情况下启用/禁用追踪的方法是使用 with tracing_context 上下文管理器,如下例所示。
- Python
- TypeScript
在 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})
在 TypeScript 中,您可以将客户端和 tracingEnabled 标志一同传递给 traceable 装饰器。
import { Client } from "langsmith";
import { traceable } from "langsmith/traceable";
import { wrapOpenAI } from "langsmith/wrappers";
import { OpenAI } from "openai";
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 the EU region
});
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-4o-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 入门课程》中的追踪的其他方法视频。