Skip to content

A programming framework for agentic AI

Add async support for `selector_func` and `candidate_func` in `SelectorGroupChat` (#6068)

Abhijeetsingh Meenae28738ac6f0f
diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_selector_group_chat.py b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_selector_group_chat.py
index 2446024c3..6a2231873 100644
--- a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_selector_group_chat.py
+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_selector_group_chat.py
@@ -1,7 +1,8 @@
import asyncio
import logging
import re
-from typing import Any, Callable, Dict, List, Mapping, Sequence
+from inspect import iscoroutinefunction
+from typing import Any, Awaitable, Callable, Dict, List, Mapping, Optional, Sequence, Union, cast
from autogen_core import AgentRuntime, Component, ComponentModel
from autogen_core.models import AssistantMessage, ChatCompletionClient, ModelFamily, SystemMessage, UserMessage
@@ -24,6 +25,14 @@ from ._events import GroupChatTermination
trace_logger = logging.getLogger(TRACE_LOGGER_NAME)
+SyncSelectorFunc = Callable[[Sequence[AgentEvent | ChatMessage]], str | None]
+AsyncSelectorFunc = Callable[[Sequence[AgentEvent | ChatMessage]], Awaitable[str | None]]
+SelectorFuncType = Union[SyncSelectorFunc | AsyncSelectorFunc]
+
+SyncCandidateFunc = Callable[[Sequence[AgentEvent | ChatMessage]], List[str]]
+AsyncCandidateFunc = Callable[[Sequence[AgentEvent | ChatMessage]], Awaitable[List[str]]]
+CandidateFuncType = Union[SyncCandidateFunc | AsyncCandidateFunc]
+
class SelectorGroupChatManager(BaseGroupChatManager):
"""A group chat manager that selects the next speaker using a ChatCompletion
@@ -43,9 +52,9 @@ class SelectorGroupChatManager(BaseGroupChatManager):
model_client: ChatCompletionClient,
selector_prompt: str,
allow_repeated_speaker: bool,
- selector_func: Callable[[Sequence[AgentEvent | ChatMessage]], str | None] | None,
+ selector_func: Optional[SelectorFuncType],
max_selector_attempts: int,
- candidate_func: Callable[[Sequence[AgentEvent | ChatMessage]], List[str]] | None,
+ candidate_func: Optional[CandidateFuncType],
) -> None:
super().__init__(
name,
@@ -63,8 +72,10 @@ class SelectorGroupChatManager(BaseGroupChatManager):
self._previous_speaker: str | None = None
self._allow_repeated_speaker = allow_repeated_speaker
self._selector_func = selector_func
+ self._is_selector_func_async = iscoroutinefunction(self._selector_func)
self._max_selector_attempts = max_selector_attempts
self._candidate_func = candidate_func
+ self._is_candidate_func_async = iscoroutinefunction(self._candidate_func)
async def validate_group_state(self, messages: List[ChatMessage] | None) -> None:
pass
@@ -99,7 +110,12 @@ class SelectorGroupChatManager(BaseGroupChatManager):
# Use the selector function if provided.
if self._selector_func is not None:
- speaker = self._selector_func(thread)
+ if self._is_selector_func_async:
+ async_selector_func = cast(AsyncSelectorFunc, self._selector_func)
+ speaker = await async_selector_func(thread)
+ else:
+ sync_selector_func = cast(SyncSelectorFunc, self._selector_func)
+ speaker = sync_selector_func(thread)
if speaker is not None:
if speaker not in self._participant_names:
raise ValueError(
@@ -111,7 +127,12 @@ class SelectorGroupChatManager(BaseGroupChatManager):
# Use the candidate function to filter participants if provided
if self._candidate_func is not None:
- participants = self._candidate_func(thread)
+ if self._is_candidate_func_async:
+ async_candidate_func = cast(AsyncCandidateFunc, self._candidate_func)
+ participants = await async_candidate_func(thread)
+ else:
+ sync_candidate_func = cast(SyncCandidateFunc, self._candidate_func)
+ participants = sync_candidate_func(thread)
if not participants:
raise ValueError("Candidate function must return a non-empty list of participant names.")
if not all(p in self._participant_names for p in participants):
@@ -287,11 +308,11 @@ class SelectorGroupChat(BaseGroupChat, Component[SelectorGroupChatConfig]):
max_selector_attempts (int, optional): The maximum number of attempts to select a speaker using the model. Defaults to 3.
If the model fails to select a speaker after the maximum number of attempts, the previous speaker will be used if available,
otherwise the first participant will be used.
- selector_func (Callable[[Sequence[AgentEvent | ChatMessage]], str | None], optional): A custom selector
+ selector_func (Callable[[Sequence[AgentEvent | ChatMessage]], str | None], Callable[[Sequence[AgentEvent | ChatMessage]], Awaitable[str | None]], optional): A custom selector
function that takes the conversation history and returns the name of the next speaker.
If provided, this function will be used to override the model to select the next speaker.
If the function returns None, the model will be used to select the next speaker.
- candidate_func (Callable[[Sequence[AgentEvent | ChatMessage]], List[str]], optional):
+ candidate_func (Callable[[Sequence[AgentEvent | ChatMessage]], List[str]], Callable[[Sequence[AgentEvent | ChatMessage]], Awaitable[List[str]]], optional):
A custom function that takes the conversation history and returns a filtered list of candidates for the next speaker
selection using model. If the function returns an empty list or `None`, `SelectorGroupChat` will raise a `ValueError`.
This function is only used if `selector_func` is not set. The `allow_repeated_speaker` will be ignored if set.
@@ -434,8 +455,8 @@ Read the above conversation. Then select the next role from {participants} to pl
""",
allow_repeated_speaker: bool = False,
max_selector_attempts: int = 3,
- selector_func: Callable[[Sequence[AgentEvent | ChatMessage]], str | None] | None = None,
- candidate_func: Callable[[Sequence[AgentEvent | ChatMessage]], List[str]] | None = None,
+ selector_func: Optional[SelectorFuncType] = None,
+ candidate_func: Optional[CandidateFuncType] = None,
):
super().__init__(
participants,