{"record":{"id":"7a92f1220190cbe6","repo":"microsoft/semantic-kernel","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/semantic_kernel/agents/runtime/in_process/agent_instantiation_context.py","lineNumber":61,"sourceCode":"    @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":43,"sourceCodeEnd":66,"githubUrl":"https://github.com/microsoft/semantic-kernel/blob/c028a0c7dc4f0814cdcbaba9d998f187a41197bf/python/semantic_kernel/agents/runtime/in_process/agent_instantiation_context.py#L43-L66","documentation":"current_agent_id() mirrors current_runtime() — it reads the second element of the tuple stored in _AGENT_INSTANTIATION_CONTEXT_VAR. It fails identically when no instantiation context is active, producing a RuntimeError that directs you to use the runtime for agent creation.","triggerScenarios":"Calling AgentInstantiationContext.current_agent_id() outside the runtime's instantiation flow — either by directly constructing the agent or by calling it from code that runs after the populate_context context manager has exited.","commonSituations":"An agent's __init__ calls current_agent_id() but the agent was constructed directly in user code rather than through the runtime. Also seen when agent initialization logic is triggered lazily (e.g. first message) rather than eagerly at construction.","solutions":["Ensure the agent is instantiated through the runtime (register_factory + get_agent), which populates the context.","Capture the agent_id at construction time and store it as an instance attribute for later use.","If you must construct outside the runtime, accept the agent_id as an explicit parameter instead of relying on the context var."],"exampleFix":"# before\nclass MyAgent(Agent):\n    def __init__(self):\n        super().__init__()\n        self.my_id = AgentInstantiationContext.current_agent_id()  # raises\n\n# after\nclass MyAgent(Agent):\n    def __init__(self):\n        super().__init__()\n        self.my_id = AgentInstantiationContext.current_agent_id()  # works when runtime constructs it","handlingStrategy":"try-catch","validationCode":"null","typeGuard":"null","tryCatchPattern":"from semantic_kernel.agents.runtime.in_process.agent_instantiation_context import AgentInstantiationContext\ntry:\n    agent_id = AgentInstantiationContext.current_agent_id()\nexcept RuntimeError:\n    # Not in an instantiation context\n    agent_id = None  # or raise a more descriptive error","preventionTips":["Ensure agents are instantiated through the runtime so the ContextVar is populated.","Store agent_id as an instance attribute during __init__ rather than calling current_agent_id() later."],"tags":["agent-runtime","contextvar","instantiation","agent-id","semantic-kernel"],"backgroundTag":null,"analyzedSha":"c028a0c7dc4f0814cdcbaba9d998f187a41197bf","analyzedAt":"2026-08-13T13:48:05.040Z","schemaVersion":2},"datasetVersion":"2026-08-13T14:17:21.547Z"}