import openai
from langsmith import Client, tracing_context, traceable
from langsmith.wrappers import wrap_openai
langsmith_client = Client(
api_key="YOUR_LANGSMITH_API_KEY", # 可以从密钥管理器中获取
api_url="https://api.smith.langchain.com", # 对于自托管安装或欧盟区域,请相应更新
workspace_id="YOUR_WORKSPACE_ID", # 对于限定在多个工作区的API密钥必须指定
)
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
# 可以设置为False以在不改变代码结构的情况下禁用追踪
with tracing_context(enabled=True):
# 使用 langsmith_extra 传递自定义客户端
chat_pipeline("Can you summarize this morning's meetings?", langsmith_extra={"client": langsmith_client})