{"record":{"id":"b2ac3b3f5f44001f","repo":"microsoft/autogen","slug":"agent-with-type-type-already-exists-b2ac3b","errorCode":null,"errorMessage":"Agent with type {type} already exists.","messagePattern":"Agent with type (.+?) already exists\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"python/packages/autogen-core/src/autogen_core/_single_threaded_agent_runtime.py","lineNumber":897,"sourceCode":"\n    async def agent_save_state(self, agent: AgentId) -> Mapping[str, Any]:\n        return await (await self._get_agent(agent)).save_state()\n\n    async def agent_load_state(self, agent: AgentId, state: Mapping[str, Any]) -> None:\n        await (await self._get_agent(agent)).load_state(state)\n\n    async def register_factory(\n        self,\n        type: str | AgentType,\n        agent_factory: Callable[[], T | Awaitable[T]],\n        *,\n        expected_class: type[T] | None = None,\n    ) -> AgentType:\n        if isinstance(type, str):\n            type = AgentType(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 not issubclass(type_func_alias(agent_instance), expected_class):\n                raise ValueError(\n                    f\"Factory registered using the wrong type: expected {expected_class.__name__}, got {type_func_alias(agent_instance).__name__}\"\n                )\n            return agent_instance\n\n        self._agent_factories[type.type] = factory_wrapper\n\n        return type\n","sourceCodeStart":879,"sourceCodeEnd":915,"githubUrl":"https://github.com/microsoft/autogen/blob/027ecf0a379bcc1d09956d46d12d44a3ad9cee14/python/packages/autogen-core/src/autogen_core/_single_threaded_agent_runtime.py#L879-L915","documentation":"register_factory raises ValueError when an agent factory is already registered under the same AgentType string. The runtime maps type strings to factories one-to-one; a second registration for an existing type is rejected instead of overwritten.","triggerScenarios":"Calling await runtime.register_factory(AgentType(\"worker\"), factory) twice; registering a type, then trying register_factory again after a failed attempt (first registration persists); a register helper (e.g. BaseAgent.__subclasses__ registration or type-safe RuntimeAgentType.register) colliding with a manual registration of the same type string.","commonSituations":"Hot-reload/notebook re-execution of registration cells; test suites sharing a runtime across cases that each register the same type; retry loops around registration; two teams using the same generic type name ('assistant').","solutions":["Use the try_register variant (e.g. try_register_factory / type-safe register with exists_ok semantics) or check existence before registering","Create a fresh runtime per test/session instead of re-registering on a shared one","Namespace your type strings (e.g. 'myapp.worker') to avoid collisions"],"exampleFix":"# before\nawait runtime.register_factory(AgentType(\"worker\"), Worker.create)  # second time -> ValueError\n\n# after\nif AgentType(\"worker\") not in already_registered:  # or use try_register_* API\n    await runtime.register_factory(AgentType(\"worker\"), Worker.create)\n# fresh runtime per session also avoids this","handlingStrategy":"validation","validationCode":"async def register_factory_once(runtime, type_str, factory):\n    try:\n        await runtime.try_register_factory(AgentType(type_str), factory)  # no-op if exists\n    except AttributeError:\n        if type_str not in runtime._agent_factories:\n            await runtime.register_factory(AgentType(type_str), factory)","typeGuard":null,"tryCatchPattern":"try:\n    await runtime.register_factory(t, factory)\nexcept ValueError as e:\n    if \"already exists\" in str(e):\n        pass  # already registered this session\n    else:\n        raise","preventionTips":["Use try_register variants where available","Fresh runtime per test/notebook session","Namespace agent type strings per app/module"],"tags":["autogen-core","agent-registration","duplicate","valueerror"],"backgroundTag":null,"analyzedSha":"027ecf0a379bcc1d09956d46d12d44a3ad9cee14","analyzedAt":"2026-08-15T03:38:00.719Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}