{"record":{"id":"4e7859e9d96ca9ff","repo":"microsoft/autogen","slug":"agentinstantiationcontext-runtime-must-be-called","errorCode":null,"errorMessage":"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.","messagePattern":"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\\.","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"python/packages/autogen-core/src/autogen_core/_agent_instantiation.py","lineNumber":109,"sourceCode":"        \"_AGENT_INSTANTIATION_CONTEXT_VAR\"\n    )\n\n    @classmethod\n    @contextmanager\n    def populate_context(cls, ctx: tuple[AgentRuntime, AgentId]) -> Generator[None, Any, None]:\n        \"\"\":meta private:\"\"\"\n        token = AgentInstantiationContext._AGENT_INSTANTIATION_CONTEXT_VAR.set(ctx)\n        try:\n            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":91,"sourceCodeEnd":127,"githubUrl":"https://github.com/microsoft/autogen/blob/027ecf0a379bcc1d09956d46d12d44a3ad9cee14/python/packages/autogen-core/src/autogen_core/_agent_instantiation.py#L91-L127","documentation":"current_runtime() reads a ContextVar that is only set while a runtime is inside its agent-factory call (via populate_context). Calling it outside that window raises LookupError from ContextVar.get(), which is re-raised as RuntimeError. The message text incorrectly names the method 'runtime()'; the real cause is that no instantiation context is active.","triggerScenarios":"Directly constructing an agent (MyAgent(...)) instead of having the runtime instantiate it via a registered factory; calling BaseAgent.__init__ (which calls current_runtime()) from outside runtime.try_instantiate_agent; accessing current_runtime() in module import time, background tasks, or threads/tasks outside the factory call's context.","commonSituations":"Writing a custom agent whose __init__ (or something it calls, e.g. a client library) queries AgentInstantiationContext; unit tests that new-up agents manually; async code that hops tasks so the context var is no longer visible.","solutions":["Register the agent type with a runtime and let the runtime instantiate it: runtime.register('my_agent', lambda: MyAgent('desc')) then send a message or call runtime.get('my_agent', key).","If manual/binding instantiation is intended, subclass BaseAgent and use await agent.bind_id_and_runtime(id, runtime) instead of relying on the instantiation context.","Guard the call with AgentInstantiationContext.is_in_factory_call() before reading current_runtime().","In tests, wrap instantiation in AgentInstantiationContext.populate_context((runtime, agent_id))."],"exampleFix":"# before\nagent = MyAgent(\"does work\")  # __init__ calls current_runtime() -> RuntimeError\n\n# after\nruntime = SingleThreadedAgentRuntime()\nawait MyAgent.register(runtime, \"my_agent\", lambda: MyAgent(\"does work\"))\nagent = await runtime.get(\"my_agent\")  # instantiated inside factory context","handlingStrategy":"validation","validationCode":"from autogen_core import AgentInstantiationContext\n\nif not AgentInstantiationContext.is_in_factory_call():\n    # defer runtime access; construct via a registered factory instead\n    raise RuntimeError(\"construct agents via runtime.register(...) factory\")\nruntime = AgentInstantiationContext.current_runtime()","typeGuard":null,"tryCatchPattern":"try:\n    runtime = AgentInstantiationContext.current_runtime()\nexcept RuntimeError as e:\n    if \"must be called within an instantiation context\" in str(e):\n        # e.g. fall back to deferred binding via bind_id_and_runtime\n        raise\n    raise","preventionTips":["Always create agents through runtime-registered factories, never direct constructor calls.","Guard any context read with is_in_factory_call() first.","In custom agents, design __init__ to not need the runtime; move runtime-dependent logic to message handlers."],"tags":["autogen-core","context","instantiation","asyncio"],"backgroundTag":null,"analyzedSha":"027ecf0a379bcc1d09956d46d12d44a3ad9cee14","analyzedAt":"2026-08-15T03:38:00.719Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}