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="检索上下文")
def my_tool(question: str) -> str:
return "在今天早上的会议中,我们解决了所有世界冲突。"
@traceable
def chat_pipeline(question: str):
context = my_tool(question)
messages = [
{ "role": "system", "content": "你是一个乐于助人的助手。请仅根据给定的上下文回应用户的请求。" },
{ "role": "user", "content": f"问题:{question}\n上下文:{context}"}
]
chat_completion = client.chat.completions.create(
model="gpt-4.1-mini", messages=messages
)
return chat_completion.choices[0].message.content
# 可设置为 False 以在此处禁用追踪,而无需更改代码结构
with tracing_context(enabled=True):
# 使用 langsmith_extra 传入自定义客户端
chat_pipeline("你能总结一下今天早上的会议吗?", langsmith_extra={"client": langsmith_client})