{"record":{"id":"88d49141252369ea","repo":"microsoft/semantic-kernel","slug":"failed-to-select-agent","errorCode":null,"errorMessage":"Failed to select agent","messagePattern":"Failed to select agent","errorType":"exception","errorClass":"AgentChatException","httpStatus":null,"severity":"error","filePath":"python/semantic_kernel/agents/group_chat/agent_group_chat.py","lineNumber":154,"sourceCode":"                yield message\n\n            return\n\n        if not self.agents:\n            raise AgentChatException(\"No agents are available\")\n\n        if self.is_complete:\n            if not self.termination_strategy.automatic_reset:\n                raise AgentChatException(\"Chat is already complete\")\n\n            self.is_complete = False\n\n        for _ in range(self.termination_strategy.maximum_iterations):\n            try:\n                selected_agent = await self.selection_strategy.next(self.agents, self.history.messages)\n            except Exception as ex:\n                logger.error(f\"Failed to select agent: {ex}\")\n                raise AgentChatException(\"Failed to select agent\") from ex\n\n            async for message in super().invoke_agent(selected_agent):\n                if message.role == AuthorRole.ASSISTANT:\n                    task = self.termination_strategy.should_terminate(selected_agent, self.history.messages)\n                    self.is_complete = await task\n                yield message\n\n            if self.is_complete:\n                break\n\n    async def invoke_stream(\n        self, agent: Agent | None = None, is_joining: bool = True\n    ) -> AsyncIterable[ChatMessageContent]:\n        \"\"\"Invoke the agent chat stream asynchronously.\n\n        Handles both group interactions and single agent interactions based on the provided arguments.\n\n        Args:","sourceCodeStart":136,"sourceCodeEnd":172,"githubUrl":"https://github.com/microsoft/semantic-kernel/blob/c028a0c7dc4f0814cdcbaba9d998f187a41197bf/python/semantic_kernel/agents/group_chat/agent_group_chat.py#L136-L172","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Inspect the chained exception (__cause__) to find the original error from the selection strategy.","Fix the SelectionStrategy.next() implementation to handle all agent/history states gracefully.","Ensure self.agents is not mutated concurrently during invoke.","Use the built-in SequentialSelectionStrategy as a baseline to confirm the issue is in the custom strategy."],"exampleFix":"# before — custom strategy with an off-by-one bug\nclass MyStrategy(SelectionStrategy):\n    async def next(self, agents, history):\n        return agents[len(history)]  # IndexError when history grows\n\n# after — safe modular indexing\nclass MyStrategy(SelectionStrategy):\n    async def next(self, agents, history):\n        return agents[len(history) % len(agents)]","handlingStrategy":"try-catch","validationCode":null,"typeGuard":null,"tryCatchPattern":"from semantic_kernel.exceptions.agent_exceptions import AgentChatException\n\ntry:\n    async for msg in chat.invoke():\n        ...\nexcept AgentChatException as exc:\n    original = exc.__cause__  # the exception from SelectionStrategy.next()\n    logger.error(\"Selection failed: %s\", original)\n    raise","preventionTips":["Inspect exc.__cause__ to find the original selection-strategy error.","Unit-test custom SelectionStrategy.next() against edge cases (empty history, single agent).","Do not mutate chat.agents concurrently during invoke."],"tags":["selection-strategy","group-chat","wrapped-exception"],"backgroundTag":null,"analyzedSha":"c028a0c7dc4f0814cdcbaba9d998f187a41197bf","analyzedAt":"2026-08-13T13:48:05.040Z","schemaVersion":2},"datasetVersion":"2026-08-13T14:17:21.547Z"}