当启用 subgraphs 时,每个流式处理事件都包含一个命名空间,用于标识产生该事件的代理。命名空间是节点名称和任务 ID 的路径,表示代理层次结构。
命名空间
来源
() (空)
主代理
("tools:abc123",)
由主代理的 task 工具调用 abc123 生成的子代理
("tools:abc123", "model_request:def456")
子代理内部的模型请求节点
使用命名空间将事件路由到正确的 UI 组件:
for chunk in agent.stream( {"messages": [{"role": "user", "content": "Plan my vacation"}]}, stream_mode="updates", subgraphs=True, version="v2",): if chunk["type"] == "updates": # 检查此事件是否来自子代理 is_subagent = any( segment.startswith("tools:") for segment in chunk["ns"] ) if is_subagent: # 从命名空间中提取工具调用 ID tool_call_id = next( s.split(":")[1] for s in chunk["ns"] if s.startswith("tools:") ) print(f"Subagent {tool_call_id}: {chunk['data']}") else: print(f"Main agent: {chunk['data']}")
from deepagents import create_deep_agentagent = create_deep_agent( model="google_genai:gemini-3.1-pro-preview", system_prompt=( "You are a project coordinator. Always delegate research tasks " "to your researcher subagent using the task tool. Keep your final response to one sentence." ), subagents=[ { "name": "researcher", "description": "Researches topics thoroughly", "system_prompt": ( "You are a thorough researcher. Research the given topic " "and provide a concise summary in 2-3 sentences." ), }, ],)for chunk in agent.stream( {"messages": [{"role": "user", "content": "Write a short summary about AI safety"}]}, stream_mode="updates", subgraphs=True, version="v2",): if chunk["type"] == "updates": # 主代理更新(空命名空间) if not chunk["ns"]: for node_name, data in chunk["data"].items(): if node_name == "tools": # 返回给主代理的子代理结果 for msg in data.get("messages", []): if msg.type == "tool": print(f"\nSubagent complete: {msg.name}") print(f" Result: {str(msg.content)[:200]}...") else: print(f"[main agent] step: {node_name}") # 子代理更新(非空命名空间) else: for node_name, data in chunk["data"].items(): print(f" [{chunk['ns'][0]}] step: {node_name}")
for chunk in agent.stream( {"messages": [{"role": "user", "content": "Research recent quantum computing advances"}]}, stream_mode="messages", subgraphs=True, version="v2",): if chunk["type"] == "messages": token, metadata = chunk["data"] # 识别来源:"main" 或子代理命名空间段 is_subagent = any(s.startswith("tools:") for s in chunk["ns"]) source = next((s for s in chunk["ns"] if s.startswith("tools:")), "main") if is_subagent else "main" # 工具调用块(流式工具调用) if token.tool_call_chunks: for tc in token.tool_call_chunks: if tc.get("name"): print(f"\n[{source}] Tool call: {tc['name']}") # 参数以块形式流式传输 - 增量写入 if tc.get("args"): print(tc["args"], end="", flush=True) # 工具结果 if token.type == "tool": print(f"\n[{source}] Tool result [{token.name}]: {str(token.content)[:150]}") # 常规 AI 内容(跳过工具调用消息) if token.type == "ai" and token.content and not token.tool_call_chunks: print(token.content, end="", flush=True)print()
import timefrom langchain.tools import toolfrom langgraph.config import get_stream_writerfrom deepagents import create_deep_agent@tooldef analyze_data(topic: str) -> str: """Run a data analysis on a given topic. This tool performs the actual analysis and emits progress updates. You MUST call this tool for any analysis request. """ writer = get_stream_writer() writer({"status": "starting", "topic": topic, "progress": 0}) time.sleep(0.5) writer({"status": "analyzing", "progress": 50}) time.sleep(0.5) writer({"status": "complete", "progress": 100}) return ( f'Analysis of "{topic}": Customer sentiment is 85% positive, ' "driven by product quality and support response times." )agent = create_deep_agent( model="google_genai:gemini-3.1-pro-preview", system_prompt=( "You are a coordinator. For any analysis request, you MUST delegate " "to the analyst subagent using the task tool. Never try to answer directly. " "After receiving the result, summarize it in one sentence." ), subagents=[ { "name": "analyst", "description": "Performs data analysis with real-time progress tracking", "system_prompt": ( "You are a data analyst. You MUST call the analyze_data tool " "for every analysis request. Do not use any other tools. " "After the analysis completes, report the result." ), "tools": [analyze_data], }, ],)for chunk in agent.stream( {"messages": [{"role": "user", "content": "Analyze customer satisfaction trends"}]}, stream_mode="custom", subgraphs=True, version="v2",): if chunk["type"] == "custom": is_subagent = any(s.startswith("tools:") for s in chunk["ns"]) if is_subagent: subagent_ns = next(s for s in chunk["ns"] if s.startswith("tools:")) print(f"[{subagent_ns}]", chunk["data"]) else: print("[main]", chunk["data"])