{"record":{"id":"56d7be8dc814f31f","repo":"microsoft/semantic-kernel","slug":"baseagent-must-be-instantiated-within-the-context","errorCode":null,"errorMessage":"BaseAgent must be instantiated within the context of an AgentRuntime. It cannot be directly instantiated.","messagePattern":"BaseAgent must be instantiated within the context of an AgentRuntime\\. It cannot be directly instantiated\\.","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"critical","filePath":"python/semantic_kernel/agents/runtime/core/base_agent.py","lineNumber":100,"sourceCode":"        return cls.internal_extra_handles_types\n\n    @classmethod\n    def _unbound_subscriptions(cls) -> list[UnboundSubscription]:\n        return cls.internal_unbound_subscriptions_list\n\n    @property\n    def metadata(self) -> AgentMetadata:\n        \"\"\"Get the metadata for this agent.\"\"\"\n        assert self._id is not None  # nosec\n        return CoreAgentMetadata(key=self._id.key, type=self._id.type, description=self._description)\n\n    def __init__(self, description: str) -> None:\n        \"\"\"Initialize the agent.\"\"\"\n        try:\n            runtime = AgentInstantiationContext.current_runtime()\n            id = AgentInstantiationContext.current_agent_id()\n        except LookupError as e:\n            raise RuntimeError(\n                \"BaseAgent must be instantiated within the context of an AgentRuntime. It cannot be directly \"\n                \"instantiated.\"\n            ) from e\n\n        self._runtime: CoreRuntime = runtime\n        self._id: AgentId = id\n        if not isinstance(description, str):\n            raise ValueError(\"Agent description must be a string\")\n        self._description = description\n\n    @property\n    def type(self) -> str:\n        \"\"\"Get the type of the agent.\"\"\"\n        return self.id.type\n\n    @property\n    def id(self) -> AgentId:\n        \"\"\"Get the id of the agent.\"\"\"","sourceCodeStart":82,"sourceCodeEnd":118,"githubUrl":"https://github.com/microsoft/semantic-kernel/blob/c028a0c7dc4f0814cdcbaba9d998f187a41197bf/python/semantic_kernel/agents/runtime/core/base_agent.py#L82-L118","documentation":"Raised by BaseAgent.__init__ when there is no active AgentInstantiationContext (no current runtime and agent id set via context vars). BaseAgent instances must be created by the runtime (which sets the context), never by calling the constructor directly, because the runtime assigns the id and wires messaging.","triggerScenarios":"Calling MyAgent(...) directly in user code instead of registering it through CoreRuntime via agent_type/my_factory and letting the runtime instantiate it. Also raised when context vars were cleared (e.g. instantiating in a different thread/task without context propagation).","commonSituations":"Trying to unit-test an agent by constructing it directly; instantiating inside a background task/thread that did not inherit AgentInstantiationContext; registering a factory incorrectly so the runtime never sets the context before __init__.","solutions":["Register the agent with the runtime and let it instantiate: await runtime.register('my-type', lambda: MyAgent(...)).","For unit tests, set the context via AgentInstantiationContext.set/runtime before constructing, or use the runtime's test helpers.","If instantiating in a spawned task, propagate context vars (contextvars.copy_context().run(...)).","Do not call MyAgent() outside a runtime-managed factory."],"exampleFix":"// before\nagent = MyAgent(description=\"d\")   # direct construction -> RuntimeError\n// after\nawait runtime.register(\"my-agent\", lambda: MyAgent(description=\"d\"))\nagent = await runtime.try_get_agent(CoreAgentId(\"my-agent\", \"default\"), MyAgent)","handlingStrategy":"try-catch","validationCode":"from semantic_kernel.agents.runtime.in_process import AgentInstantiationContext\n\ndef has_instantiation_context() -> bool:\n    try:\n        AgentInstantiationContext.current_runtime()\n        AgentInstantiationContext.current_agent_id()\n        return True\n    except LookupError:\n        return False","typeGuard":"from semantic_kernel.agents.runtime.in_process import AgentInstantiationContext\n\ndef is_inside_runtime() -> bool:\n    try:\n        AgentInstantiationContext.current_runtime()\n        return True\n    except LookupError:\n        return False","tryCatchPattern":"try:\n    agent = MyAgent(description=\"d\")\nexcept RuntimeError as e:\n    if \"AgentRuntime\" in str(e):\n        # must go through the runtime instead\n        await runtime.register(\"my-agent\", lambda: MyAgent(description=\"d\"))\n        agent = await runtime.try_get_agent(CoreAgentId(\"my-agent\", \"default\"), MyAgent)\n    else:\n        raise","preventionTips":["Never call BaseAgent subclasses directly; always register them with the runtime.","For tests, set AgentInstantiationContext before constructing.","Propagate contextvars when spawning tasks that instantiate agents.","Use runtime factory functions for all agent creation."],"tags":["runtime","agent-lifecycle","context","semantic-kernel"],"backgroundTag":null,"analyzedSha":"c028a0c7dc4f0814cdcbaba9d998f187a41197bf","analyzedAt":"2026-08-13T13:48:05.040Z","schemaVersion":2},"datasetVersion":"2026-08-13T14:17:21.547Z"}