{"record":{"id":"06a3daa67afe1605","repo":"microsoft/autogen","slug":"subscriptioninstantiationcontext-runtime-must-be","errorCode":null,"errorMessage":"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.","messagePattern":"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\\.","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"python/packages/autogen-core/src/autogen_core/_subscription_context.py","lineNumber":31,"sourceCode":"\n    _SUBSCRIPTION_CONTEXT_VAR: ClassVar[ContextVar[AgentType]] = ContextVar(\"_SUBSCRIPTION_CONTEXT_VAR\")\n\n    @classmethod\n    @contextmanager\n    def populate_context(cls, ctx: AgentType) -> Generator[None, Any, None]:\n        \"\"\":meta private:\"\"\"\n        token = SubscriptionInstantiationContext._SUBSCRIPTION_CONTEXT_VAR.set(ctx)\n        try:\n            yield\n        finally:\n            SubscriptionInstantiationContext._SUBSCRIPTION_CONTEXT_VAR.reset(token)\n\n    @classmethod\n    def agent_type(cls) -> AgentType:\n        try:\n            return cls._SUBSCRIPTION_CONTEXT_VAR.get()\n        except LookupError as e:\n            raise RuntimeError(\n                \"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.\"\n            ) from e\n","sourceCodeStart":13,"sourceCodeEnd":34,"githubUrl":"https://github.com/microsoft/autogen/blob/027ecf0a379bcc1d09956d46d12d44a3ad9cee14/python/packages/autogen-core/src/autogen_core/_subscription_context.py#L13-L34","documentation":"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).","triggerScenarios":"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).","commonSituations":"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.","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."],"exampleFix":"# before\nagent = MyAgent()  # MyAgent.__init__ calls SubscriptionInstantiationContext.agent_type() -> RuntimeError\n\n# after\nfrom autogen_core import AgentType\nwith SubscriptionInstantiationContext.populate_context(AgentType(\"my_agent\")):\n    agent = MyAgent()","handlingStrategy":"validation","validationCode":"from contextvars import LookupError as CVLookupError\n\ndef has_instantiation_context() -> bool:\n    try:\n        SubscriptionInstantiationContext.agent_type()\n        return True\n    except RuntimeError:\n        return False\n\n# or directly:\n# SubscriptionInstantiationContext._SUBSCRIPTION_CONTEXT_VAR.get() raising LookupError means no context","typeGuard":null,"tryCatchPattern":"try:\n    agent_type = SubscriptionInstantiationContext.agent_type()\nexcept RuntimeError:\n    agent_type = None  # not inside runtime-managed instantiation; use explicit AgentType instead","preventionTips":["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."],"tags":["python","autogen-core","subscriptions","context","agents","testing"],"backgroundTag":null,"analyzedSha":"027ecf0a379bcc1d09956d46d12d44a3ad9cee14","analyzedAt":"2026-08-15T03:38:00.719Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}