from langchain.agents import create_agentdef get_weather(city: str) -> str: """Get weather for a given city.""" return f"It's always sunny in {city}!"agent = create_agent( model="gpt-5-nano", tools=[get_weather],)for chunk in agent.stream( {"messages": [{"role": "user", "content": "What is the weather in SF?"}]}, stream_mode="updates", version="v2",): if chunk["type"] == "updates": for step, data in chunk["data"].items(): print(f"step: {step}") print(f"content: {data['messages'][-1].content_blocks}")
输出
step: modelcontent: [{'type': 'tool_call', 'name': 'get_weather', 'args': {'city': 'San Francisco'}, 'id': 'call_OW2NYNsNSKhRZpjW0wm2Aszd'}]step: toolscontent: [{'type': 'text', 'text': "It's always sunny in San Francisco!"}]step: modelcontent: [{'type': 'text', 'text': 'It's always sunny in San Francisco!'}]
from langchain.agents import create_agentfrom langgraph.config import get_stream_writer def get_weather(city: str) -> str: """Get weather for a given city.""" writer = get_stream_writer() # 流式输出任意数据 writer(f"Looking up data for city: {city}") writer(f"Acquired data for city: {city}") return f"It's always sunny in {city}!"agent = create_agent( model="claude-sonnet-4-6", tools=[get_weather],)for chunk in agent.stream( {"messages": [{"role": "user", "content": "What is the weather in SF?"}]}, stream_mode="custom", version="v2",): if chunk["type"] == "custom": print(chunk["data"])
输出
Looking up data for city: San FranciscoAcquired data for city: San Francisco
from langchain.agents import create_agentfrom langchain.messages import AIMessageChunkfrom langchain_anthropic import ChatAnthropicfrom langchain_core.runnables import Runnabledef get_weather(city: str) -> str: """Get weather for a given city.""" return f"It's always sunny in {city}!"model = ChatAnthropic( model_name="claude-sonnet-4-6", timeout=None, stop=None, thinking={"type": "enabled", "budget_tokens": 5000},)agent: Runnable = create_agent( model=model, tools=[get_weather],)for token, metadata in agent.stream( {"messages": [{"role": "user", "content": "What is the weather in SF?"}]}, stream_mode="messages",): if not isinstance(token, AIMessageChunk): continue reasoning = [b for b in token.content_blocks if b["type"] == "reasoning"] text = [b for b in token.content_blocks if b["type"] == "text"] if reasoning: print(f"[thinking] {reasoning[0]['reasoning']}", end="") if text: print(text[0]["text"], end="")
输出
[thinking] The user is asking about the weather in San Francisco. I have a tool[thinking] available to get this information. Let me call the get_weather tool[thinking] with "San Francisco" as the city parameter.The weather in San Francisco is: It's always sunny in San Francisco!