microsoft/semantic-kernel · error · RuntimeError

SubscriptionInstantiationContext.runtime() must be called wi

Error message

SubscriptionInstantiationContext.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

agent_type() reads a ContextVar that is set only while the runtime is instantiating an agent (inside populate_context). When the ContextVar is unset, ContextVar.get() raises LookupError, which is caught and re-raised as RuntimeError. This almost always means an agent was constructed directly instead of through the runtime.

Source

Thrown at python/semantic_kernel/agents/runtime/in_process/subscription_context.py:41

    _SUBSCRIPTION_CONTEXT_VAR: ClassVar[ContextVar[AgentType]] = ContextVar("_SUBSCRIPTION_CONTEXT_VAR")

    @classmethod
    @contextmanager
    def populate_context(cls, ctx: AgentType) -> Generator[None, Any, None]:
        """Populate the context with the agent type."""
        token = SubscriptionInstantiationContext._SUBSCRIPTION_CONTEXT_VAR.set(ctx)
        try:
            yield
        finally:
            SubscriptionInstantiationContext._SUBSCRIPTION_CONTEXT_VAR.reset(token)

    @classmethod
    def agent_type(cls) -> AgentType:
        """Get the agent type from the context."""
        try:
            return cls._SUBSCRIPTION_CONTEXT_VAR.get()
        except LookupError as e:
            raise RuntimeError(
                "SubscriptionInstantiationContext.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

View on GitHub (pinned to c028a0c7dc)

Solutions

  1. Instantiate agents through the runtime API (get/register helpers) so populate_context is active during construction.
  2. If you must call agent_type manually, wrap the call in `with SubscriptionInstantiationContext.populate_context(agent_type):`
  3. When spawning tasks, ensure they run within the same context or re-establish it, since ContextVar values do not cross certain boundaries automatically.

Example fix

// before
agent = MyAgent(name="a", runtime=runtime)  # constructor reads agent_type() -> no context set

// after
agent = await runtime.get_agent(...)  # runtime sets the instantiation context first
Defensive patterns

Strategy: try-catch

Validate before calling

# Prefer not to call agent_type() yourself. If you must, ensure a context is active:
from semantic_kernel.agents.runtime.in_process.subscription_context import SubscriptionInstantiationContext

try:
    SubscriptionInstantiationContext._SUBSCRIPTION_CONTEXT_VAR.get()
    has_context = True
except LookupError:
    has_context = False
if not has_context:
    raise RuntimeError('no instantiation context; obtain the agent via the runtime instead')

Try / catch

try:
    agent_type = SubscriptionInstantiationContext.agent_type()
except RuntimeError:
    # no context: fall back to runtime-managed instantiation
    agent = await runtime.get_agent(...)

Prevention

When it happens

Trigger: Calling SubscriptionInstantiationContext.agent_type() from application code outside the runtime's instantiation flow, or constructing an agent directly (e.g. `MyAgent(...)`) whose constructor reads agent_type() instead of obtaining the agent via the runtime (`await runtime.get_agent` / register-and-get APIs).

Common situations: Direct agent instantiation bypassing the runtime; calling agent_type in a separate asyncio Task or thread to which the ContextVar was not propagated; testing an agent in isolation without establishing the context.

Related errors


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