microsoft/autogen · error · RuntimeError

AgentInstantiationContext.agent_id() must be called within a

Error message

AgentInstantiationContext.agent_id() 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

current_agent_id() reads the same instantiation-context ContextVar as current_runtime(); outside a runtime factory call it raises LookupError, re-raised as RuntimeError. The message's 'agent_id()' name matches the classmethod but the 'directly instantiating an agent' explanation is the usual root cause.

Source

Thrown at python/packages/autogen-core/src/autogen_core/_agent_instantiation.py:118

            yield
        finally:
            AgentInstantiationContext._AGENT_INSTANTIATION_CONTEXT_VAR.reset(token)

    @classmethod
    def current_runtime(cls) -> AgentRuntime:
        try:
            return cls._AGENT_INSTANTIATION_CONTEXT_VAR.get()[0]
        except LookupError as e:
            raise RuntimeError(
                "AgentInstantiationContext.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

    @classmethod
    def current_agent_id(cls) -> AgentId:
        try:
            return cls._AGENT_INSTANTIATION_CONTEXT_VAR.get()[1]
        except LookupError as e:
            raise RuntimeError(
                "AgentInstantiationContext.agent_id() 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

    @classmethod
    def is_in_factory_call(cls) -> bool:
        if cls._AGENT_INSTANTIATION_CONTEXT_VAR.get(None) is None:
            return False
        return True

View on GitHub (pinned to 027ecf0a37)

Solutions

  1. Let the runtime instantiate the agent (register a factory, then get/send) so the context var carries (runtime, agent_id).
  2. Check AgentInstantiationContext.is_in_factory_call() first and defer ID-dependent logic to on_message or bind_id_and_runtime.
  3. For manual construction, call await agent.bind_id_and_runtime(AgentId('type','key'), runtime) and read agent.id afterwards.

Example fix

# before
self._id = AgentInstantiationContext.current_agent_id()  # RuntimeError when manual

# after
if AgentInstantiationContext.is_in_factory_call():
    self._id = AgentInstantiationContext.current_agent_id()
# else: ID arrives later via bind_id_and_runtime(); use self.id lazily
Defensive patterns

Strategy: validation

Validate before calling

from autogen_core import AgentInstantiationContext

if AgentInstantiationContext.is_in_factory_call():
    my_id = AgentInstantiationContext.current_agent_id()
else:
    my_id = None  # ID arrives later via bind_id_and_runtime / agent.id

Try / catch

try:
    aid = AgentInstantiationContext.current_agent_id()
except RuntimeError as e:
    if "must be called within an instantiation context" in str(e):
        aid = None  # defer ID usage until bound
    else:
        raise

Prevention

When it happens

Trigger: An agent's __init__ (or helper it calls) invoking AgentInstantiationContext.current_agent_id() when the agent was constructed manually rather than by a registered runtime factory; calling it from code running before runtime instantiation or in a detached task/thread.

Common situations: Custom agents that want their own ID at construction time (for logging, self-addressing); refactors that move agent construction out of the factory; test harnesses that instantiate agents directly.

Related errors


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