{"record":{"id":"861e85f58def5595","repo":"microsoft/autogen","slug":"agentinstantiationcontext-agent-id-must-be-calle","errorCode":null,"errorMessage":"AgentInstantiationContext.agent_id() must be called within an instantiation context such as when the AgentRuntime is instantiating an agent. Mostly likely this was caused by directly instantiating an agent instead of using the AgentRuntime to do so.","messagePattern":"AgentInstantiationContext\\.agent_id\\(\\) must be called within an instantiation context such as when the AgentRuntime is instantiating an agent\\. Mostly likely this was caused by directly instantiating an agent instead of using the AgentRuntime to do so\\.","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"python/packages/autogen-core/src/autogen_core/_agent_instantiation.py","lineNumber":118,"sourceCode":"            yield\n        finally:\n            AgentInstantiationContext._AGENT_INSTANTIATION_CONTEXT_VAR.reset(token)\n\n    @classmethod\n    def current_runtime(cls) -> AgentRuntime:\n        try:\n            return cls._AGENT_INSTANTIATION_CONTEXT_VAR.get()[0]\n        except LookupError as e:\n            raise RuntimeError(\n                \"AgentInstantiationContext.runtime() must be called within an instantiation context such as when the AgentRuntime is instantiating an agent. Mostly likely this was caused by directly instantiating an agent instead of using the AgentRuntime to do so.\"\n            ) from e\n\n    @classmethod\n    def current_agent_id(cls) -> AgentId:\n        try:\n            return cls._AGENT_INSTANTIATION_CONTEXT_VAR.get()[1]\n        except LookupError as e:\n            raise RuntimeError(\n                \"AgentInstantiationContext.agent_id() must be called within an instantiation context such as when the AgentRuntime is instantiating an agent. Mostly likely this was caused by directly instantiating an agent instead of using the AgentRuntime to do so.\"\n            ) from e\n\n    @classmethod\n    def is_in_factory_call(cls) -> bool:\n        if cls._AGENT_INSTANTIATION_CONTEXT_VAR.get(None) is None:\n            return False\n        return True\n","sourceCodeStart":100,"sourceCodeEnd":127,"githubUrl":"https://github.com/microsoft/autogen/blob/027ecf0a379bcc1d09956d46d12d44a3ad9cee14/python/packages/autogen-core/src/autogen_core/_agent_instantiation.py#L100-L127","documentation":"current_agent_id() reads the same instantiation-context ContextVar as current_runtime(); outside a runtime factory call it raises LookupError, re-raised as RuntimeError. The message's 'agent_id()' name matches the classmethod but the 'directly instantiating an agent' explanation is the usual root cause.","triggerScenarios":"An agent's __init__ (or helper it calls) invoking AgentInstantiationContext.current_agent_id() when the agent was constructed manually rather than by a registered runtime factory; calling it from code running before runtime instantiation or in a detached task/thread.","commonSituations":"Custom agents that want their own ID at construction time (for logging, self-addressing); refactors that move agent construction out of the factory; test harnesses that instantiate agents directly.","solutions":["Let the runtime instantiate the agent (register a factory, then get/send) so the context var carries (runtime, agent_id).","Check AgentInstantiationContext.is_in_factory_call() first and defer ID-dependent logic to on_message or bind_id_and_runtime.","For manual construction, call await agent.bind_id_and_runtime(AgentId('type','key'), runtime) and read agent.id afterwards."],"exampleFix":"# before\nself._id = AgentInstantiationContext.current_agent_id()  # RuntimeError when manual\n\n# after\nif AgentInstantiationContext.is_in_factory_call():\n    self._id = AgentInstantiationContext.current_agent_id()\n# else: ID arrives later via bind_id_and_runtime(); use self.id lazily","handlingStrategy":"validation","validationCode":"from autogen_core import AgentInstantiationContext\n\nif AgentInstantiationContext.is_in_factory_call():\n    my_id = AgentInstantiationContext.current_agent_id()\nelse:\n    my_id = None  # ID arrives later via bind_id_and_runtime / agent.id","typeGuard":null,"tryCatchPattern":"try:\n    aid = AgentInstantiationContext.current_agent_id()\nexcept RuntimeError as e:\n    if \"must be called within an instantiation context\" in str(e):\n        aid = None  # defer ID usage until bound\n    else:\n        raise","preventionTips":["Read agent IDs lazily via self.id inside handlers rather than at construction time.","Use runtime.register + runtime.get so the instantiation context is always present.","Unit-test agents through a real SingleThreadedAgentRuntime to catch context misuse early."],"tags":["autogen-core","context","agent-id","instantiation"],"backgroundTag":null,"analyzedSha":"027ecf0a379bcc1d09956d46d12d44a3ad9cee14","analyzedAt":"2026-08-15T03:38:00.719Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}