{"record":{"id":"d123f1ebbb51cbb4","repo":"microsoft/autogen","slug":"agent-with-id-agent-id-already-exists-d123f1","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-ext/src/autogen_ext/runtimes/grpc/_worker_runtime.py","lineNumber":757,"sourceCode":"\n        self._agent_factories[type.type] = factory_wrapper\n        # Send the registration request message to the host.\n        await self._register_agent_type(type.type)\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            await self._register_agent_type(agent_id.type)\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]],","sourceCodeStart":739,"sourceCodeEnd":775,"githubUrl":"https://github.com/microsoft/autogen/blob/027ecf0a379bcc1d09956d46d12d44a3ad9cee14/python/packages/autogen-ext/src/autogen_ext/runtimes/grpc/_worker_runtime.py#L739-L775","documentation":"register_agent_instance stores instances in self._instantiated_agents keyed by AgentId. If the exact AgentId (type + key) is already present it raises ValueError('Agent with id {agent_id} already exists.') to prevent silently replacing a bound, running agent. This is a per-worker duplicate check, independent of registrations on other workers.","triggerScenarios":"Calling register_agent_instance twice with the same AgentId on one runtime; re-running setup code (notebook cell, test fixture) against a runtime that still holds the previous registration; constructing the same logical agent in a loop with a constant key.","commonSituations":"Notebook re-execution without recreating the runtime; pytest fixtures that register a fixed AgentId on a session-scoped runtime; scripts that register agents on every retry of a connection loop.","solutions":["Check the id is not already registered before registering (inspect via runtime.try_get_underlying_agent_instance or track registered ids yourself)","Use distinct keys per registration (e.g. uuid suffix) when the same type must hold several instances","Recreate the runtime (or restart the kernel/fixture) between runs so _instantiated_agents resets","Move registration into an idempotent setup function executed once per process"],"exampleFix":"# before\nawait runtime.register_agent_instance(agent, AgentId('assistant', 'default'))  # re-run -> ValueError\n\n# after\naid = AgentId('assistant', 'default')\ntry:\n    await runtime.register_agent_instance(agent, aid)\nexcept ValueError:\n    pass  # already registered this run\n# or: key = f'default-{uuid4()}' when multiple instances are intended","handlingStrategy":"try-catch","validationCode":"def id_free(runtime, agent_id) -> bool:\n    return agent_id not in getattr(runtime, '_instantiated_agents', {})","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        pass  # already registered this session\n    else:\n        raise","preventionTips":["Track registered AgentIds in app code and skip duplicates","Restart runtime/kernel between notebook or test re-runs","Use uuid-suffixed keys when registering many instances","Keep registration in idempotent setup code"],"tags":["registration","duplicate","agent-id"],"backgroundTag":null,"analyzedSha":"027ecf0a379bcc1d09956d46d12d44a3ad9cee14","analyzedAt":"2026-08-15T03:38:00.719Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}