microsoft/autogen · error · ValueError

Factory registered using the wrong type: expected {expected_

Error message

Factory registered using the wrong type: expected {expected_class.__name__}, got {type_func_alias(agent_instance).__name__}

What it means

Inside the factory wrapper created by register_factory, if expected_class was supplied and the produced instance's class is not a subclass of expected_class, a ValueError is raised at agent instantiation time (not at registration). This guards runtime.type-based casts (e.g. try_get_underlying_agent_instance(T)) against factories returning an unexpected class.

Source

Thrown at python/packages/autogen-core/src/autogen_core/_single_threaded_agent_runtime.py:907

        agent_factory: Callable[[], T | Awaitable[T]],
        *,
        expected_class: type[T] | None = None,
    ) -> AgentType:
        if isinstance(type, str):
            type = AgentType(type)

        if type.type in self._agent_factories:
            raise ValueError(f"Agent with type {type} already exists.")

        async def factory_wrapper() -> T:
            maybe_agent_instance = agent_factory()
            if inspect.isawaitable(maybe_agent_instance):
                agent_instance = await maybe_agent_instance
            else:
                agent_instance = maybe_agent_instance

            if expected_class is not None and not issubclass(type_func_alias(agent_instance), expected_class):
                raise ValueError(
                    f"Factory registered using the wrong type: expected {expected_class.__name__}, got {type_func_alias(agent_instance).__name__}"
                )
            return agent_instance

        self._agent_factories[type.type] = factory_wrapper

        return type

    async def register_agent_instance(
        self,
        agent_instance: Agent,
        agent_id: AgentId,
    ) -> AgentId:
        def agent_factory() -> Agent:
            raise RuntimeError(
                "Agent factory was invoked for an agent instance that was not registered. This is likely due to the agent type being incorrectly subscribed to a topic. If this exception occurs when publishing a message to the DefaultTopicId, then it is likely that `skip_class_subscriptions` needs to be turned off when registering the agent."
            )

View on GitHub (pinned to 027ecf0a37)

Solutions

  1. Make the factory construct the same class (or subclass) passed as expected_class; align the generic type parameter, registration call, and constructed class
  2. Drop expected_class if you intentionally register heterogeneous factories under one type (then handle typing at retrieval)
  3. If the class was renamed, update expected_class to the new name

Example fix

# before
await runtime.register_factory(
    AgentType("worker"), lambda: OldWorker(), expected_class=NewWorker
)

# after
await runtime.register_factory(
    AgentType("worker"), NewWorker.create, expected_class=NewWorker
)
Defensive patterns

Strategy: type-guard

Validate before calling

def factory_returns_subclass(factory, expected) -> bool:
    import inspect
    hints = inspect.signature(factory).return_annotation
    # runtime-proof: dry-run the factory in a sandbox when cheap
    try:
        inst = factory()
        import inspect as i
        if i.isawaitable(inst):
            inst = await_early(inst)  # only if sync-safe
        return isinstance(inst, expected)
    except Exception:
        return True  # defer check to runtime

Type guard

def instance_matches_expected(instance, expected_class) -> bool:
    return expected_class is None or isinstance(instance, expected_class)

Try / catch

try:
    agent = await runtime.try_get_underlying_agent_instance(agent_id, WorkerAgent)
except ValueError as e:
    if "wrong type" in str(e):
        log_registration_bug(agent_id, expected=WorkerAgent)
    raise

Prevention

When it happens

Trigger: register_factory(type, factory, expected_class=B) where factory returns A (A not a subclass of B, including cases where the factory was copy-pasted and constructs the old agent class); async factories returning a coroutine that resolves to the wrong class; refactoring an agent class without updating expected_class at the registration site.

Common situations: Copy-pasted registration blocks after creating a new agent variant; renaming/splitting agent classes so isinstance relationships break; passing expected_class=Agent but factory returns a non-Agent helper object.

Related errors


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