A programming framework for agentic AI
Implement 'candidate_func' parameter to filter down the pool of candidates for selection (#5954)
Abhijeetsingh Meenac4e07e86d8c4
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.pyindex 0403025de..2446024c3 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@@ -45,6 +45,7 @@ class SelectorGroupChatManager(BaseGroupChatManager):allow_repeated_speaker: bool,selector_func: Callable[[Sequence[AgentEvent | ChatMessage]], str | None] | None,max_selector_attempts: int,+ candidate_func: Callable[[Sequence[AgentEvent | ChatMessage]], List[str]] | None,) -> None:super().__init__(name,@@ -63,6 +64,7 @@ class SelectorGroupChatManager(BaseGroupChatManager):self._allow_repeated_speaker = allow_repeated_speakerself._selector_func = selector_funcself._max_selector_attempts = max_selector_attempts+ self._candidate_func = candidate_funcasync def validate_group_state(self, messages: List[ChatMessage] | None) -> None:pass@@ -107,6 +109,25 @@ class SelectorGroupChatManager(BaseGroupChatManager):# Skip the model based selection.return speaker+ # Use the candidate function to filter participants if provided+ if self._candidate_func is not None:+ participants = self._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):+ raise ValueError(+ f"Candidate function returned invalid participant names: {participants}. "+ f"Expected one of: {self._participant_names}."+ )+ else:+ # Construct the candidate agent list to be selected from, skip the previous speaker if not allowed.+ if self._previous_speaker is not None and not self._allow_repeated_speaker:+ participants = [p for p in self._participant_names if p != self._previous_speaker]+ else:+ participants = list(self._participant_names)++ assert len(participants) > 0+# Construct the history of the conversation.history_messages: List[str] = []for msg in thread:@@ -136,13 +157,6 @@ class SelectorGroupChatManager(BaseGroupChatManager):roles += re.sub(r"\s+", " ", f"{topic_type}: {description}").strip() + "\n"roles = roles.strip()- # Construct the candidate agent list to be selected from, skip the previous speaker if not allowed.- if self._previous_speaker is not None and not self._allow_repeated_speaker:- participants = [p for p in self._participant_names if p != self._previous_speaker]- else:- participants = list(self._participant_names)- assert len(participants) > 0-# Select the next speaker.if len(participants) > 1:agent_name = await self._select_speaker(roles, participants, history, self._max_selector_attempts)@@ -277,6 +291,10 @@ class SelectorGroupChat(BaseGroupChat, Component[SelectorGroupChatConfig]):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):+ 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.Raises:@@ -417,6 +435,7 @@ Read the above conversation. Then select the next role from {participants} to plallow_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,):super().__init__(participants,@@ -434,6 +453,7 @@ Read the above conversation. Then select the next role from {participants} to plself._allow_repeated_speaker = allow_repeated_speakerself._selector_func = selector_funcself._max_selector_attempts = max_selector_attempts+ self._candidate_func = candidate_funcdef _create_group_chat_manager_factory(self,@@ -462,6 +482,7 @@ Read the above conversation. Then select the next role from {participants} to plself._allow_repeated_speaker,self._selector_func,self._max_selector_attempts,+ self._candidate_func,)def _to_config(self) -> SelectorGroupChatConfig:diff --git a/python/packages/autogen-agentchat/tests/test_group_chat.py b/python/packages/autogen-agentchat/tests/test_group_chat.pyindex 94dcb612e..5ab1605a7 100644--- a/python/packages/autogen-agentchat/tests/test_group_chat.py+++ b/python/packages/autogen-agentchat/tests/test_group_chat.py@@ -725,6 +725,47 @@ async def test_selector_group_chat_custom_selector(runtime: AgentRuntime | None))+async def test_selector_group_chat_custom_candidate_func(runtime: AgentRuntime | None) -> None:+ model_client = ReplayChatCompletionClient(["agent3"])+ agent1 = _EchoAgent("agent1", description="echo agent 1")+ agent2 = _EchoAgent("agent2", description="echo agent 2")+ agent3 = _EchoAgent("agent3", description="echo agent 3")+ agent4 = _EchoAgent("agent4", description="echo agent 4")++ def _candidate_func(messages: Sequence[AgentEvent | ChatMessage]) -> List[str]:+ if len(messages) == 0:+ return ["agent1"]+ elif messages[-1].source == "agent1":+ return ["agent2"]+ elif messages[-1].source == "agent2":+ return ["agent2", "agent3"] # will generate agent3+ elif messages[-1].source == "agent3":+ return ["agent4"]+ else:+ return ["agent1"]++ termination = MaxMessageTermination(6)+ team = SelectorGroupChat(+ participants=[agent1, agent2, agent3, agent4],+ model_client=model_client,+ candidate_func=_candidate_func,+ termination_condition=termination,+ runtime=runtime,+ )+ result = await team.run(task="task")+ assert len(result.messages) == 6+ assert result.messages[1].source == "agent1"+ assert result.messages[2].source == "agent2"+ assert result.messages[3].source == "agent3"+ assert result.messages[4].source == "agent4"+ assert result.messages[5].source == "agent1"+ assert (+ result.stop_reason is not None+ and result.stop_reason == "Maximum number of messages 6 reached, current message count: 6"+ )++class _HandOffAgent(BaseChatAgent):def __init__(self, name: str, description: str, next_agent: str) -> None:super().__init__(name, description)diff --git a/python/packages/autogen-agentchat/tests/test_group_chat_endpoint.py b/python/packages/autogen-agentchat/tests/test_group_chat_endpoint.pyindex e32d8fd97..390a45e03 100644--- a/python/packages/autogen-agentchat/tests/test_group_chat_endpoint.py+++ b/python/packages/autogen-agentchat/tests/test_group_chat_endpoint.py@@ -1,7 +1,13 @@import os+from typing import List, Sequenceimport pytestfrom autogen_agentchat.agents import AssistantAgent+from autogen_agentchat.base import TaskResult+from autogen_agentchat.messages import (+ AgentEvent,+ ChatMessage,+)from autogen_agentchat.teams import SelectorGroupChatfrom autogen_agentchat.ui import Consolefrom autogen_core.models import ChatCompletionClient@@ -27,6 +33,51 @@ async def _test_selector_group_chat(model_client: ChatCompletionClient) -> None:await Console(team.run_stream(task="Draft a short email about organizing a holiday party for new year."))+async def _test_selector_group_chat_with_candidate_func(model_client: ChatCompletionClient) -> None:+ filtered_participants = ["developer", "tester"]++ def dummy_candidate_func(thread: Sequence[AgentEvent | ChatMessage]) -> List[str]:+ # Dummy candidate function that will return+ # only return developer and reviewer+ return filtered_participants++ developer = AssistantAgent(+ "developer",+ description="Writes and implements code based on requirements.",+ model_client=model_client,+ system_message="You are a software developer working on a new feature.",+ )++ tester = AssistantAgent(+ "tester",+ description="Writes and executes test cases to validate the implementation.",+ model_client=model_client,+ system_message="You are a software tester ensuring the feature works correctly.",+ )++ project_manager = AssistantAgent(+ "project_manager",+ description="Oversees the project and ensures alignment with the broader goals.",+ model_client=model_client,+ system_message="You are a project manager ensuring the team meets the project goals.",+ )++ team = SelectorGroupChat(+ participants=[developer, tester, project_manager],+ model_client=model_client,+ max_turns=3,+ candidate_func=dummy_candidate_func,+ )++ task = "Create a detailed implementation plan for adding dark mode in a React app and review it for feasibility and improvements."++ async for message in team.run_stream(task=task):+ if not isinstance(message, TaskResult):+ if message.source == "user": # ignore the first 'user' message+ continue+ assert message.source in filtered_participants, "Candidate function didn't filter the participants"++@pytest.mark.asyncioasync def test_selector_group_chat_gemini() -> None:try:@@ -39,6 +90,7 @@ async def test_selector_group_chat_gemini() -> None:api_key=api_key,)await _test_selector_group_chat(model_client)+ await _test_selector_group_chat_with_candidate_func(model_client)@pytest.mark.asyncio@@ -53,3 +105,4 @@ async def test_selector_group_chat_openai() -> None:api_key=api_key,)await _test_selector_group_chat(model_client)+ await _test_selector_group_chat_with_candidate_func(model_client)diff --git a/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/selector-group-chat.ipynb b/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/selector-group-chat.ipynbindex ee3caf558..522c26b20 100644--- a/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/selector-group-chat.ipynb+++ b/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/selector-group-chat.ipynb@@ -20,6 +20,7 @@"- Prevention of consecutive turns by the same speaker (optional)\n","- Customizable selection prompting\n","- Customizable selection function to override the default model-based selection\n",+ "- Customizable candidate function to narrow-down the set of agents for selection using model\n","\n","```{note}\n","{py:class}`~autogen_agentchat.teams.SelectorGroupChat` is a high-level API. For more control and customization, refer to the [Group Chat Pattern](../core-user-guide/design-patterns/group-chat.ipynb) in the Core API documentation to implement your own group chat logic.\n",@@ -56,7 +57,7 @@"metadata": {},"outputs": [],"source": [- "from typing import Sequence\n",+ "from typing import List, Sequence\n","\n","from autogen_agentchat.agents import AssistantAgent, UserProxyAgent\n","from autogen_agentchat.conditions import MaxMessageTermination, TextMentionTermination\n",@@ -547,6 +548,161 @@"```"]},+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Custom Candidate Function"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "One more possible requirement might be to automatically select the next speaker from a filtered list of agents.\n",+ "For this, we can set `candidate_func` parameter with a custom candidate function to filter down the list of potential agents for speaker selection for each turn of groupchat.\n",+ "\n",+ "This allow us to restrict speaker selection to a specific set of agents after a given agent.\n",+ "\n",+ "\n",+ "```{note}\n",+ "The `candidate_func` is only valid if `selector_func` is not set.\n",+ "Returning `None` or an empty list `[]` from the custom candidate function will raise a `ValueError`.\n",+ "```"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "---------- user ----------\n",+ "Who was the Miami Heat player with the highest points in the 2006-2007 season, and what was the percentage change in his total rebounds between the 2007-2008 and 2008-2009 seasons?\n",+ "---------- PlanningAgent ----------\n",+ "To answer this question, we'll break it down into two main subtasks:\n",+ "\n",+ "1. Identify the Miami Heat player with the highest points in the 2006-2007 season.\n",+ "2. Calculate the percentage change in that player's total rebounds between the 2007-2008 and 2008-2009 seasons.\n",+ "\n",+ "Let's assign these tasks:\n",+ "\n",+ "1. WebSearchAgent: Search for the Miami Heat player with the highest points in the 2006-2007 NBA season.\n",+ "2. WebSearchAgent: Find the total rebound statistics for that identified player for both the 2007-2008 and 2008-2009 NBA seasons.\n",+ "3. DataAnalystAgent: Calculate the percentage change in the player's total rebounds between the 2007-2008 and 2008-2009 seasons once the data is retrieved.\n",+ "---------- WebSearchAgent ----------\n",+ "[FunctionCall(id='call_WtR5KTfEIxs3jIO25gjAw7dF', arguments='{\"query\":\"Miami Heat highest points scorer 2006-2007 NBA season\"}', name='search_web_tool')]\n",+ "---------- WebSearchAgent ----------\n",+ "[FunctionExecutionResult(content='Here are the total points scored by Miami Heat players in the 2006-2007 season:\\n Udonis Haslem: 844 points\\n Dwayne Wade: 1397 points\\n James Posey: 550 points\\n ...\\n ', name='search_web_tool', call_id='call_WtR5KTfEIxs3jIO25gjAw7dF', is_error=False)]\n",+ "---------- WebSearchAgent ----------\n",+ "Here are the total points scored by Miami Heat players in the 2006-2007 season:\n",+ " Udonis Haslem: 844 points\n",+ " Dwayne Wade: 1397 points\n",+ " James Posey: 550 points\n",+ " ...\n",+ " \n",+ "---------- DataAnalystAgent ----------\n",+ "[FunctionCall(id='call_9HA3DEacUl4WuG2G2PtRkXAO', arguments='{\"start\": 432, \"end\": 527}', name='percentage_change_tool')]\n",+ "---------- DataAnalystAgent ----------\n",+ "[FunctionExecutionResult(content='21.99074074074074', name='percentage_change_tool', call_id='call_9HA3DEacUl4WuG2G2PtRkXAO', is_error=False)]\n",+ "---------- DataAnalystAgent ----------\n",+ "21.99074074074074\n",+ "---------- PlanningAgent ----------\n",+ "It seems we've missed some context there, so let's assign the subtasks again for clarity:\n",+ "\n",+ "Based on the search results, Dwyane Wade had the highest points for the Miami Heat in the 2006-2007 season with 1397 points.\n",+ "\n",+ "Now, let's find the necessary rebound statistics:\n",+ "\n",+ "2. WebSearchAgent: Find Dwyane Wade's total rebound statistics for both the 2007-2008 and 2008-2009 NBA seasons.\n",+ "3. DataAnalystAgent: Once the data is retrieved, calculate the percentage change in Dwyane Wade's total rebounds between the 2007-2008 and 2008-2009 seasons.\n",+ "---------- WebSearchAgent ----------\n",+ "[FunctionCall(id='call_3i1wTDSjkGg6Ev8YKYWkZK55', arguments='{\"query\": \"Dwyane Wade total rebounds 2007-2008 NBA season\"}', name='search_web_tool'), FunctionCall(id='call_NRAs6jHxXRi8zsvpW5WlHAaU', arguments='{\"query\": \"Dwyane Wade total rebounds 2008-2009 NBA season\"}', name='search_web_tool')]\n",+ "---------- WebSearchAgent ----------\n",+ "[FunctionExecutionResult(content='The number of total rebounds for Dwayne Wade in the Miami Heat season 2007-2008 is 214.', name='search_web_tool', call_id='call_3i1wTDSjkGg6Ev8YKYWkZK55', is_error=False), FunctionExecutionResult(content='The number of total rebounds for Dwayne Wade in the Miami Heat season 2008-2009 is 398.', name='search_web_tool', call_id='call_NRAs6jHxXRi8zsvpW5WlHAaU', is_error=False)]\n",+ "---------- WebSearchAgent ----------\n",+ "The number of total rebounds for Dwayne Wade in the Miami Heat season 2007-2008 is 214.\n",+ "The number of total rebounds for Dwayne Wade in the Miami Heat season 2008-2009 is 398.\n",+ "---------- PlanningAgent ----------\n",+ "The total rebounds for Dwyane Wade in the 2007-2008 season were 214, and in the 2008-2009 season, they were 398.\n",+ "\n",+ "Now, let's calculate the percentage change.\n",+ "\n",+ "3. DataAnalystAgent: Calculate the percentage change in Dwyane Wade's total rebounds from the 2007-2008 season to the 2008-2009 season.\n",+ "---------- DataAnalystAgent ----------\n",+ "[FunctionCall(id='call_XECA7ezz7VIKbf8IbZYSCSpI', arguments='{\"start\":214,\"end\":398}', name='percentage_change_tool')]\n",+ "---------- DataAnalystAgent ----------\n",+ "[FunctionExecutionResult(content='85.98130841121495', name='percentage_change_tool', call_id='call_XECA7ezz7VIKbf8IbZYSCSpI', is_error=False)]\n",+ "---------- DataAnalystAgent ----------\n",+ "85.98130841121495\n",+ "---------- PlanningAgent ----------\n",+ "The Miami Heat player with the highest points in the 2006-2007 season was Dwyane Wade, with 1397 points. The percentage change in his total rebounds between the 2007-2008 and 2008-2009 seasons was approximately 85.98%.\n",+ "\n",+ "TERMINATE\n"+ ]+ },+ {+ "data": {+ "text/plain": [+ "TaskResult(messages=[TextMessage(source='user', models_usage=None, metadata={}, content='Who was the Miami Heat player with the highest points in the 2006-2007 season, and what was the percentage change in his total rebounds between the 2007-2008 and 2008-2009 seasons?', type='TextMessage'), TextMessage(source='PlanningAgent', models_usage=RequestUsage(prompt_tokens=161, completion_tokens=169), metadata={}, content=\"To answer this question, we'll break it down into two main subtasks:\\n\\n1. Identify the Miami Heat player with the highest points in the 2006-2007 season.\\n2. Calculate the percentage change in that player's total rebounds between the 2007-2008 and 2008-2009 seasons.\\n\\nLet's assign these tasks:\\n\\n1. WebSearchAgent: Search for the Miami Heat player with the highest points in the 2006-2007 NBA season.\\n2. WebSearchAgent: Find the total rebound statistics for that identified player for both the 2007-2008 and 2008-2009 NBA seasons.\\n3. DataAnalystAgent: Calculate the percentage change in the player's total rebounds between the 2007-2008 and 2008-2009 seasons once the data is retrieved.\", type='TextMessage'), ToolCallRequestEvent(source='WebSearchAgent', models_usage=RequestUsage(prompt_tokens=324, completion_tokens=28), metadata={}, content=[FunctionCall(id='call_WtR5KTfEIxs3jIO25gjAw7dF', arguments='{\"query\":\"Miami Heat highest points scorer 2006-2007 NBA season\"}', name='search_web_tool')], type='ToolCallRequestEvent'), ToolCallExecutionEvent(source='WebSearchAgent', models_usage=None, metadata={}, content=[FunctionExecutionResult(content='Here are the total points scored by Miami Heat players in the 2006-2007 season:\\n Udonis Haslem: 844 points\\n Dwayne Wade: 1397 points\\n James Posey: 550 points\\n ...\\n ', name='search_web_tool', call_id='call_WtR5KTfEIxs3jIO25gjAw7dF', is_error=False)], type='ToolCallExecutionEvent'), ToolCallSummaryMessage(source='WebSearchAgent', models_usage=None, metadata={}, content='Here are the total points scored by Miami Heat players in the 2006-2007 season:\\n Udonis Haslem: 844 points\\n Dwayne Wade: 1397 points\\n James Posey: 550 points\\n ...\\n ', type='ToolCallSummaryMessage'), ToolCallRequestEvent(source='DataAnalystAgent', models_usage=RequestUsage(prompt_tokens=390, completion_tokens=37), metadata={}, content=[FunctionCall(id='call_9HA3DEacUl4WuG2G2PtRkXAO', arguments='{\"start\": 432, \"end\": 527}', name='percentage_change_tool')], type='ToolCallRequestEvent'), ToolCallExecutionEvent(source='DataAnalystAgent', models_usage=None, metadata={}, content=[FunctionExecutionResult(content='21.99074074074074', name='percentage_change_tool', call_id='call_9HA3DEacUl4WuG2G2PtRkXAO', is_error=False)], type='ToolCallExecutionEvent'), ToolCallSummaryMessage(source='DataAnalystAgent', models_usage=None, metadata={}, content='21.99074074074074', type='ToolCallSummaryMessage'), TextMessage(source='PlanningAgent', models_usage=RequestUsage(prompt_tokens=413, completion_tokens=137), metadata={}, content=\"It seems we've missed some context there, so let's assign the subtasks again for clarity:\\n\\nBased on the search results, Dwyane Wade had the highest points for the Miami Heat in the 2006-2007 season with 1397 points.\\n\\nNow, let's find the necessary rebound statistics:\\n\\n2. WebSearchAgent: Find Dwyane Wade's total rebound statistics for both the 2007-2008 and 2008-2009 NBA seasons.\\n3. DataAnalystAgent: Once the data is retrieved, calculate the percentage change in Dwyane Wade's total rebounds between the 2007-2008 and 2008-2009 seasons.\", type='TextMessage'), ToolCallRequestEvent(source='WebSearchAgent', models_usage=RequestUsage(prompt_tokens=576, completion_tokens=73), metadata={}, content=[FunctionCall(id='call_3i1wTDSjkGg6Ev8YKYWkZK55', arguments='{\"query\": \"Dwyane Wade total rebounds 2007-2008 NBA season\"}', name='search_web_tool'), FunctionCall(id='call_NRAs6jHxXRi8zsvpW5WlHAaU', arguments='{\"query\": \"Dwyane Wade total rebounds 2008-2009 NBA season\"}', name='search_web_tool')], type='ToolCallRequestEvent'), ToolCallExecutionEvent(source='WebSearchAgent', models_usage=None, metadata={}, content=[FunctionExecutionResult(content='The number of total rebounds for Dwayne Wade in the Miami Heat season 2007-2008 is 214.', name='search_web_tool', call_id='call_3i1wTDSjkGg6Ev8YKYWkZK55', is_error=False), FunctionExecutionResult(content='The number of total rebounds for Dwayne Wade in the Miami Heat season 2008-2009 is 398.', name='search_web_tool', call_id='call_NRAs6jHxXRi8zsvpW5WlHAaU', is_error=False)], type='ToolCallExecutionEvent'), ToolCallSummaryMessage(source='WebSearchAgent', models_usage=None, metadata={}, content='The number of total rebounds for Dwayne Wade in the Miami Heat season 2007-2008 is 214.\\nThe number of total rebounds for Dwayne Wade in the Miami Heat season 2008-2009 is 398.', type='ToolCallSummaryMessage'), TextMessage(source='PlanningAgent', models_usage=RequestUsage(prompt_tokens=612, completion_tokens=84), metadata={}, content=\"The total rebounds for Dwyane Wade in the 2007-2008 season were 214, and in the 2008-2009 season, they were 398.\\n\\nNow, let's calculate the percentage change.\\n\\n3. DataAnalystAgent: Calculate the percentage change in Dwyane Wade's total rebounds from the 2007-2008 season to the 2008-2009 season.\", type='TextMessage'), ToolCallRequestEvent(source='DataAnalystAgent', models_usage=RequestUsage(prompt_tokens=720, completion_tokens=21), metadata={}, content=[FunctionCall(id='call_XECA7ezz7VIKbf8IbZYSCSpI', arguments='{\"start\":214,\"end\":398}', name='percentage_change_tool')], type='ToolCallRequestEvent'), ToolCallExecutionEvent(source='DataAnalystAgent', models_usage=None, metadata={}, content=[FunctionExecutionResult(content='85.98130841121495', name='percentage_change_tool', call_id='call_XECA7ezz7VIKbf8IbZYSCSpI', is_error=False)], type='ToolCallExecutionEvent'), ToolCallSummaryMessage(source='DataAnalystAgent', models_usage=None, metadata={}, content='85.98130841121495', type='ToolCallSummaryMessage'), TextMessage(source='PlanningAgent', models_usage=RequestUsage(prompt_tokens=718, completion_tokens=63), metadata={}, content='The Miami Heat player with the highest points in the 2006-2007 season was Dwyane Wade, with 1397 points. The percentage change in his total rebounds between the 2007-2008 and 2008-2009 seasons was approximately 85.98%.\\n\\nTERMINATE', type='TextMessage')], stop_reason=\"Text 'TERMINATE' mentioned\")"+ ]+ },+ "metadata": {},+ "output_type": "display_data"+ }+ ],+ "source": [+ "def candidate_func(messages: Sequence[AgentEvent | ChatMessage]) -> List[str]:\n",+ " # keep planning_agent first one to plan out the tasks\n",+ " if messages[-1].source == \"user\":\n",+ " return [planning_agent.name]\n",+ "\n",+ " # if previous agent is planning_agent and if it explicitely asks for web_search_agent\n",+ " # or data_analyst_agent or both (in-case of re-planning or re-assignment of tasks)\n",+ " # then return those specific agents\n",+ " last_message = messages[-1]\n",+ " if last_message.source == planning_agent.name:\n",+ " participants = []\n",+ " if web_search_agent.name in last_message.content:\n",+ " participants.append(web_search_agent.name)\n",+ " if data_analyst_agent.name in last_message.content:\n",+ " participants.append(data_analyst_agent.name)\n",+ " if participants:\n",+ " return participants # SelectorGroupChat will select from the remaining two agents.\n",+ "\n",+ " # we can assume that the task is finished once the web_search_agent\n",+ " # and data_analyst_agent have took their turns, thus we send\n",+ " # in planning_agent to terminate the chat\n",+ " previous_set_of_agents = set(message.source for message in messages)\n",+ " if web_search_agent.name in previous_set_of_agents and data_analyst_agent.name in previous_set_of_agents:\n",+ " return [planning_agent.name]\n",+ "\n",+ " # if no-conditions are met then return all the agents\n",+ " return [planning_agent.name, web_search_agent.name, data_analyst_agent.name]\n",+ "\n",+ "\n",+ "# Reset the previous team and run the chat again with the selector function.\n",+ "await team.reset()\n",+ "team = SelectorGroupChat(\n",+ " [planning_agent, web_search_agent, data_analyst_agent],\n",+ " model_client=model_client,\n",+ " termination_condition=termination,\n",+ " candidate_func=candidate_func,\n",+ ")\n",+ "\n",+ "await Console(team.run_stream(task=task))"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "You can see from the conversation log that the Planning Agent returns to conversation once the Web Search Agent and Data Analyst Agent took their turns and it finds that the task was not finished as expected so it called the WebSearchAgent again to get rebound values and then called DataAnalysetAgent to get the percentage change."+ ]+ },{"cell_type": "markdown","metadata": {},