microsoft/semantic-kernel · error · RuntimeError

AgentInstantiationContext.agent_id() must be called within a

Error message

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.

What it means

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.

Source

Thrown at python/semantic_kernel/agents/runtime/in_process/agent_instantiation_context.py:61

    @classmethod
    def current_runtime(cls) -> CoreRuntime:
        """Get the current runtime."""
        try:
            return cls._AGENT_INSTANTIATION_CONTEXT_VAR.get()[0]
        except LookupError as e:
            raise RuntimeError(
                "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."
            ) from e

    @classmethod
    def current_agent_id(cls) -> AgentId:
        """Get the current agent ID."""
        try:
            return cls._AGENT_INSTANTIATION_CONTEXT_VAR.get()[1]
        except LookupError as e:
            raise RuntimeError(
                "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."
            ) from e

View on GitHub (pinned to c028a0c7dc)

Solutions

  1. Ensure the agent is instantiated through the runtime (register_factory + get_agent), which populates the context.
  2. Capture the agent_id at construction time and store it as an instance attribute for later use.
  3. If you must construct outside the runtime, accept the agent_id as an explicit parameter instead of relying on the context var.

Example fix

# before
class MyAgent(Agent):
    def __init__(self):
        super().__init__()
        self.my_id = AgentInstantiationContext.current_agent_id()  # raises

# after
class MyAgent(Agent):
    def __init__(self):
        super().__init__()
        self.my_id = AgentInstantiationContext.current_agent_id()  # works when runtime constructs it
Defensive patterns

Strategy: try-catch

Validate before calling

null

Type guard

null

Try / catch

from semantic_kernel.agents.runtime.in_process.agent_instantiation_context import AgentInstantiationContext
try:
    agent_id = AgentInstantiationContext.current_agent_id()
except RuntimeError:
    # Not in an instantiation context
    agent_id = None  # or raise a more descriptive error

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


AI-assisted analysis of microsoft/semantic-kernel@c028a0c7dc (2026-08-13). Data as JSON: /api/errors/7a92f1220190cbe6. Report an issue: GitHub.