microsoft/autogen · 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() reads a ContextVar that is only set while a runtime is inside its agent-factory call (via populate_context). Calling it outside that window raises LookupError from ContextVar.get(), which is re-raised as RuntimeError. The message text incorrectly names the method 'runtime()'; the real cause is that no instantiation context is active.

Source

Thrown at python/packages/autogen-core/src/autogen_core/_agent_instantiation.py:109

        "_AGENT_INSTANTIATION_CONTEXT_VAR"
    )

    @classmethod
    @contextmanager
    def populate_context(cls, ctx: tuple[AgentRuntime, AgentId]) -> Generator[None, Any, None]:
        """:meta private:"""
        token = AgentInstantiationContext._AGENT_INSTANTIATION_CONTEXT_VAR.set(ctx)
        try:
            yield
        finally:
            AgentInstantiationContext._AGENT_INSTANTIATION_CONTEXT_VAR.reset(token)

    @classmethod
    def current_runtime(cls) -> AgentRuntime:
        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:
        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

    @classmethod
    def is_in_factory_call(cls) -> bool:
        if cls._AGENT_INSTANTIATION_CONTEXT_VAR.get(None) is None:
            return False
        return True

View on GitHub (pinned to 027ecf0a37)

Solutions

  1. Register the agent type with a runtime and let the runtime instantiate it: runtime.register('my_agent', lambda: MyAgent('desc')) then send a message or call runtime.get('my_agent', key).
  2. If manual/binding instantiation is intended, subclass BaseAgent and use await agent.bind_id_and_runtime(id, runtime) instead of relying on the instantiation context.
  3. Guard the call with AgentInstantiationContext.is_in_factory_call() before reading current_runtime().
  4. In tests, wrap instantiation in AgentInstantiationContext.populate_context((runtime, agent_id)).

Example fix

# before
agent = MyAgent("does work")  # __init__ calls current_runtime() -> RuntimeError

# after
runtime = SingleThreadedAgentRuntime()
await MyAgent.register(runtime, "my_agent", lambda: MyAgent("does work"))
agent = await runtime.get("my_agent")  # instantiated inside factory context
Defensive patterns

Strategy: validation

Validate before calling

from autogen_core import AgentInstantiationContext

if not AgentInstantiationContext.is_in_factory_call():
    # defer runtime access; construct via a registered factory instead
    raise RuntimeError("construct agents via runtime.register(...) factory")
runtime = AgentInstantiationContext.current_runtime()

Try / catch

try:
    runtime = AgentInstantiationContext.current_runtime()
except RuntimeError as e:
    if "must be called within an instantiation context" in str(e):
        # e.g. fall back to deferred binding via bind_id_and_runtime
        raise
    raise

Prevention

When it happens

Trigger: Directly constructing an agent (MyAgent(...)) instead of having the runtime instantiate it via a registered factory; calling BaseAgent.__init__ (which calls current_runtime()) from outside runtime.try_instantiate_agent; accessing current_runtime() in module import time, background tasks, or threads/tasks outside the factory call's context.

Common situations: Writing a custom agent whose __init__ (or something it calls, e.g. a client library) queries AgentInstantiationContext; unit tests that new-up agents manually; async code that hops tasks so the context var is no longer visible.

Related errors


AI-assisted analysis of microsoft/autogen@027ecf0a37 (2026-08-15). Data as JSON: /api/errors/4e7859e9d96ca9ff. Report an issue: GitHub.