microsoft/semantic-kernel · critical · RuntimeError
BaseAgent must be instantiated within the context of an Agen
Error message
BaseAgent must be instantiated within the context of an AgentRuntime. It cannot be directly instantiated.
What it means
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.
Source
Thrown at python/semantic_kernel/agents/runtime/core/base_agent.py:100
return cls.internal_extra_handles_types
@classmethod
def _unbound_subscriptions(cls) -> list[UnboundSubscription]:
return cls.internal_unbound_subscriptions_list
@property
def metadata(self) -> AgentMetadata:
"""Get the metadata for this agent."""
assert self._id is not None # nosec
return CoreAgentMetadata(key=self._id.key, type=self._id.type, description=self._description)
def __init__(self, description: str) -> None:
"""Initialize the agent."""
try:
runtime = AgentInstantiationContext.current_runtime()
id = AgentInstantiationContext.current_agent_id()
except LookupError as e:
raise RuntimeError(
"BaseAgent must be instantiated within the context of an AgentRuntime. It cannot be directly "
"instantiated."
) from e
self._runtime: CoreRuntime = runtime
self._id: AgentId = id
if not isinstance(description, str):
raise ValueError("Agent description must be a string")
self._description = description
@property
def type(self) -> str:
"""Get the type of the agent."""
return self.id.type
@property
def id(self) -> AgentId:
"""Get the id of the agent."""View on GitHub (pinned to c028a0c7dc)
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.
Example fix
// before
agent = MyAgent(description="d") # direct construction -> RuntimeError
// after
await runtime.register("my-agent", lambda: MyAgent(description="d"))
agent = await runtime.try_get_agent(CoreAgentId("my-agent", "default"), MyAgent) Defensive patterns
Strategy: try-catch
Validate before calling
from semantic_kernel.agents.runtime.in_process import AgentInstantiationContext
def has_instantiation_context() -> bool:
try:
AgentInstantiationContext.current_runtime()
AgentInstantiationContext.current_agent_id()
return True
except LookupError:
return False Type guard
from semantic_kernel.agents.runtime.in_process import AgentInstantiationContext
def is_inside_runtime() -> bool:
try:
AgentInstantiationContext.current_runtime()
return True
except LookupError:
return False Try / catch
try:
agent = MyAgent(description="d")
except RuntimeError as e:
if "AgentRuntime" in str(e):
# must go through the runtime instead
await runtime.register("my-agent", lambda: MyAgent(description="d"))
agent = await runtime.try_get_agent(CoreAgentId("my-agent", "default"), MyAgent)
else:
raise Prevention
- 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.
When it happens
Trigger: 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).
Common situations: 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__.
Related errors
- Agent description must be a string
- Python nodes are not supported in the dotnet runtime.
- No response from DirectLine Bot.
- Invalid response from DirectLine Bot.\n{response_data}
- Invalid agent type: {type}. Allowed values MUST match the re
AI-assisted analysis of microsoft/semantic-kernel@c028a0c7dc (2026-08-13).
Data as JSON: /api/errors/56d7be8dc814f31f.
Report an issue: GitHub.