microsoft/autogen · 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
Raised by SubscriptionInstantiationContext.agent_type() when the backing ContextVar has no value set — i.e. the call happens outside an agent-instantiation context established by populate_context(). Note the message text says 'runtime()' even though the method is agent_type(); the meaning is the same: you are not inside runtime-managed agent construction. The runtime sets this context var only while its agent factories run, which is how an agent can discover which agent type is instantiating it (used by subscription-mapped instantiation).
Source
Thrown at python/packages/autogen-core/src/autogen_core/_subscription_context.py:31
_SUBSCRIPTION_CONTEXT_VAR: ClassVar[ContextVar[AgentType]] = ContextVar("_SUBSCRIPTION_CONTEXT_VAR")
@classmethod
@contextmanager
def populate_context(cls, ctx: AgentType) -> Generator[None, Any, None]:
""":meta private:"""
token = SubscriptionInstantiationContext._SUBSCRIPTION_CONTEXT_VAR.set(ctx)
try:
yield
finally:
SubscriptionInstantiationContext._SUBSCRIPTION_CONTEXT_VAR.reset(token)
@classmethod
def agent_type(cls) -> AgentType:
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 027ecf0a37)
Solutions
- Create agents through the runtime (register a factory and let AgentRuntime instantiate it) so populate_context is active during construction.
- In tests, wrap direct construction: `with SubscriptionInstantiationContext.populate_context(AgentType("my_agent")): agent = MyAgent(...)`.
- Move the agent_type() call out of module-level or post-construction code paths into the constructor (where the runtime guarantees the context).
- If you don't need subscription-context awareness, remove the agent_type() call entirely.
Example fix
# before
agent = MyAgent() # MyAgent.__init__ calls SubscriptionInstantiationContext.agent_type() -> RuntimeError
# after
from autogen_core import AgentType
with SubscriptionInstantiationContext.populate_context(AgentType("my_agent")):
agent = MyAgent() Defensive patterns
Strategy: validation
Validate before calling
from contextvars import LookupError as CVLookupError
def has_instantiation_context() -> bool:
try:
SubscriptionInstantiationContext.agent_type()
return True
except RuntimeError:
return False
# or directly:
# SubscriptionInstantiationContext._SUBSCRIPTION_CONTEXT_VAR.get() raising LookupError means no context Try / catch
try:
agent_type = SubscriptionInstantiationContext.agent_type()
except RuntimeError:
agent_type = None # not inside runtime-managed instantiation; use explicit AgentType instead Prevention
- Always let the runtime instantiate agents (register factories) rather than calling agent constructors directly.
- In unit tests, wrap direct construction in populate_context(AgentType(...)).
- Never call agent_type() from background tasks spawned outside construction time.
When it happens
Trigger: Calling SubscriptionInstantiationContext.agent_type() in module scope, in __init__ of an agent you constructed directly with `MyAgent()` instead of through the runtime, or in a background task spawned outside the instantiation window (the ContextVar value does not propagate to tasks created before it was set).
Common situations: Unit tests that instantiate agent classes directly (`agent = MyAgent()`) but whose __init__ or a helper calls agent_type(); calling an agent's subscription-registration helper outside the runtime lifecycle; copy-pasting runtime-internal code into application code.
Related errors
- Agent with name {id.type} is not of type {type.__name__}. It
- SubscriptionInstantiationContext cannot be instantiated. It
- TopicId does not match the subscription
- TopicId does not match the subscription
- AgentInstantiationContext.runtime() must be called within an
AI-assisted analysis of microsoft/autogen@027ecf0a37 (2026-08-15).
Data as JSON: /api/errors/06a3daa67afe1605.
Report an issue: GitHub.