- 将
LANGCHAIN_WANDB_TRACING环境变量设置为 “true”。 - 使用上下文管理器
wandb_tracing_enabled()追踪特定代码块。
Copy
import os
from langchain_community.callbacks import wandb_tracing_enabled
os.environ["LANGCHAIN_WANDB_TRACING"] = "true"
# wandb 文档:使用环境变量配置 wandb
# https://docs.wandb.ai/guides/track/advanced/environment-variables
os.environ["WANDB_PROJECT"] = "langchain-tracing"
from langchain.agents import create_agent, load_tools
from langchain_openai import OpenAI
Copy
# 带追踪的 Agent 运行。确保 OPENAI_API_KEY 已正确设置才能运行此示例。
llm = OpenAI(temperature=0)
tools = load_tools(["llm-math"], llm=llm)
agent = create_agent(
model=llm,
tools=tools,
verbose=True,
)
agent.invoke("What is 2 raised to .123243 power?")
Copy
# 现在,我们取消环境变量的设置,并使用上下文管理器。
if "LANGCHAIN_WANDB_TRACING" in os.environ:
del os.environ["LANGCHAIN_WANDB_TRACING"]
# 使用上下文管理器启用追踪
with wandb_tracing_enabled():
agent.invoke("What is 5 raised to .123243 power?")
agent.invoke("What is 2 raised to .123243 power?")
Copy
> Entering new AgentExecutor chain...
I need to use a calculator to solve this.
Action: Calculator
Action Input: 5^.123243
Observation: Answer: 1.2193914912400514
Thought: I now know the final answer.
Final Answer: 1.2193914912400514
> Finished chain.
> Entering new AgentExecutor chain...
I need to use a calculator to solve this.
Action: Calculator
Action Input: 2^.123243
Observation: Answer: 1.0891804557407723
Thought: I now know the final answer.
Final Answer: 1.0891804557407723
> Finished chain.
Copy
'1.0891804557407723'
通过 MCP 将这些文档连接到 Claude、VSCode 等以获取实时答案。

