{"record":{"id":"32bc8491768a0b67","repo":"microsoft/semantic-kernel","slug":"factory-registered-using-the-wrong-type","errorCode":null,"errorMessage":"Factory registered using the wrong type.","messagePattern":"Factory registered using the wrong type\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"python/semantic_kernel/agents/runtime/in_process/in_process_runtime.py","lineNumber":751,"sourceCode":"        *,\n        expected_class: type[T] | None = None,\n    ) -> AgentType:\n        \"\"\"Register a factory for creating agents.\"\"\"\n        if isinstance(type, str):\n            type = CoreAgentType(type)\n\n        if type.type in self._agent_factories:\n            raise ValueError(f\"Agent with type {type} already exists.\")\n\n        async def factory_wrapper() -> T:\n            maybe_agent_instance = agent_factory()\n            if inspect.isawaitable(maybe_agent_instance):\n                agent_instance = await maybe_agent_instance\n            else:\n                agent_instance = maybe_agent_instance\n\n            if expected_class is not None and type_func_alias(agent_instance) != expected_class:\n                raise ValueError(\"Factory registered using the wrong type.\")\n\n            return agent_instance\n\n        self._agent_factories[type.type] = factory_wrapper\n\n        return type\n\n    async def _invoke_agent_factory(\n        self,\n        agent_factory: Callable[[], T | Awaitable[T]] | Callable[[CoreRuntime, AgentId], T | Awaitable[T]],\n        agent_id: AgentId,\n    ) -> T:\n        with AgentInstantiationContext.populate_context((self, agent_id)):\n            try:\n                if len(inspect.signature(agent_factory).parameters) == 0:\n                    factory_one = cast(Callable[[], T], agent_factory)\n                    agent = factory_one()\n                elif len(inspect.signature(agent_factory).parameters) == 2:","sourceCodeStart":733,"sourceCodeEnd":769,"githubUrl":"https://github.com/microsoft/semantic-kernel/blob/c028a0c7dc4f0814cdcbaba9d998f187a41197bf/python/semantic_kernel/agents/runtime/in_process/in_process_runtime.py#L733-L769","documentation":"When registering a factory with expected_class, the factory_wrapper invokes the factory and checks that the returned instance's type matches expected_class using type_func_alias. If it does not match, ValueError is raised. This is a runtime type-safety guard ensuring factories produce the declared type.","triggerScenarios":"Calling register_factory('MyAgent', lambda: SomeOtherAgent(), expected_class=MyAgent) where the factory returns an instance of a different class. Also triggered if the factory returns a base class or unrelated type.","commonSituations":"A factory function was updated to return a different agent class but expected_class was not updated. A factory that dynamically returns different agent subclasses but expected_class is set to a specific one.","solutions":["Ensure the factory function returns an instance whose type matches the expected_class parameter.","If using polymorphism, set expected_class to the common base type, or pass expected_class=None to skip the check.","Verify that type_func_alias(instance) resolves to the same class object you pass as expected_class."],"exampleFix":"# before\nawait runtime.register_factory('my_agent', lambda: BaseAgent(), expected_class=MyAgent)\n\n# after\nawait runtime.register_factory('my_agent', lambda: MyAgent(), expected_class=MyAgent)\n# or skip the check:\nawait runtime.register_factory('my_agent', lambda: BaseAgent(), expected_class=None)","handlingStrategy":"type-guard","validationCode":"# Validate factory output type before registering\nagent_instance = my_factory()\nassert isinstance(agent_instance, ExpectedAgent), f'Factory returns {type(agent_instance).__name__}, expected {ExpectedAgent.__name__}'\nawait runtime.register_factory('my_agent', my_factory, expected_class=ExpectedAgent)","typeGuard":"def is_correct_type(instance, expected_class) -> bool:\n    from semantic_kernel.agents.runtime.in_process.utils import type_func_alias\n    return type_func_alias(instance) == expected_class","tryCatchPattern":"null","preventionTips":["Test the factory function independently before registering it.","Pass expected_class=None if you don't need the type guard.","Ensure the factory's return type annotation matches expected_class."],"tags":["agent-runtime","factory","type-check","registration","semantic-kernel"],"backgroundTag":null,"analyzedSha":"c028a0c7dc4f0814cdcbaba9d998f187a41197bf","analyzedAt":"2026-08-13T13:48:05.040Z","schemaVersion":2},"datasetVersion":"2026-08-13T14:17:21.547Z"}