{"record":{"id":"349943344947b072","repo":"microsoft/autogen","slug":"handoff-message-target-does-not-match-agent-name","errorCode":null,"errorMessage":"Handoff message target does not match agent name: {messages[-1].source}","messagePattern":"Handoff message target does not match agent name: (.+?)","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"python/packages/autogen-agentchat/src/autogen_agentchat/agents/_user_proxy_agent.py","lineNumber":183,"sourceCode":"        input_func: Optional[InputFuncType] = None,\n    ) -> None:\n        \"\"\"Initialize the UserProxyAgent.\"\"\"\n        super().__init__(name=name, description=description)\n        self.input_func = input_func or cancellable_input\n        self._is_async = iscoroutinefunction(self.input_func)\n\n    @property\n    def produced_message_types(self) -> Sequence[type[BaseChatMessage]]:\n        \"\"\"Message types this agent can produce.\"\"\"\n        return (TextMessage, HandoffMessage)\n\n    def _get_latest_handoff(self, messages: Sequence[BaseChatMessage]) -> Optional[HandoffMessage]:\n        \"\"\"Find the HandoffMessage in the message sequence that addresses this agent.\"\"\"\n        if len(messages) > 0 and isinstance(messages[-1], HandoffMessage):\n            if messages[-1].target == self.name:\n                return messages[-1]\n            else:\n                raise RuntimeError(f\"Handoff message target does not match agent name: {messages[-1].source}\")\n        return None\n\n    async def _get_input(self, prompt: str, cancellation_token: Optional[CancellationToken]) -> str:\n        \"\"\"Handle input based on function signature.\"\"\"\n        try:\n            if self._is_async:\n                # Cast to AsyncInputFunc for proper typing\n                async_func = cast(AsyncInputFunc, self.input_func)\n                return await async_func(prompt, cancellation_token)\n            else:\n                # Cast to SyncInputFunc for proper typing\n                sync_func = cast(SyncInputFunc, self.input_func)\n                loop = asyncio.get_event_loop()\n                return await loop.run_in_executor(None, sync_func, prompt)\n\n        except asyncio.CancelledError:\n            raise\n        except Exception as e:","sourceCodeStart":165,"sourceCodeEnd":201,"githubUrl":"https://github.com/microsoft/autogen/blob/027ecf0a379bcc1d09956d46d12d44a3ad9cee14/python/packages/autogen-agentchat/src/autogen_agentchat/agents/_user_proxy_agent.py#L165-L201","documentation":"UserProxyAgent._get_latest_handoff() accepts the last message only if it is a HandoffMessage whose target equals this agent's name; otherwise it raises. Note the message text prints the message's source, but the actual failed comparison is target vs. the agent's name. This guard keeps handoff routing consistent when on_messages is invoked directly.","triggerScenarios":"Calling user_proxy_agent.on_messages(...) / on_messages_stream(...) directly with a HandoffMessage addressed to a different agent; a team/handoff configuration where the handoff target name doesn't exactly match the UserProxyAgent's name (typo, case mismatch).","commonSituations":"Manual orchestration that forwards the full message history (including handoffs meant for other agents) to the user proxy; handoff targets defined with different casing or a renamed agent.","solutions":["Ensure HandoffMessage.target exactly equals the receiving UserProxyAgent's name (case-sensitive).","Don't call on_messages directly with handoff messages addressed elsewhere; let the team runtime route them.","Fix the handoff target list/config that references the wrong agent name."],"exampleFix":"// before\nagent = UserProxyAgent(name=\"human\")\nawait agent.on_messages([HandoffMessage(content=\"take over\", target=\"Human\", source=\"assistant\")])\n\n// after\nagent = UserProxyAgent(name=\"human\")\nawait agent.on_messages([HandoffMessage(content=\"take over\", target=\"human\", source=\"assistant\")])","handlingStrategy":"validation","validationCode":"def handoff_targets_agent(msgs, agent_name) -> bool:\n    last = msgs[-1] if msgs else None\n    return not isinstance(last, HandoffMessage) or last.target == agent_name\n\nif handoff_targets_agent(messages, user_proxy.name):\n    await user_proxy.on_messages(messages, ct)","typeGuard":"def is_handoff_for(msg, agent_name) -> bool:\n    return isinstance(msg, HandoffMessage) and msg.target == agent_name","tryCatchPattern":"try:\n    await user_proxy.on_messages(messages, ct)\nexcept RuntimeError as e:\n    if \"target does not match\" in str(e):\n        # route to the correct agent instead\n        target = next(a for a in team_agents if a.name == messages[-1].target)\n        await target.on_messages(messages, ct)\n    else:\n        raise","preventionTips":["Define handoff targets from the agents' name attributes, never from free-text strings.","Assert HandoffMessage.target == receiving_agent.name before calling on_messages directly.","Prefer team-level routing (Selector/Swarm) over manual on_messages forwarding."],"tags":["user-proxy","handoff","routing","validation"],"backgroundTag":null,"analyzedSha":"027ecf0a379bcc1d09956d46d12d44a3ad9cee14","analyzedAt":"2026-08-15T03:38:00.719Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}