microsoft/autogen · error · RuntimeError

ClosureAgent must be instantiated within the context of an A

Error message

ClosureAgent must be instantiated within the context of an AgentRuntime. It cannot be directly instantiated.

What it means

ClosureAgent.__init__ immediately calls AgentInstantiationContext.current_runtime() and current_agent_id(); outside a runtime factory call both raise, and the except re-raises as RuntimeError. Unlike plain BaseAgent subclasses, ClosureAgent cannot be constructed standalone or via bind_id_and_runtime — it must be created by a registered runtime factory.

Source

Thrown at python/packages/autogen-core/src/autogen_core/_closure_agent.py:88

        topic_id: TopicId,
        *,
        cancellation_token: CancellationToken | None = None,
    ) -> None: ...


class ClosureAgent(BaseAgent, ClosureContext):
    def __init__(
        self,
        description: str,
        closure: Callable[[ClosureContext, T, MessageContext], Awaitable[Any]],
        *,
        unknown_type_policy: Literal["error", "warn", "ignore"] = "warn",
    ) -> None:
        try:
            runtime = AgentInstantiationContext.current_runtime()
            id = AgentInstantiationContext.current_agent_id()
        except Exception as e:
            raise RuntimeError(
                "ClosureAgent must be instantiated within the context of an AgentRuntime. It cannot be directly instantiated."
            ) from e

        self._runtime: AgentRuntime = runtime
        self._id: AgentId = id
        self._description = description
        handled_types = get_handled_types_from_closure(closure)
        self._expected_types = handled_types
        self._closure = closure
        self._unknown_type_policy = unknown_type_policy
        super().__init__(description)

    @property
    def metadata(self) -> AgentMetadata:
        assert self._id is not None
        return AgentMetadata(
            key=self._id.key,
            type=self._id.type,

View on GitHub (pinned to 027ecf0a37)

Solutions

  1. Register via ClosureAgent.register(runtime, "closure_agent", lambda: ClosureAgent("desc", my_closure)) and instantiate through the runtime.
  2. Trigger instantiation by sending a message to the agent or calling await runtime.get("closure_agent").
  3. In tests, instantiate inside populate_context((runtime, AgentId(...))) if you truly need a direct handle.

Example fix

# before
agent = ClosureAgent("d", my_closure)  # RuntimeError

# after
await ClosureAgent.register(
    runtime, "closure_agent", lambda: ClosureAgent("d", my_closure)
)
agent = await runtime.get("closure_agent")
Defensive patterns

Strategy: try-catch

Validate before calling

from autogen_core import AgentInstantiationContext

if not AgentInstantiationContext.is_in_factory_call():
    raise RuntimeError("construct ClosureAgent via runtime-registered factory")

Try / catch

try:
    agent = ClosureAgent("d", closure)
except RuntimeError as e:
    if "must be instantiated within the context of an AgentRuntime" in str(e):
        # fix call site: register factory with a runtime instead
        raise
    raise

Prevention

When it happens

Trigger: ClosureAgent("d", closure) in ordinary code or tests; registering it with a factory that is never invoked through the runtime; constructing inside a thread/task where the ContextVar is not set.

Common situations: Prototyping closures without setting up a runtime; calling the constructor in unit tests instead of registering with SingleThreadedAgentRuntime and using runtime.get()/send_message.

Related errors


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