microsoft/semantic-kernel · error · AgentChatException

Failed to select agent

Error message

Failed to select agent

What it means

Raised by AgentGroupChat.invoke() when self.selection_strategy.next(self.agents, self.history.messages) raises any exception. The original exception is caught, logged, and re-raised as AgentChatException chained with 'from ex'. This wraps any failure in the agent-selection logic.

Source

Thrown at python/semantic_kernel/agents/group_chat/agent_group_chat.py:154

                yield message

            return

        if not self.agents:
            raise AgentChatException("No agents are available")

        if self.is_complete:
            if not self.termination_strategy.automatic_reset:
                raise AgentChatException("Chat is already complete")

            self.is_complete = False

        for _ in range(self.termination_strategy.maximum_iterations):
            try:
                selected_agent = await self.selection_strategy.next(self.agents, self.history.messages)
            except Exception as ex:
                logger.error(f"Failed to select agent: {ex}")
                raise AgentChatException("Failed to select agent") from ex

            async for message in super().invoke_agent(selected_agent):
                if message.role == AuthorRole.ASSISTANT:
                    task = self.termination_strategy.should_terminate(selected_agent, self.history.messages)
                    self.is_complete = await task
                yield message

            if self.is_complete:
                break

    async def invoke_stream(
        self, agent: Agent | None = None, is_joining: bool = True
    ) -> AsyncIterable[ChatMessageContent]:
        """Invoke the agent chat stream asynchronously.

        Handles both group interactions and single agent interactions based on the provided arguments.

        Args:

View on GitHub (pinned to c028a0c7dc)

Solutions

  1. Inspect the chained exception (__cause__) to find the original error from the selection strategy.
  2. Fix the SelectionStrategy.next() implementation to handle all agent/history states gracefully.
  3. Ensure self.agents is not mutated concurrently during invoke.
  4. Use the built-in SequentialSelectionStrategy as a baseline to confirm the issue is in the custom strategy.

Example fix

# before — custom strategy with an off-by-one bug
class MyStrategy(SelectionStrategy):
    async def next(self, agents, history):
        return agents[len(history)]  # IndexError when history grows

# after — safe modular indexing
class MyStrategy(SelectionStrategy):
    async def next(self, agents, history):
        return agents[len(history) % len(agents)]
Defensive patterns

Strategy: try-catch

Try / catch

from semantic_kernel.exceptions.agent_exceptions import AgentChatException

try:
    async for msg in chat.invoke():
        ...
except AgentChatException as exc:
    original = exc.__cause__  # the exception from SelectionStrategy.next()
    logger.error("Selection failed: %s", original)
    raise

Prevention

When it happens

Trigger: Using a custom SelectionStrategy whose next() method raises (e.g. IndexError, ValueError, or application logic error). Also possible with built-in strategies if the agents list is mutated concurrently or the strategy has a bug.

Common situations: Custom SelectionStrategy with a bug (e.g. indexing past the end of the agents list); a selection strategy that depends on external state that became invalid; race condition modifying self.agents during iteration.

Related errors


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