{"record":{"id":"ecf8a55f23baaac8","repo":"microsoft/autogen","slug":"message-type-type-message-not-in-target-types-ecf8a5","errorCode":null,"errorMessage":"Message type {type(message)} not in target types {target_types}","messagePattern":"Message type (.+?) not in target types (.+?)","errorType":"exception","errorClass":"CantHandleException","httpStatus":null,"severity":"error","filePath":"python/packages/autogen-core/src/autogen_core/_routed_agent.py","lineNumber":145,"sourceCode":"\n        # Get the type of the message parameter\n        target_types = get_types(type_hints[\"message\"])\n        if target_types is None:\n            raise AssertionError(\"Message type not found\")\n\n        # print(type_hints)\n        return_types = get_types(type_hints[\"return\"])\n\n        if return_types is None:\n            raise AssertionError(\"Return type not found\")\n\n        # Convert target_types to list and stash\n\n        @wraps(func)\n        async def wrapper(self: AgentT, message: ReceivesT, ctx: MessageContext) -> ProducesT:\n            if type(message) not in target_types:\n                if strict:\n                    raise CantHandleException(f\"Message type {type(message)} not in target types {target_types}\")\n                else:\n                    logger.warning(f\"Message type {type(message)} not in target types {target_types}\")\n\n            return_value = await func(self, message, ctx)\n\n            if AnyType not in return_types and type(return_value) not in return_types:\n                if strict:\n                    raise ValueError(f\"Return type {type(return_value)} not in return types {return_types}\")\n                else:\n                    logger.warning(f\"Return type {type(return_value)} not in return types {return_types}\")\n\n            return return_value\n\n        wrapper_handler = cast(MessageHandler[AgentT, ReceivesT, ProducesT], wrapper)\n        wrapper_handler.target_types = list(target_types)\n        wrapper_handler.produces_types = list(return_types)\n        wrapper_handler.is_message_handler = True\n        wrapper_handler.router = match or (lambda _message, _ctx: True)","sourceCodeStart":127,"sourceCodeEnd":163,"githubUrl":"https://github.com/microsoft/autogen/blob/027ecf0a379bcc1d09956d46d12d44a3ad9cee14/python/packages/autogen-core/src/autogen_core/_routed_agent.py#L127-L163","documentation":"At runtime the generated wrapper checks type(message) against the handler's target_types using exact type() membership. If the delivered message's concrete class is not in target_types and strict=True, CantHandleException is raised, which lets the RoutedAgent runtime try other handlers or respond with an Undeliverable error. With strict=False it only logs a warning and still calls the handler.","triggerScenarios":"A sender publishes a different concrete message class than annotated (e.g. subclass instance of the annotated type, since type() matching is exact); multiple handlers exist and the message type was routed to a handler not declared for it; ctx.is_rpc semantics mismatch so a publish message reaches an rpc handler via @message_handler.","commonSituations":"Subclassing a message model and sending the subclass while the handler annotates the base class; version drift between sender and receiver message definitions; using @message_handler for both event and rpc traffic and receiving a type not in the annotation union.","solutions":["Annotate the handler with every concrete message type it accepts (union annotation), since matching is exact type() not isinstance","Ensure the sender serializes/deserializes to the exact same class the handler annotates (same model definition on both sides)","Set strict=False on the decorator to downgrade this to a warning if lenient routing is acceptable"],"exampleFix":"# before\n@message_handler\nasync def handle(self, message: BaseMsg, ctx: MessageContext) -> None: ...\n# sender publishes SubMsg(BaseMsg) -> CantHandleException\n\n# after\n@message_handler\nasync def handle(self, message: BaseMsg | SubMsg, ctx: MessageContext) -> None: ...","handlingStrategy":"try-catch","validationCode":"from autogen_core import try_get_known_serializers_for_type\n\ndef can_handle(handler_wrapper, message) -> bool:\n    return type(message) in handler_wrapper.target_types","typeGuard":"def message_in_target_types(handler, msg) -> bool:\n    return type(msg) in getattr(handler, \"target_types\", ())","tryCatchPattern":"from autogen_core import CantHandleException\n\ntry:\n    result = await agent.on_message(msg, ctx)\nexcept CantHandleException:\n    # let the runtime pick another handler / report undeliverable\n    raise","preventionTips":["Share one message-models module between sender and receiver so concrete classes match exactly","Remember routing is exact type() matching, not isinstance — annotate every concrete subclass you send","Consider strict=False in prototypes to get warnings instead of exceptions while wiring routing"],"tags":["python","message-routing","runtime","autogen-core"],"backgroundTag":null,"analyzedSha":"027ecf0a379bcc1d09956d46d12d44a3ad9cee14","analyzedAt":"2026-08-15T03:38:00.719Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}