{"record":{"id":"2d21f2956bd795da","repo":"microsoft/autogen","slug":"agent-with-id-agent-id-already-exists","errorCode":null,"errorMessage":"Agent with id {agent_id} already exists.","messagePattern":"Agent with id (.+?) already exists\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"python/packages/autogen-core/src/autogen_core/_single_threaded_agent_runtime.py","lineNumber":927,"sourceCode":"                )\n            return agent_instance\n\n        self._agent_factories[type.type] = factory_wrapper\n\n        return type\n\n    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,","sourceCodeStart":909,"sourceCodeEnd":945,"githubUrl":"https://github.com/microsoft/autogen/blob/027ecf0a379bcc1d09956d46d12d44a3ad9cee14/python/packages/autogen-core/src/autogen_core/_single_threaded_agent_runtime.py#L909-L945","documentation":"register_agent_instance raises ValueError when the exact AgentId (type + key) is already present in _instantiated_agents. Each instance occupies one id; re-registering the same id — even with a new object — is rejected to prevent silently orphaning the bound agent.","triggerScenarios":"Calling register_agent_instance(agent, AgentId(\"counter\", \"1\")) twice; a startup routine that re-runs (retry, hot reload) and re-registers its instances; registering an instance created for a previous runtime run on a reused runtime object.","commonSituations":"Re-running initialization cells in notebooks; service restarts that rebuild agents against a runtime that was not recreated; loops that register one instance per worker with a constant key instead of a unique one.","solutions":["Use a unique key per instance (e.g. str(i) or uuid) when registering many instances of the same type","Check agent_id in runtime._instantiated_agents (or track registered ids yourself) before registering","Recreate the SingleThreadedAgentRuntime when restarting a session rather than re-registering on the old one"],"exampleFix":"# before\nawait runtime.register_agent_instance(a1, AgentId(\"counter\", \"main\"))\nawait runtime.register_agent_instance(a2, AgentId(\"counter\", \"main\"))  # ValueError\n\n# after\nawait runtime.register_agent_instance(a1, AgentId(\"counter\", \"main\"))\nawait runtime.register_agent_instance(a2, AgentId(\"counter\", \"backup\"))","handlingStrategy":"validation","validationCode":"async def register_instance_if_absent(runtime, agent, agent_id):\n    if agent_id not in runtime._instantiated_agents:\n        await runtime.register_agent_instance(agent, agent_id)\n        return True\n    return False","typeGuard":null,"tryCatchPattern":"try:\n    await runtime.register_agent_instance(agent, agent_id)\nexcept ValueError as e:\n    if \"already exists\" in str(e):\n        existing = runtime._instantiated_agents[agent_id]\n        # decide: reuse existing or pick a new key\n    else:\n        raise","preventionTips":["Derive keys from stable unique inputs (ids, uuids), never constants","Track registered AgentIds in your bootstrap object","Recreate the runtime on session restart"],"tags":["autogen-core","agent-registration","duplicate","instance"],"backgroundTag":null,"analyzedSha":"027ecf0a379bcc1d09956d46d12d44a3ad9cee14","analyzedAt":"2026-08-15T03:38:00.719Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}