主题
追踪 OpenAI 应用
Python/TypeScript 中的 wrap_openai / wrapOpenAI 方法允许你包装 OpenAI 客户端,从而自动记录追踪 —— 无需装饰器或函数包装!使用该包装器可确保消息(包括工具调用与多模态内容块)在 LangSmith 中良好呈现。另请注意,该包装器可与 @traceable 装饰器或 traceable 函数无缝配合,你可以在同一个应用中同时使用两者。
NOTE
即使使用 wrap_openai 或 wrapOpenAI,也必须将 LANGSMITH_TRACING 环境变量设为 'true',追踪才会记录到 LangSmith。这样你无需修改代码即可开启或关闭追踪。
此外,你还需要将 LANGSMITH_API_KEY 环境变量设置为你的 API key(更多信息见设置。)
如果你的 LangSmith API key 关联了多个工作区,请设置 LANGSMITH_WORKSPACE_ID 环境变量以指定使用哪个工作区。
默认情况下,追踪会记录到名为 default 的项目。要将追踪记录到其他项目,请参阅将追踪记录到指定项目。
python
import openai
from langsmith import traceable
from langsmith.wrappers import wrap_openai
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(name="Chat Pipeline")
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.5", messages=messages
)
return chat_completion.choices[0].message.content
chat_pipeline("Can you summarize this morning's meetings?")typescript
import OpenAI from "openai";
import { traceable } from "langsmith/traceable";
import { wrapOpenAI } from "langsmith/wrappers";
const client = wrapOpenAI(new OpenAI());
const myTool = traceable(async (question: string) => {
return "During this morning's meeting, we solved all world conflict.";
}, { name: "Retrieve Context", run_type: "tool" });
const chatPipeline = traceable(async (question: string) => {
const context = await myTool(question);
const 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: `Question: ${question} Context: ${context}` },
];
const chatCompletion = await client.chat.completions.create({
model: "gpt-5.5",
messages: messages,
});
return chatCompletion.choices[0].message.content;
}, { name: "Chat Pipeline" });
await chatPipeline("Can you summarize this morning's meetings?");要追踪提供 OpenAI 兼容 API 的提供商,请参阅追踪 OpenAI 兼容的提供商。