{"record":{"id":"c57f7b7b72bb7f69","repo":"microsoft/autogen","slug":"agent-factories-and-agent-instances-cannot-be-regi","errorCode":null,"errorMessage":"Agent factories and agent instances cannot be registered to the same type.","messagePattern":"Agent factories and agent instances cannot be registered to the same type\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"python/packages/autogen-core/src/autogen_core/_single_threaded_agent_runtime.py","lineNumber":934,"sourceCode":"    async def register_agent_instance(\n        self,\n        agent_instance: Agent,\n        agent_id: AgentId,\n    ) -> AgentId:\n        def agent_factory() -> Agent:\n            raise RuntimeError(\n                \"Agent factory was invoked for an agent instance that was not registered. This is likely due to the agent type being incorrectly subscribed to a topic. If this exception occurs when publishing a message to the DefaultTopicId, then it is likely that `skip_class_subscriptions` needs to be turned off when registering the agent.\"\n            )\n\n        if agent_id in self._instantiated_agents:\n            raise ValueError(f\"Agent with id {agent_id} already exists.\")\n\n        if agent_id.type not in self._agent_factories:\n            self._agent_factories[agent_id.type] = agent_factory\n            self._agent_instance_types[agent_id.type] = type_func_alias(agent_instance)\n        else:\n            if self._agent_factories[agent_id.type].__code__ != agent_factory.__code__:\n                raise ValueError(\"Agent factories and agent instances cannot be registered to the same type.\")\n            if self._agent_instance_types[agent_id.type] != type_func_alias(agent_instance):\n                raise ValueError(\"Agent instances must be the same object type.\")\n\n        await agent_instance.bind_id_and_runtime(id=agent_id, runtime=self)\n        self._instantiated_agents[agent_id] = agent_instance\n        return agent_id\n\n    async def _invoke_agent_factory(\n        self,\n        agent_factory: Callable[[], T | Awaitable[T]] | Callable[[AgentRuntime, 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":916,"sourceCodeEnd":952,"githubUrl":"https://github.com/microsoft/autogen/blob/027ecf0a379bcc1d09956d46d12d44a3ad9cee14/python/packages/autogen-core/src/autogen_core/_single_threaded_agent_runtime.py#L916-L952","documentation":"In register_agent_instance, when the agent_id.type already has an entry in _agent_factories, the runtime compares code objects: if the existing factory is a real factory (registered via register_factory) rather than the instance sentinel, it raises ValueError. One type string cannot be backed by both a callable factory and a directly-registered instance.","triggerScenarios":"First calling await runtime.register_factory(AgentType(\"worker\"), factory), then await runtime.register_agent_instance(inst, AgentId(\"worker\", \"1\")) (or the reverse order for another key) — the second registration detects the mismatch between factory code and the instance sentinel and fails.","commonSituations":"Hybrid designs where some workers are factories and one 'singleton' is an instance under the same type name; refactoring from instance registration to factory registration without renaming the type; copy-paste across setups that pick the opposite registration style for the same name.","solutions":["Use a distinct AgentType string for instance-registered agents vs factory-registered ones (e.g. 'worker' vs 'worker-singleton')","Convert the instance to a factory: register_factory returning the pre-built instance (with skip_class_subscriptions if needed)","Standardize on one registration style per type across the codebase"],"exampleFix":"# before\nawait runtime.register_factory(AgentType(\"worker\"), Worker.create)\nawait runtime.register_agent_instance(w, AgentId(\"worker\", \"1\"))  # ValueError\n\n# after\nawait runtime.register_factory(AgentType(\"worker\"), Worker.create)\nawait runtime.register_agent_instance(w, AgentId(\"worker_singleton\", \"1\"))","handlingStrategy":"validation","validationCode":"async def can_register_instance(runtime, agent_id) -> bool:\n    factory = runtime._agent_factories.get(agent_id.type)\n    return factory is None  # must not collide with a real factory","typeGuard":"def type_is_factory_free(runtime, t: str) -> bool:\n    return t not in runtime._agent_factories","tryCatchPattern":"try:\n    await runtime.register_agent_instance(agent, agent_id)\nexcept ValueError as e:\n    if \"cannot be registered to the same type\" in str(e):\n        await runtime.register_agent_instance(agent, AgentId(agent_id.type + '_singleton', agent_id.key))\n    else:\n        raise","preventionTips":["One registration style (factory OR instance) per type string","Namespace singleton instances with their own type name","Document which types are factory-backed vs instance-backed in project docs"],"tags":["autogen-core","agent-registration","factory","instance","conflict"],"backgroundTag":null,"analyzedSha":"027ecf0a379bcc1d09956d46d12d44a3ad9cee14","analyzedAt":"2026-08-15T03:38:00.719Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}