{"record":{"id":"1ba1f43e0c2f526a","repo":"microsoft/autogen","slug":"agent-with-type-type-already-exists-1ba1f4","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-ext/src/autogen_ext/runtimes/grpc/_worker_runtime.py","lineNumber":724,"sourceCode":"        if self._host_connection is None:\n            raise RuntimeError(\"Host connection is not set.\")\n        message = agent_worker_pb2.RegisterAgentTypeRequest(type=agent_type)\n        _response: agent_worker_pb2.RegisterAgentTypeResponse = await self._host_connection.stub.RegisterAgent(\n            message, metadata=self._host_connection.metadata\n        )\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        if self._host_connection is None:\n            raise RuntimeError(\"Host connection is not set.\")\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        # Send the registration request message to the host.\n        await self._register_agent_type(type.type)","sourceCodeStart":706,"sourceCodeEnd":742,"githubUrl":"https://github.com/microsoft/autogen/blob/027ecf0a379bcc1d09956d46d12d44a3ad9cee14/python/packages/autogen-ext/src/autogen_ext/runtimes/grpc/_worker_runtime.py#L706-L742","documentation":"GrpcWorkerAgentRuntime.register_factory stores factories in a dict keyed by AgentType.type. If the key already exists it raises ValueError('Agent with type {type} already exists.') to prevent one factory from silently replacing another. The check is purely local to this worker process, independent of what other workers registered.","triggerScenarios":"Calling register_factory twice with the same type string or AgentType on the same runtime instance; registering both a factory and an agent instance under the same type name; module-level registration code that re-executes (e.g. notebook re-runs, hot reload) against a still-alive runtime.","commonSituations":"Jupyter notebooks where a cell registering agents is re-run without restarting the kernel; test suites that build one runtime per session but reuse a module-level registry; copy-pasted registration code hitting the same type name; for-loops that accidentally register the same type on every iteration.","solutions":["Guard or deduplicate registration: check the type is not already registered before calling register_factory","Use unique type names per registration attempt (e.g. suffix with a run id) when re-registration is expected","Restart the runtime/kernel between notebook or test runs so the in-memory factory map resets","Restructure code so registration happens exactly once per process (register in a single setup function)"],"exampleFix":"# before\nawait runtime.register_factory(MyAgent, MyAgent)  # re-run cell -> ValueError\n\n# after\nif MyAgent not in [str(t) for t in registered]:\n    await runtime.register_factory(MyAgent, MyAgent)\n# or in notebooks: recreate the runtime / restart kernel before re-registering","handlingStrategy":"validation","validationCode":"def already_registered(runtime, agent_type: str) -> bool:\n    return agent_type in getattr(runtime, '_agent_factories', {})","typeGuard":null,"tryCatchPattern":"try:\n    await runtime.register_factory(MyAgent, MyAgent)\nexcept ValueError as e:\n    if 'already exists' in str(e):\n        pass  # idempotent setup\n    else:\n        raise","preventionTips":["Centralize agent registration in one idempotent setup function","Recreate the runtime/kernel before re-running registration cells","Use unique type names per run when re-registration is expected","Assert type uniqueness in test fixtures"],"tags":["registration","duplicate","agent-type"],"backgroundTag":null,"analyzedSha":"027ecf0a379bcc1d09956d46d12d44a3ad9cee14","analyzedAt":"2026-08-15T03:38:00.719Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}