基于工具调用与状态切换的智能体交接模式

介绍智能体交接模式的核心机制,即通过工具调用更新状态变量,在单一智能体或图节点间转移控制权,并讨论上下文过滤与工具语义两类设计考量。

在那个 **分发** 架构,行为根据状态发生动态变化。核心机制: [工具](<https://docs.langchain.com/oss/python/langchain/tools>) 更新状态变量(例如, `current_step` 或 时 间 `active_agent`),它持续跨转弯,系统读取这个变量来调整行为——要么应用不同的配置(系统即时,工具),要么向不同的方向行进 [代理服务器](<https://docs.langchain.com/oss/python/langchain/agents>)。这种模式既支持不同物剂之间的交接,也支持单一物剂内部的动态配置变化。 术语 **分发** 钱币由 [OpenAI](<https://openai.github.io/openai-agents-python/handoffs/>) 用于使用工具调用(例如, `transfer_to_sales_agent`在代理人或国家之间转移控制。 ## 关键特征 - 国家驱动的行为:行为改变基于状态变量(例如, `current_step` 或 时 间 `active_agent`) - 基于工具的转换: 工具更新状态变量以在州与州之间移动 - 直接用户互动:每个州的配置直接处理用户信息 - 持续状态:国家通过对话而生存 ## 何时使用 当您需要执行顺序限制( 只有在满足了先决条件后才能解锁) 时使用交接模式, 代理机需要直接与不同状态的用户交谈, 或者您正在构建多阶段的对话流程 。这种模式对于客户支持情景特别宝贵,因为您需要按特定顺序收集信息——例如,在处理退款之前收集保修件ID。 ## 基本执行情况 核心机制是: [工具](<https://docs.langchain.com/oss/python/langchain/tools>) 返回一个 [`Command`](<https://docs.langchain.com/oss/python/langgraph/graph-api#command>) 以更新状态,触发向新步骤或代理的过渡 : ``` from langchain.tools import tool from langchain.messages import ToolMessage from langgraph.types import Command @tool def transfer_to_specialist(runtime) -> Command: """Transfer to the specialist agent.""" return Command( update={ "messages": [ ToolMessage( content="Transferred to specialist", tool_call_id=runtime.tool_call_id ) ], "current_step": "specialist" # Triggers behavior change } ) ``` **为什么包括a `ToolMessage`?** 当一个LLM调用一个工具时,它会期望得到一个响应. The. `ToolMessage` 并配对 `tool_call_id` 完成请求- 响应周期—— 没有它, 对话历史会变得不正确 。 当您的交接工具更新消息时, 需要这样做 。 完整的实施情况见下文教程。 ## 教程:通过交割建立客户支持 学习如何使用交割模式构建客户客服智能体,其中单个代理在不同配置之间过渡. ## 执行办法 有两种方法可以实施交割: **[带有中间软件的单一代理](<https://docs.langchain.com/oss/python/langchain/multi-agent/handoffs#single-agent-with-middleware>)** (一个具有动态配置的代理)或 **[多个代理子图](<https://docs.langchain.com/oss/python/langchain/multi-agent/handoffs#multiple-agent-subgraphs>)** (清晰的代理作为图表节点). ### 带有中间软件的单一代理 单个代理基于状态改变其行为。 Middleware 截取每个模型调用并动态调整系统即时和可用的工具。 工具更新状态变量以触发过渡 : ``` from langchain.tools import ToolRuntime, tool from langchain.messages import ToolMessage from langgraph.types import Command @tool def record_warranty_status( status: str, runtime: ToolRuntime[None, SupportState] ) -> Command: """Record warranty status and transition to next step.""" return Command( update={ "messages": [ ToolMessage( content=f"Warranty status recorded: {status}", tool_call_id=runtime.tool_call_id ) ], "warranty_status": status, "current_step": "specialist" # Update state to trigger transition } ) ``` 完整示例: 客户端支持和中间软件 ``` from langchain.agents import AgentState, create_agent from langchain.agents.middleware import wrap_model_call, ModelRequest, ModelResponse from langchain.tools import tool, ToolRuntime from langchain.messages import ToolMessage from langgraph.checkpoint.memory import InMemorySaver from langgraph.types import Command from typing import Callable # 1. Define state with current_step tracker class SupportState(AgentState): """Track which step is currently active.""" current_step: str = "triage" warranty_status: str | None = None # 2. Tools update current_step via Command @tool def record_warranty_status( status: str, runtime: ToolRuntime[None, SupportState] ) -> Command: """Record warranty status and transition to next step.""" return Command(update={ "messages": [ ToolMessage( content=f"Warranty status recorded: {status}", tool_call_id=runtime.tool_call_id ) ], "warranty_status": status, # Transition to next step "current_step": "specialist" }) # 3. Middleware applies dynamic configuration based on current_step @wrap_model_call def apply_step_config( request: ModelRequest, handler: Callable[[ModelRequest], ModelResponse] ) -> ModelResponse: """Configure agent behavior based on current_step.""" step = request.state.get("current_step", "triage") # Map steps to their configurations configs = { "triage": { "prompt": "Collect warranty information...", "tools": [record_warranty_status] }, "specialist": { "prompt": "Provide solutions based on warranty: {warranty_status}", "tools": [provide_solution, escalate] } } config = configs[step] request = request.override( system_prompt=config["prompt"].format(**request.state), tools=config["tools"] ) return handler(request) # 4. Create agent with middleware agent = create_agent( model, tools=[record_warranty_status, provide_solution, escalate], state_schema=SupportState, middleware=[apply_step_config], checkpointer=InMemorySaver() # Persist state across turns ) ``` ### 多个代理子图 多个不同的代理在图表中作为单独的节点存在。 Handoff 工具在代理节点之间导航 。 `Command.PARENT` 以指定下一个执行的节点。 分图的交割需要小心 **[环境工程](<https://docs.langchain.com/oss/python/langchain/context-engineering>)**。与单代理中间软件不同(信息历史自然流动),您必须明确决定代理之间传递的是什么消息。获取错误,代理商接收的谈话历史或上下文不整齐。见 [环境工程](<https://docs.langchain.com/oss/python/langchain/multi-agent/handoffs#context-engineering>) 现列于下。 ``` from langchain.messages import AIMessage, ToolMessage from langchain.tools import tool, ToolRuntime from langgraph.types import Command @tool def transfer_to_sales( runtime: ToolRuntime, ) -> Command: """Transfer to the sales agent.""" last_ai_message = next( msg for msg in reversed(runtime.state["messages"]) if isinstance(msg, AIMessage) ) transfer_message = ToolMessage( content="Transferred to sales agent", tool_call_id=runtime.tool_call_id, ) return Command( goto="sales_agent", update={ "active_agent": "sales_agent", "messages": [last_ai_message, transfer_message], }, graph=Command.PARENT ) ``` 完整的例子:销售和支持与分红 这个例子显示了一个多代理系统,有独立的销售和辅助代理. 每个代理都是单独的图表节点,交接工具允许代理将对话传递给对方. ``` from typing import Literal from langchain.agents import AgentState, create_agent from langchain.messages import AIMessage, ToolMessage from langchain.tools import tool, ToolRuntime from langgraph.graph import StateGraph, START, END from langgraph.types import Command from typing_extensions import NotRequired # 1. Define state with active_agent tracker class MultiAgentState(AgentState): active_agent: NotRequired[str] # 2. Create handoff tools @tool def transfer_to_sales( runtime: ToolRuntime, ) -> Command: """Transfer to the sales agent.""" last_ai_message = next( msg for msg in reversed(runtime.state["messages"]) if isinstance(msg, AIMessage) ) transfer_message = ToolMessage( content="Transferred to sales agent from support agent", tool_call_id=runtime.tool_call_id, ) return Command( goto="sales_agent", update={ "active_agent": "sales_agent", "messages": [last_ai_message, transfer_message], }, graph=Command.PARENT, ) @tool def transfer_to_support( runtime: ToolRuntime, ) -> Command: """Transfer to the support agent.""" last_ai_message = next( msg for msg in reversed(runtime.state["messages"]) if isinstance(msg, AIMessage) ) transfer_message = ToolMessage( content="Transferred to support agent from sales agent", tool_call_id=runtime.tool_call_id, ) return Command( goto="support_agent", update={ "active_agent": "support_agent", "messages": [last_ai_message, transfer_message], }, graph=Command.PARENT, ) # 3. Create agents with handoff tools sales_agent = create_agent( model="google_genai:gemini-4-hydrogen", tools=[transfer_to_support], system_prompt="You are a sales agent. Help with sales inquiries. If asked about technical issues or support, transfer to the support agent.", ) support_agent = create_agent( model="google_genai:gemini-4-hydrogen", tools=[transfer_to_sales], system_prompt="You are a support agent. Help with technical issues. If asked about pricing or purchasing, transfer to the sales agent.", ) # 4. Create agent nodes that invoke the agents def call_sales_agent(state: MultiAgentState) -> Command: """Node that calls the sales agent.""" response = sales_agent.invoke(state) return response def call_support_agent(state: MultiAgentState) -> Command: """Node that calls the support agent.""" response = support_agent.invoke(state) return response # 5. Create router that checks if we should end or continue def route_after_agent( state: MultiAgentState, ) -> Literal["sales_agent", "support_agent", "__end__"]: """Route based on active_agent, or END if the agent finished without handoff.""" messages = state.get("messages", []) # Check the last message - if it's an AIMessage without tool calls, we're done if messages: last_msg = messages[-1] if isinstance(last_msg, AIMessage) and not last_msg.tool_calls: return "__end__" # Otherwise route to the active agent active = state.get("active_agent", "sales_agent") return active if active else "sales_agent" def route_initial( state: MultiAgentState, ) -> Literal["sales_agent", "support_agent"]: """Route to the active agent based on state, default to sales agent.""" return state.get("active_agent") or "sales_agent" # 6. Build the graph builder = StateGraph(MultiAgentState) builder.add_node("sales_agent", call_sales_agent) builder.add_node("support_agent", call_support_agent) # Start with conditional routing based on initial active_agent builder.add_conditional_edges(START, route_initial, ["sales_agent", "support_agent"]) # After each agent, check if we should end or route to another agent builder.add_conditional_edges( "sales_agent", route_after_agent, ["sales_agent", "support_agent", END] ) builder.add_conditional_edges( "support_agent", route_after_agent, ["sales_agent", "support_agent", END] ) graph = builder.compile() result = graph.invoke( { "messages": [ { "role": "user", "content": "Hi, I'm having trouble with my account login. Can you help?", } ] } ) for msg in result["messages"]: msg.pretty_print() ``` 使用( U) **带有中间软件的单一代理** 对于大多数交割者来说,它使用的案例比较简单。只使用 **多个代理子图** 当您需要调试代理执行时(例如,一个节点本身是一个带有反射或检索步骤的复杂图表). #### 环境工程 通过子图的交接, 您可以控制代理商之间的信息流。 这种精确度对于保持有效对话历史和避免可能混淆下游代理商的上下文 bloat 至关重要。 更多关于此话题, 请参见 。 [环境工程](<https://docs.langchain.com/oss/python/langchain/context-engineering>). **交割时处理上下文** 在代理之间交接时, 您需要确保对话历史依然有效 。 LLMs 期望工具调用会与其响应对齐, 因此在使用时 `Command.PARENT` 向另一代理人交接,必须同时包括: 1. **那个... `AIMessage` 包含工具调用** (引发交接的讯息) 2. **A `ToolMessage` 承认交接** (对这个工具呼吁的人工响应) 如果没有这种对齐,接收代理将看到一个不完整的对口,并可能产生错误或出乎意料的行为。下面的例子假设只有交接工具被调用(没有并行工具调用): ``` @tool def transfer_to_sales(runtime: ToolRuntime) -> Command: # Get the AI message that triggered this handoff last_ai_message = runtime.state["messages"][-1] # Create an artificial tool response to complete the pair transfer_message = ToolMessage( content="Transferred to sales agent", tool_call_id=runtime.tool_call_id, ) return Command( goto="sales_agent", update={ "active_agent": "sales_agent", # Pass only these two messages, not the full subagent history "messages": [last_ai_message, transfer_message], }, graph=Command.PARENT, ) ``` **为什么不传递所有子代理信息?** 尽管您可以在交接中包括全部的副代理谈话,但这往往会造成问题。 接收代理可能会因为无关紧要的内部推理而变得困惑,而象征性成本也无必要地增加。 仅仅通过交接对,您就会把母图的背景集中在高层协调上。如果接收代理需要额外的上下文,请考虑在ToolMessage内容中总结副代理的工作,而不是传递原始消息历史. **将控件返回用户** 当返回控制器给用户( 结束代理机的转弯)时, 确保最后的消息是 `AIMessage`。这保持了有效的对话历史,并向用户界面发出信号,说明代理已完成了工作。 ## 执行方面的考虑 在设计你的多剂系统时,请考虑: - **上下文过滤策略**: 每位代理员会收到完整的对话历史,过滤部分,还是摘要?不同的代理员可能需要不同的上下文,取决于他们的角色. - **工具语义**: 澄清交接工具是只更新路由状态,还是也执行副作用。例如,应该 `transfer_to_sales()` 还要制作一张支持票,还是应该单独行动? - **调试效率**: 平衡上下文的完整性与象征性成本. 总结和选择性上下文随着对话时间的延长而变得更加重要. --- [连接这些文件](<https://docs.langchain.com/use-these-docs>) 通过 MCP 向您选择的代理提供实时答案。 [在 GitHub 上编辑此页面](<https://github.com/langchain-ai/docs/edit/main/src/oss/langchain/multi-agent/handoffs.mdx>) 或 时 间 [提交一个问题](<https://github.com/langchain-ai/docs/issues/new/choose>). 这页有用吗?

查看原始来源