{"record":{"id":"4ed25421c11fff09","repo":"microsoft/semantic-kernel","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/semantic_kernel/agents/runtime/in_process/agent_instantiation_context.py","lineNumber":49,"sourceCode":"    )\n\n    @classmethod\n    @contextmanager\n    def populate_context(cls, ctx: tuple[CoreRuntime, AgentId]) -> Generator[None, Any, None]:\n        \"\"\"Populate the context with the current runtime and agent ID.\"\"\"\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) -> CoreRuntime:\n        \"\"\"Get the current runtime.\"\"\"\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 \"\n                \"AgentRuntime is instantiating an agent. Mostly likely this was caused by directly instantiating an \"\n                \"agent instead of using the AgentRuntime to do so.\"\n            ) from e\n\n    @classmethod\n    def current_agent_id(cls) -> AgentId:\n        \"\"\"Get the current agent ID.\"\"\"\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 \"\n                \"AgentRuntime is instantiating an agent. Mostly likely this was caused by directly instantiating an \"\n                \"agent instead of using the AgentRuntime to do so.\"\n            ) from e\n","sourceCodeStart":31,"sourceCodeEnd":66,"githubUrl":"https://github.com/microsoft/semantic-kernel/blob/c028a0c7dc4f0814cdcbaba9d998f187a41197bf/python/semantic_kernel/agents/runtime/in_process/agent_instantiation_context.py#L31-L66","documentation":"current_runtime() retrieves the CoreRuntime from a ContextVar (_AGENT_INSTANTIATION_CONTEXT_VAR) that is only populated when the runtime instantiates an agent through its factory. If no instantiation context is active, the ContextVar lookup raises LookupError, which is re-raised as RuntimeError with guidance to use the runtime instead of direct construction.","triggerScenarios":"Calling AgentInstantiationContext.current_runtime() outside of: (a) an agent factory function invoked by the runtime, or (b) an agent's __init__/constructor during runtime-managed instantiation. Directly constructing an agent via `MyAgent(...)` bypasses the runtime's populate_context context manager, leaving the ContextVar unset.","commonSituations":"A developer instantiates an agent directly (e.g. in a test or script) rather than registering it via runtime.register_factory and then calling runtime.get_agent(). Also occurs when agent code calls current_runtime() in an async callback or background task that has escaped the populate_context scope.","solutions":["Register the agent via runtime.register_factory(type, factory_fn) and let the runtime instantiate it — the runtime wraps the factory call in populate_context.","If calling current_runtime() in a deferred callback or background task, capture the runtime/agent_id in a local variable at construction time and pass it through instead of relying on the context var.","In tests, use a real InProcessRuntime with register_factory rather than directly constructing agents."],"exampleFix":"# before\nagent = MyAgent(...)\nruntime = AgentInstantiationContext.current_runtime()  # raises\n\n# after\nawait runtime.register_factory(\"MyAgent\", lambda: MyAgent(...))\nagent = await runtime.get_agent(AgentId(\"MyAgent\", \"default\"))","handlingStrategy":"try-catch","validationCode":"null","typeGuard":"null","tryCatchPattern":"from semantic_kernel.agents.runtime.in_process.agent_instantiation_context import AgentInstantiationContext\ntry:\n    runtime = AgentInstantiationContext.current_runtime()\nexcept RuntimeError:\n    # Not in an instantiation context — use explicit runtime reference instead\n    runtime = my_explicit_runtime_ref","preventionTips":["Always construct agents through the runtime (register_factory + get_agent), never directly.","Capture runtime/agent_id at construction time if needed in deferred callbacks.","In tests, use a real InProcessRuntime rather than constructing agents standalone."],"tags":["agent-runtime","contextvar","instantiation","semantic-kernel"],"backgroundTag":null,"analyzedSha":"c028a0c7dc4f0814cdcbaba9d998f187a41197bf","analyzedAt":"2026-08-13T13:48:05.040Z","schemaVersion":2},"datasetVersion":"2026-08-13T14:17:21.547Z"}