microsoft/semantic-kernel · error · ValueError

Factory registered using the wrong type.

Error message

Factory registered using the wrong type.

What it means

When registering a factory with expected_class, the factory_wrapper invokes the factory and checks that the returned instance's type matches expected_class using type_func_alias. If it does not match, ValueError is raised. This is a runtime type-safety guard ensuring factories produce the declared type.

Source

Thrown at python/semantic_kernel/agents/runtime/in_process/in_process_runtime.py:751

        *,
        expected_class: type[T] | None = None,
    ) -> AgentType:
        """Register a factory for creating agents."""
        if isinstance(type, str):
            type = CoreAgentType(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 type_func_alias(agent_instance) != expected_class:
                raise ValueError("Factory registered using the wrong type.")

            return agent_instance

        self._agent_factories[type.type] = factory_wrapper

        return type

    async def _invoke_agent_factory(
        self,
        agent_factory: Callable[[], T | Awaitable[T]] | Callable[[CoreRuntime, AgentId], T | Awaitable[T]],
        agent_id: AgentId,
    ) -> T:
        with AgentInstantiationContext.populate_context((self, agent_id)):
            try:
                if len(inspect.signature(agent_factory).parameters) == 0:
                    factory_one = cast(Callable[[], T], agent_factory)
                    agent = factory_one()
                elif len(inspect.signature(agent_factory).parameters) == 2:

View on GitHub (pinned to c028a0c7dc)

Solutions

  1. Ensure the factory function returns an instance whose type matches the expected_class parameter.
  2. If using polymorphism, set expected_class to the common base type, or pass expected_class=None to skip the check.
  3. Verify that type_func_alias(instance) resolves to the same class object you pass as expected_class.

Example fix

# before
await runtime.register_factory('my_agent', lambda: BaseAgent(), expected_class=MyAgent)

# after
await runtime.register_factory('my_agent', lambda: MyAgent(), expected_class=MyAgent)
# or skip the check:
await runtime.register_factory('my_agent', lambda: BaseAgent(), expected_class=None)
Defensive patterns

Strategy: type-guard

Validate before calling

# Validate factory output type before registering
agent_instance = my_factory()
assert isinstance(agent_instance, ExpectedAgent), f'Factory returns {type(agent_instance).__name__}, expected {ExpectedAgent.__name__}'
await runtime.register_factory('my_agent', my_factory, expected_class=ExpectedAgent)

Type guard

def is_correct_type(instance, expected_class) -> bool:
    from semantic_kernel.agents.runtime.in_process.utils import type_func_alias
    return type_func_alias(instance) == expected_class

Try / catch

null

Prevention

When it happens

Trigger: Calling register_factory('MyAgent', lambda: SomeOtherAgent(), expected_class=MyAgent) where the factory returns an instance of a different class. Also triggered if the factory returns a base class or unrelated type.

Common situations: A factory function was updated to return a different agent class but expected_class was not updated. A factory that dynamically returns different agent subclasses but expected_class is set to a specific one.

Related errors


AI-assisted analysis of microsoft/semantic-kernel@c028a0c7dc (2026-08-13). Data as JSON: /api/errors/32bc8491768a0b67. Report an issue: GitHub.