microsoft/semantic-kernel · error · RuntimeError

AgentInstantiationContext.runtime() must be called within an

Error message

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.

What it means

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.

Source

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

    )

    @classmethod
    @contextmanager
    def populate_context(cls, ctx: tuple[CoreRuntime, AgentId]) -> Generator[None, Any, None]:
        """Populate the context with the current runtime and agent ID."""
        token = AgentInstantiationContext._AGENT_INSTANTIATION_CONTEXT_VAR.set(ctx)
        try:
            yield
        finally:
            AgentInstantiationContext._AGENT_INSTANTIATION_CONTEXT_VAR.reset(token)

    @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. 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.
  2. 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.
  3. In tests, use a real InProcessRuntime with register_factory rather than directly constructing agents.

Example fix

# before
agent = MyAgent(...)
runtime = AgentInstantiationContext.current_runtime()  # raises

# after
await runtime.register_factory("MyAgent", lambda: MyAgent(...))
agent = await runtime.get_agent(AgentId("MyAgent", "default"))
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:
    runtime = AgentInstantiationContext.current_runtime()
except RuntimeError:
    # Not in an instantiation context — use explicit runtime reference instead
    runtime = my_explicit_runtime_ref

Prevention

When it happens

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

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

Related errors


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