A programming framework for agentic AI
Adds a SocietyOfMindAgent that presents as a single agent, but runs GroupChat as an inner-monologue (#890)
afourney0107b52d5a7d
diff --git a/autogen/agentchat/contrib/society_of_mind_agent.py b/autogen/agentchat/contrib/society_of_mind_agent.pynew file mode 100644index 000000000..06c449816--- /dev/null+++ b/autogen/agentchat/contrib/society_of_mind_agent.py@@ -0,0 +1,176 @@+# ruff: noqa: E722+import json+import traceback+import copy+from dataclasses import dataclass+from typing import Dict, List, Optional, Union, Callable, Literal, Tuple+from autogen import Agent, ConversableAgent, GroupChatManager, GroupChat, OpenAIWrapper+++class SocietyOfMindAgent(ConversableAgent):+ """(In preview) A single agent that runs a Group Chat as an inner monologue.+ At the end of the conversation (termination for any reason), the SocietyOfMindAgent+ applies the response_preparer method on the entire inner monologue message history to+ extract a final answer for the reply.++ Most arguments are inherited from ConversableAgent. New arguments are:+ chat_manager (GroupChatManager): the group chat manager that will be running the inner monologue+ response_preparer (Optional, Callable or String): If response_preparer is a callable function, then+ it should have the signature:+ f( self: SocietyOfMindAgent, messages: List[Dict])+ where `self` is this SocietyOfMindAgent, and `messages` is a list of inner-monologue messages.+ The function should return a string representing the final response (extracted or prepared)+ from that history.+ If response_preparer is a string, then it should be the LLM prompt used to extract the final+ message from the inner chat transcript.+ The default response_preparer depends on if an llm_config is provided. If llm_config is False,+ then the response_preparer deterministically returns the last message in the inner-monolgue. If+ llm_config is set to anything else, then a default LLM prompt is used.+ """++ def __init__(+ self,+ name: str,+ chat_manager: GroupChatManager,+ response_preparer: Optional[Union[str, Callable]] = None,+ is_termination_msg: Optional[Callable[[Dict], bool]] = None,+ max_consecutive_auto_reply: Optional[int] = None,+ human_input_mode: Optional[str] = "TERMINATE",+ function_map: Optional[Dict[str, Callable]] = None,+ code_execution_config: Optional[Union[Dict, Literal[False]]] = None,+ llm_config: Optional[Union[Dict, Literal[False]]] = False,+ default_auto_reply: Optional[Union[str, Dict, None]] = "",+ ):+ super().__init__(+ name=name,+ system_message="",+ is_termination_msg=is_termination_msg,+ max_consecutive_auto_reply=max_consecutive_auto_reply,+ human_input_mode=human_input_mode,+ function_map=function_map,+ code_execution_config=code_execution_config,+ llm_config=llm_config,+ default_auto_reply=default_auto_reply,+ )++ self.update_chat_manager(chat_manager)++ # response_preparer default depends on if the llm_config is set, and if a client was created+ if response_preparer is None:+ if self.client is not None:+ response_preparer = "Output a standalone response to the original request, without mentioning any of the intermediate discussion."+ else:++ def response_preparer(agent, messages):+ return messages[-1]["content"].replace("TERMINATE", "").strip()++ # Create the response_preparer callable, if given only a prompt string+ if isinstance(response_preparer, str):+ self.response_preparer = lambda agent, messages: agent._llm_response_preparer(response_preparer, messages)+ else:+ self.response_preparer = response_preparer++ # NOTE: Async reply functions are not yet supported with this contrib agent+ self._reply_func_list = []+ self.register_reply([Agent, None], SocietyOfMindAgent.generate_inner_monologue_reply)+ self.register_reply([Agent, None], ConversableAgent.generate_code_execution_reply)+ self.register_reply([Agent, None], ConversableAgent.generate_function_call_reply)+ self.register_reply([Agent, None], ConversableAgent.check_termination_and_human_reply)++ def _llm_response_preparer(self, prompt, messages):+ """Default response_preparer when provided with a string prompt, rather than a callable.++ Args:+ prompt (str): The prompt used to extract the final response from the transcript.+ messages (list): The messages generated as part of the inner monologue group chat.+ """++ _messages = [+ {+ "role": "system",+ "content": """Earlier you were asked to fulfill a request. You and your team worked diligently to address that request. Here is a transcript of that conversation:""",+ }+ ]++ for message in messages:+ message = copy.deepcopy(message)+ message["role"] = "user"+ _messages.append(message)++ _messages.append(+ {+ "role": "system",+ "content": prompt,+ }+ )++ response = self.client.create(context=None, messages=_messages, cache=self.client_cache)+ extracted_response = self.client.extract_text_or_completion_object(response)[0]+ if not isinstance(extracted_response, str):+ return str(extracted_response.model_dump(mode="dict"))+ else:+ return extracted_response++ @property+ def chat_manager(self) -> Union[GroupChatManager, None]:+ """Return the group chat manager."""+ return self._chat_manager++ def update_chat_manager(self, chat_manager: Union[GroupChatManager, None]):+ """Update the chat manager.++ Args:+ chat_manager (GroupChatManager): the group chat manager+ """+ self._chat_manager = chat_manager++ # Awkward, but due to object cloning, there's no better way to do this+ # Read the GroupChat object from the callback+ self._group_chat = None+ if self._chat_manager is not None:+ for item in self._chat_manager._reply_func_list:+ if isinstance(item["config"], GroupChat):+ self._group_chat = item["config"]+ break++ def generate_inner_monologue_reply(+ self,+ messages: Optional[List[Dict]] = None,+ sender: Optional[Agent] = None,+ config: Optional[OpenAIWrapper] = None,+ ) -> Tuple[bool, Union[str, Dict, None]]:+ """Generate a reply by running the group chat"""+ if self.chat_manager is None:+ return False, None+ if messages is None:+ messages = self._oai_messages[sender]++ # We want to clear the inner monolgue, keeping only the exteranl chat for context.+ # Reset all the counters and histories, then populate agents with necessary context from the external chat+ self.chat_manager.reset()+ self.update_chat_manager(self.chat_manager)++ external_history = []+ if len(messages) > 1:+ external_history = messages[0 : len(messages) - 1] # All but the current message++ for agent in self._group_chat.agents:+ agent.reset()+ for message in external_history:+ # Assign each message a name+ attributed_message = message.copy()+ if "name" not in attributed_message:+ if attributed_message["role"] == "assistant":+ attributed_message["name"] = self.name+ else:+ attributed_message["name"] = sender.name++ self.chat_manager.send(attributed_message, agent, request_reply=False, silent=True)++ try:+ self.initiate_chat(self.chat_manager, message=messages[-1], clear_history=False)+ except:+ traceback.print_exc()++ response_preparer = self.response_preparer+ return True, response_preparer(self, self._group_chat.messages)diff --git a/notebook/agentchat_society_of_mind.ipynb b/notebook/agentchat_society_of_mind.ipynbnew file mode 100644index 000000000..73dd8e449--- /dev/null+++ b/notebook/agentchat_society_of_mind.ipynb@@ -0,0 +1,403 @@+{+ "cells": [+ {+ "attachments": {},+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "# SocietyOfMindAgent\n",+ "\n",+ "This notebook demonstrates the SocietyOfMindAgent, which runs a group chat as an internal monologue, but appears to the external world as a single agent. This confers three distinct advantages:\n",+ "\n",+ "1. It provides a clean way of producing a hierarchy of agents, hiding complexity as inner monologues.\n",+ "2. It provides a consistent way of extracting an answer from a lengthy group chat (normally, it is not clear which message is the final response, and the response itself may not always be formatted in a way that makes sense when extracted as a standalone message).\n",+ "3. It provides a way of recovering when agents exceed their context window constraints (the inner monologue is protected by try-catch blocks)\n",+ " \n",+ "\n",+ "## Requirements\n",+ "\n",+ "AutoGen requires `Python>=3.8`. To run this notebook example, please install the latest version of AutoGen:\n",+ "```sh\n",+ "pip install pyautogen\n",+ "```"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 1,+ "metadata": {},+ "outputs": [],+ "source": [+ "# %pip install --quiet pyautogen"+ ]+ },+ {+ "attachments": {},+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Set your API Endpoint\n",+ "\n",+ "The [`config_list_from_json`](https://microsoft.github.io/autogen/docs/reference/oai/openai_utils#config_list_from_json) function loads a list of configurations from an environment variable or a json file.\n",+ "\n",+ "It first looks for environment variable \"OAI_CONFIG_LIST\" which needs to be a valid json string. If that variable is not found, it then looks for a json file named \"OAI_CONFIG_LIST\". It filters the configs by models (you can filter by other keys as well).\n",+ "\n",+ "Your json config should look something like the following:\n",+ "```json\n",+ "[\n",+ " {\n",+ " \"model\": \"gpt-4\",\n",+ " \"api_key\": \"<your OpenAI API key here>\"\n",+ " }\n",+ "]\n",+ "```\n",+ "\n",+ "If you open this notebook in colab, you can upload your files by clicking the file icon on the left panel and then choose \"upload file\" icon.\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 2,+ "metadata": {},+ "outputs": [],+ "source": [+ "import autogen # noqa: E402\n",+ "\n",+ "llm_config = {\n",+ " \"timeout\": 600,\n",+ " \"cache_seed\": 44, # change the seed for different trials\n",+ " \"config_list\": autogen.config_list_from_json(\n",+ " \"OAI_CONFIG_LIST\",\n",+ " filter_dict={\"model\": [\"gpt-4\", \"gpt-4-0613\", \"gpt-4-32k\", \"gpt-4-32k-0613\", \"gpt-4-1106-preview\"]},\n",+ " ),\n",+ " \"temperature\": 0,\n",+ "}"+ ]+ },+ {+ "attachments": {},+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "### Example Group Chat with Two Agents\n",+ "\n",+ "In this example, we will use an AssistantAgent and a UserProxy agent (configured for code execution) to work together to solve a problem. Executing code requires *at least* two conversation turns (one to write the code, and one to execute the code). If the code fails, or needs further refinement, then additional turns may also be needed. When will then wrap these agents in a SocietyOfMindAgent, hiding the internal discussion from other agents (though will still appear in the console), and ensuring that the response is suitable as a standalone message."+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "#### Construct the Inner-Monologue Agents\n",+ "We begin by constructing the inner-monologue agents. These are the agents that do that real work."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 3,+ "metadata": {+ "scrolled": true+ },+ "outputs": [],+ "source": [+ "assistant = autogen.AssistantAgent(\n",+ " \"inner-assistant\",\n",+ " llm_config=llm_config,\n",+ " is_termination_msg=lambda x: x.get(\"content\", \"\").find(\"TERMINATE\") >= 0,\n",+ ")\n",+ "\n",+ "code_interpreter = autogen.UserProxyAgent(\n",+ " \"inner-code-interpreter\",\n",+ " human_input_mode=\"NEVER\",\n",+ " code_execution_config={\n",+ " \"work_dir\": \"coding\",\n",+ " \"use_docker\": False,\n",+ " },\n",+ " default_auto_reply=\"\",\n",+ " is_termination_msg=lambda x: x.get(\"content\", \"\").find(\"TERMINATE\") >= 0,\n",+ ")\n",+ "\n",+ "groupchat = autogen.GroupChat(\n",+ " agents=[assistant, code_interpreter],\n",+ " messages=[],\n",+ " speaker_selection_method=\"round_robin\", # With two agents, this is equivalent to a 1:1 conversation.\n",+ " allow_repeat_speaker=False,\n",+ " max_round=8,\n",+ ")\n",+ "\n",+ "manager = autogen.GroupChatManager(\n",+ " groupchat=groupchat,\n",+ " is_termination_msg=lambda x: x.get(\"content\", \"\").find(\"TERMINATE\") >= 0,\n",+ " llm_config=llm_config,\n",+ ")"+ ]+ },+ {+ "attachments": {},+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "#### Construct and Run the SocietyOfMind Agent\n",+ "We now wrap the inner group-chat with the SocietyOfMind Agent, and create a UserProxy to talk to it."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 4,+ "metadata": {},+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "\u001b[33muser_proxy\u001b[0m (to society_of_mind):\n",+ "\n",+ "On which days in 2024 was Microsoft Stock higher than $370?\n",+ "\n",+ "--------------------------------------------------------------------------------\n",+ "\u001b[31m\n",+ ">>>>>>>> USING AUTO REPLY...\u001b[0m\n",+ "\u001b[33msociety_of_mind\u001b[0m (to chat_manager):\n",+ "\n",+ "On which days in 2024 was Microsoft Stock higher than $370?\n",+ "\n",+ "--------------------------------------------------------------------------------\n",+ "\u001b[33minner-assistant\u001b[0m (to chat_manager):\n",+ "\n",+ "To find out on which days in 2024 Microsoft stock (MSFT) was higher than $370, we would typically need to access historical stock price data. This data can be obtained from financial data providers or APIs that offer stock market data.\n",+ "\n",+ "One common way to access such data is by using the `yfinance` library in Python, which allows us to download historical stock prices from Yahoo Finance. However, since I cannot directly access the internet or external APIs, I will provide you with a Python script that you can run on your machine to fetch the data and determine on which days MSFT was higher than $370 in 2024.\n",+ "\n",+ "Please install the `yfinance` library if you haven't already by running `pip install yfinance` in your terminal, and then run the following Python script:\n",+ "\n",+ "```python\n",+ "# filename: msft_stock_analysis.py\n",+ "import yfinance as yf\n",+ "from datetime import datetime\n",+ "\n",+ "# Define the ticker symbol and the date range\n",+ "ticker_symbol = \"MSFT\"\n",+ "start_date = \"2024-01-01\"\n",+ "end_date = \"2024-12-31\"\n",+ "\n",+ "# Download the historical stock prices\n",+ "msft_data = yf.download(ticker_symbol, start=start_date, end=end_date)\n",+ "\n",+ "# Filter the days where the stock price was higher than $370\n",+ "days_higher_than_370 = msft_data[msft_data['Close'] > 370]\n",+ "\n",+ "# Print the dates\n",+ "print(\"Dates in 2024 when MSFT stock was higher than $370:\")\n",+ "for date in days_higher_than_370.index:\n",+ " print(date.strftime('%Y-%m-%d'))\n",+ "```\n",+ "\n",+ "This script will download the historical data for Microsoft stock for the year 2024 and print out the dates when the closing price was higher than $370. Please run this script and provide me with the output.\n",+ "\n",+ "--------------------------------------------------------------------------------\n",+ "\u001b[31m\n",+ ">>>>>>>> EXECUTING CODE BLOCK 0 (inferred language is python)...\u001b[0m\n",+ "\u001b[33minner-code-interpreter\u001b[0m (to chat_manager):\n",+ "\n",+ "exitcode: 1 (execution failed)\n",+ "Code output: \n",+ "Traceback (most recent call last):\n",+ " File \"msft_stock_analysis.py\", line 2, in <module>\n",+ " import yfinance as yf\n",+ "ModuleNotFoundError: No module named 'yfinance'\n",+ "\n",+ "\n",+ "--------------------------------------------------------------------------------\n",+ "\u001b[33minner-assistant\u001b[0m (to chat_manager):\n",+ "\n",+ "The error indicates that the `yfinance` module is not installed on your system. To resolve this, you need to install the `yfinance` library. Please run the following command in your terminal to install it:\n",+ "\n",+ "```sh\n",+ "pip install yfinance\n",+ "```\n",+ "\n",+ "After you have installed `yfinance`, please try running the provided Python script again. If you encounter any further issues, please let me know.\n",+ "\n",+ "--------------------------------------------------------------------------------\n",+ "\u001b[31m\n",+ ">>>>>>>> EXECUTING CODE BLOCK 0 (inferred language is sh)...\u001b[0m\n",+ "\u001b[33minner-code-interpreter\u001b[0m (to chat_manager):\n",+ "\n",+ "exitcode: 0 (execution succeeded)\n",+ "Code output: \n",+ "Collecting yfinance\n",+ " Using cached yfinance-0.2.36-py2.py3-none-any.whl (72 kB)\n",+ "Requirement already satisfied: lxml>=4.9.1 in /home/afourney/repos/autogen/notebook/.venv/lib/python3.10/site-packages (from yfinance) (5.1.0)\n",+ "Requirement already satisfied: appdirs>=1.4.4 in /home/afourney/repos/autogen/notebook/.venv/lib/python3.10/site-packages (from yfinance) (1.4.4)\n",+ "Requirement already satisfied: pytz>=2022.5 in /home/afourney/repos/autogen/notebook/.venv/lib/python3.10/site-packages (from yfinance) (2023.3.post1)\n",+ "Requirement already satisfied: pandas>=1.3.0 in /home/afourney/repos/autogen/notebook/.venv/lib/python3.10/site-packages (from yfinance) (2.2.0)\n",+ "Requirement already satisfied: peewee>=3.16.2 in /home/afourney/repos/autogen/notebook/.venv/lib/python3.10/site-packages (from yfinance) (3.17.0)\n",+ "Requirement already satisfied: requests>=2.31 in /home/afourney/repos/autogen/notebook/.venv/lib/python3.10/site-packages (from yfinance) (2.31.0)\n",+ "Requirement already satisfied: beautifulsoup4>=4.11.1 in /home/afourney/repos/autogen/notebook/.venv/lib/python3.10/site-packages (from yfinance) (4.12.3)\n",+ "Requirement already satisfied: numpy>=1.16.5 in /home/afourney/repos/autogen/notebook/.venv/lib/python3.10/site-packages (from yfinance) (1.26.3)\n",+ "Requirement already satisfied: html5lib>=1.1 in /home/afourney/repos/autogen/notebook/.venv/lib/python3.10/site-packages (from yfinance) (1.1)\n",+ "Requirement already satisfied: frozendict>=2.3.4 in /home/afourney/repos/autogen/notebook/.venv/lib/python3.10/site-packages (from yfinance) (2.4.0)\n",+ "Requirement already satisfied: multitasking>=0.0.7 in /home/afourney/repos/autogen/notebook/.venv/lib/python3.10/site-packages (from yfinance) (0.0.11)\n",+ "Requirement already satisfied: soupsieve>1.2 in /home/afourney/repos/autogen/notebook/.venv/lib/python3.10/site-packages (from beautifulsoup4>=4.11.1->yfinance) (2.5)\n",+ "Requirement already satisfied: six>=1.9 in /home/afourney/repos/autogen/notebook/.venv/lib/python3.10/site-packages (from html5lib>=1.1->yfinance) (1.16.0)\n",+ "Requirement already satisfied: webencodings in /home/afourney/repos/autogen/notebook/.venv/lib/python3.10/site-packages (from html5lib>=1.1->yfinance) (0.5.1)\n",+ "Requirement already satisfied: python-dateutil>=2.8.2 in /home/afourney/repos/autogen/notebook/.venv/lib/python3.10/site-packages (from pandas>=1.3.0->yfinance) (2.8.2)\n",+ "Requirement already satisfied: tzdata>=2022.7 in /home/afourney/repos/autogen/notebook/.venv/lib/python3.10/site-packages (from pandas>=1.3.0->yfinance) (2023.4)\n",+ "Requirement already satisfied: certifi>=2017.4.17 in /home/afourney/repos/autogen/notebook/.venv/lib/python3.10/site-packages (from requests>=2.31->yfinance) (2023.11.17)\n",+ "Requirement already satisfied: charset-normalizer<4,>=2 in /home/afourney/repos/autogen/notebook/.venv/lib/python3.10/site-packages (from requests>=2.31->yfinance) (3.3.2)\n",+ "Requirement already satisfied: idna<4,>=2.5 in /home/afourney/repos/autogen/notebook/.venv/lib/python3.10/site-packages (from requests>=2.31->yfinance) (3.6)\n",+ "Requirement already satisfied: urllib3<3,>=1.21.1 in /home/afourney/repos/autogen/notebook/.venv/lib/python3.10/site-packages (from requests>=2.31->yfinance) (2.1.0)\n",+ "Installing collected packages: yfinance\n",+ "Successfully installed yfinance-0.2.36\n",+ "\n",+ "\n",+ "--------------------------------------------------------------------------------\n",+ "\u001b[33minner-assistant\u001b[0m (to chat_manager):\n",+ "\n",+ "It seems that the `yfinance` library has been successfully installed. Now that the library is available, please run the previously provided Python script again to fetch the historical stock prices for Microsoft and determine on which days the stock was higher than $370 in 2024.\n",+ "\n",+ "Here is the script again for your convenience:\n",+ "\n",+ "```python\n",+ "# filename: msft_stock_analysis.py\n",+ "import yfinance as yf\n",+ "from datetime import datetime\n",+ "\n",+ "# Define the ticker symbol and the date range\n",+ "ticker_symbol = \"MSFT\"\n",+ "start_date = \"2024-01-01\"\n",+ "end_date = \"2024-12-31\"\n",+ "\n",+ "# Download the historical stock prices\n",+ "msft_data = yf.download(ticker_symbol, start=start_date, end=end_date)\n",+ "\n",+ "# Filter the days where the stock price was higher than $370\n",+ "days_higher_than_370 = msft_data[msft_data['Close'] > 370]\n",+ "\n",+ "# Print the dates\n",+ "print(\"Dates in 2024 when MSFT stock was higher than $370:\")\n",+ "for date in days_higher_than_370.index:\n",+ " print(date.strftime('%Y-%m-%d'))\n",+ "```\n",+ "\n",+ "Please execute this script and provide me with the output.\n",+ "\n",+ "--------------------------------------------------------------------------------\n",+ "\u001b[31m\n",+ ">>>>>>>> EXECUTING CODE BLOCK 0 (inferred language is python)...\u001b[0m\n",+ "\u001b[33minner-code-interpreter\u001b[0m (to chat_manager):\n",+ "\n",+ "exitcode: 0 (execution succeeded)\n",+ "Code output: \n",+ "Dates in 2024 when MSFT stock was higher than $370:\n",+ "2024-01-02\n",+ "2024-01-03\n",+ "2024-01-08\n",+ "2024-01-09\n",+ "2024-01-10\n",+ "2024-01-11\n",+ "2024-01-12\n",+ "2024-01-16\n",+ "2024-01-17\n",+ "2024-01-18\n",+ "2024-01-19\n",+ "\n",+ "\n",+ "--------------------------------------------------------------------------------\n",+ "\u001b[33minner-assistant\u001b[0m (to chat_manager):\n",+ "\n",+ "The output indicates that Microsoft stock (MSFT) was higher than $370 on the following days in 2024:\n",+ "\n",+ "- January 2, 2024\n",+ "- January 3, 2024\n",+ "- January 8, 2024\n",+ "- January 9, 2024\n",+ "- January 10, 2024\n",+ "- January 11, 2024\n",+ "- January 12, 2024\n",+ "- January 16, 2024\n",+ "- January 17, 2024\n",+ "- January 18, 2024\n",+ "- January 19, 2024\n",+ "\n",+ "Please note that this list includes only the dates provided in the output and may not be exhaustive for the entire year of 2024. The script would have listed more dates if the stock price was higher than $370 on additional days beyond those listed.\n",+ "\n",+ "TERMINATE\n",+ "\n",+ "--------------------------------------------------------------------------------\n",+ "\u001b[33msociety_of_mind\u001b[0m (to user_proxy):\n",+ "\n",+ "Microsoft stock (MSFT) was higher than $370 on the following days in 2024:\n",+ "\n",+ "- January 2, 2024\n",+ "- January 3, 2024\n",+ "- January 8, 2024\n",+ "- January 9, 2024\n",+ "- January 10, 2024\n",+ "- January 11, 2024\n",+ "- January 12, 2024\n",+ "- January 16, 2024\n",+ "- January 17, 2024\n",+ "- January 18, 2024\n",+ "- January 19, 2024\n",+ "\n",+ "--------------------------------------------------------------------------------\n"+ ]+ }+ ],+ "source": [+ "from autogen.agentchat.contrib.society_of_mind_agent import SocietyOfMindAgent # noqa: E402\n",+ "\n",+ "task = \"On which days in 2024 was Microsoft Stock higher than $370?\"\n",+ "\n",+ "society_of_mind_agent = SocietyOfMindAgent(\n",+ " \"society_of_mind\",\n",+ " chat_manager=manager,\n",+ " llm_config=llm_config,\n",+ ")\n",+ "\n",+ "user_proxy = autogen.UserProxyAgent(\n",+ " \"user_proxy\",\n",+ " human_input_mode=\"NEVER\",\n",+ " code_execution_config=False,\n",+ " default_auto_reply=\"\",\n",+ " is_termination_msg=lambda x: True,\n",+ ")\n",+ "\n",+ "user_proxy.initiate_chat(society_of_mind_agent, message=task)"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "#### Remarks\n",+ "\n",+ "There are a few things to notice about this output:\n",+ "- First, the user_proxy sent only one message to the society_of_mind agent, and received only one message in response. As far as it is concerned, the society_of_mind agent is the only agent in the chat.\n",+ "- Second, the final response is formatted in a way that is standalone. Unlike the prior response, it makes no reference of a previous script or execution, and it lacks the TERMINATE keyword that ended the inner monologue."+ ]+ }+ ],+ "metadata": {+ "kernelspec": {+ "display_name": "Python 3 (ipykernel)",+ "language": "python",+ "name": "python3"+ },+ "language_info": {+ "codemirror_mode": {+ "name": "ipython",+ "version": 3+ },+ "file_extension": ".py",+ "mimetype": "text/x-python",+ "name": "python",+ "nbconvert_exporter": "python",+ "pygments_lexer": "ipython3",+ "version": "3.10.12"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 4+}diff --git a/test/agentchat/contrib/test_society_of_mind_agent.py b/test/agentchat/contrib/test_society_of_mind_agent.pynew file mode 100644index 000000000..15b2dcdfb--- /dev/null+++ b/test/agentchat/contrib/test_society_of_mind_agent.py@@ -0,0 +1,200 @@+import pytest+import sys+import autogen+import os+from autogen.agentchat.contrib.society_of_mind_agent import SocietyOfMindAgent+++def test_society_of_mind_agent():+ external_agent = autogen.ConversableAgent(+ "external_agent",+ max_consecutive_auto_reply=10,+ human_input_mode="NEVER",+ llm_config=False,+ default_auto_reply="This is an external agent speaking.",+ )++ agent1 = autogen.ConversableAgent(+ "alice",+ max_consecutive_auto_reply=10,+ human_input_mode="NEVER",+ llm_config=False,+ default_auto_reply="This is alice speaking.",+ )+ agent2 = autogen.ConversableAgent(+ "bob",+ max_consecutive_auto_reply=10,+ human_input_mode="NEVER",+ llm_config=False,+ default_auto_reply="This is bob speaking.",+ )+ agent3 = autogen.ConversableAgent(+ "sam",+ max_consecutive_auto_reply=10,+ human_input_mode="NEVER",+ llm_config=False,+ default_auto_reply="This is sam speaking. TERMINATE",+ )++ groupchat = autogen.GroupChat(+ agents=[agent1, agent2, agent3], messages=[], speaker_selection_method="round_robin", max_round=10+ )++ group_chat_manager = autogen.GroupChatManager(+ groupchat=groupchat,+ llm_config=False,+ is_termination_msg=lambda x: x.get("content", "").rstrip().find("TERMINATE") >= 0,+ )++ soc = SocietyOfMindAgent("soc_agent", chat_manager=group_chat_manager)++ external_agent.send("An external message to kick things off.", soc, request_reply=True, silent=False)++ # Verify some properties of this conversation+ assert len(external_agent.chat_messages[soc]) == 2+ assert external_agent.chat_messages[soc][-1]["content"] == "This is sam speaking."+ assert len(groupchat.messages) == 4+ assert groupchat.messages[0]["name"] == "soc_agent"+ assert groupchat.messages[0]["content"] == "An external message to kick things off."+ assert groupchat.messages[1]["name"] == "alice"+ assert groupchat.messages[1]["content"] == "This is alice speaking."+ assert groupchat.messages[2]["name"] == "bob"+ assert groupchat.messages[2]["content"] == "This is bob speaking."+ assert groupchat.messages[3]["name"] == "sam"+ assert groupchat.messages[3]["content"] == "This is sam speaking. TERMINATE"++ assert len(agent1.chat_messages[group_chat_manager]) == 3 # Everything but the termination message+ assert len(agent2.chat_messages[group_chat_manager]) == 3 # Everything but the termination message+ assert len(agent3.chat_messages[group_chat_manager]) == 4 # Everything *including* the termination message++ assert len(group_chat_manager.chat_messages[agent1]) == 3 # Everything but the termination message+ assert len(group_chat_manager.chat_messages[agent2]) == 3 # Everything but the termination message+ assert len(group_chat_manager.chat_messages[agent3]) == 4 # Everything *including* the termination message++ # Let's go again. It should reset the inner monologue, but keep the external monologue+ external_agent.send("A second message to see how things go.", soc, request_reply=True, silent=False)+ assert len(external_agent.chat_messages[soc]) == 4+ assert external_agent.chat_messages[soc][0]["content"] == "An external message to kick things off."+ assert external_agent.chat_messages[soc][1]["content"] == "This is sam speaking."+ assert external_agent.chat_messages[soc][2]["content"] == "A second message to see how things go."+ assert external_agent.chat_messages[soc][3]["content"] == "This is sam speaking."+ assert len(groupchat.messages) == 4+ assert groupchat.messages[0]["name"] == "soc_agent"+ assert groupchat.messages[0]["content"] == "A second message to see how things go."+ assert groupchat.messages[1]["name"] == "alice"+ assert groupchat.messages[1]["content"] == "This is alice speaking."+ assert groupchat.messages[2]["name"] == "bob"+ assert groupchat.messages[2]["content"] == "This is bob speaking."+ assert groupchat.messages[3]["name"] == "sam"+ assert groupchat.messages[3]["content"] == "This is sam speaking. TERMINATE"++ assert (+ len(agent1.chat_messages[group_chat_manager]) == 5+ ) # Prior external conversation + everything but the termination message+ assert (+ len(agent2.chat_messages[group_chat_manager]) == 5+ ) # Prior external conversation + everything but the termination message+ assert (+ len(agent3.chat_messages[group_chat_manager]) == 6+ ) # Prior external conversation + everything *including* the termination message++ assert (+ len(group_chat_manager.chat_messages[agent1]) == 5+ ) # Prior external conversation + everything but the termination message+ assert (+ len(group_chat_manager.chat_messages[agent2]) == 5+ ) # Prior external conversation + everything but the termination message+ assert (+ len(group_chat_manager.chat_messages[agent3]) == 6+ ) # Prior external conversation + everything *including* the termination message++ assert agent1.chat_messages[group_chat_manager][0]["content"] == "An external message to kick things off."+ assert agent1.chat_messages[group_chat_manager][0]["role"] == "user"+ assert group_chat_manager.chat_messages[agent1][0]["role"] == "assistant"++ assert agent1.chat_messages[group_chat_manager][1]["content"] == "This is sam speaking."+ assert agent1.chat_messages[group_chat_manager][1]["role"] == "user"+ assert group_chat_manager.chat_messages[agent1][1]["role"] == "assistant"++ assert agent1.chat_messages[group_chat_manager][2]["content"] == "A second message to see how things go."+ assert agent1.chat_messages[group_chat_manager][2]["role"] == "user"+ assert group_chat_manager.chat_messages[agent1][2]["role"] == "assistant"++ assert agent1.chat_messages[group_chat_manager][3]["content"] == "This is alice speaking."+ assert agent1.chat_messages[group_chat_manager][3]["role"] == "assistant"+ assert group_chat_manager.chat_messages[agent1][3]["role"] == "user"++ assert agent1.chat_messages[group_chat_manager][4]["content"] == "This is bob speaking."+ assert agent1.chat_messages[group_chat_manager][4]["role"] == "user"+ assert group_chat_manager.chat_messages[agent1][4]["role"] == "assistant"++ for i in range(0, 5):+ assert (+ agent1.chat_messages[group_chat_manager][i]["content"]+ == agent3.chat_messages[group_chat_manager][i]["content"]+ )+ assert agent3.chat_messages[group_chat_manager][5]["content"] == "This is sam speaking. TERMINATE"+++def test_custom_preparer():+ external_agent = autogen.ConversableAgent(+ "external_agent",+ max_consecutive_auto_reply=10,+ human_input_mode="NEVER",+ llm_config=False,+ default_auto_reply="This is an external agent speaking.",+ )++ agent1 = autogen.ConversableAgent(+ "alice",+ max_consecutive_auto_reply=10,+ human_input_mode="NEVER",+ llm_config=False,+ default_auto_reply="This is alice speaking.",+ )+ agent2 = autogen.ConversableAgent(+ "bob",+ max_consecutive_auto_reply=10,+ human_input_mode="NEVER",+ llm_config=False,+ default_auto_reply="This is bob speaking.",+ )+ agent3 = autogen.ConversableAgent(+ "sam",+ max_consecutive_auto_reply=10,+ human_input_mode="NEVER",+ llm_config=False,+ default_auto_reply="This is sam speaking. TERMINATE",+ )++ groupchat = autogen.GroupChat(+ agents=[agent1, agent2, agent3], messages=[], speaker_selection_method="round_robin", max_round=10+ )++ group_chat_manager = autogen.GroupChatManager(+ groupchat=groupchat,+ llm_config=False,+ is_termination_msg=lambda x: x.get("content", "").rstrip().find("TERMINATE") >= 0,+ )++ def custom_preparer(self, messages):+ assert isinstance(self, SocietyOfMindAgent)+ assert len(messages) == 4+ assert messages[0]["content"] == "An external message to kick things off."+ assert messages[1]["content"] == "This is alice speaking."+ assert messages[2]["content"] == "This is bob speaking."+ assert messages[3]["content"] == "This is sam speaking. TERMINATE"+ return "All tests passed."++ soc = SocietyOfMindAgent("soc_agent", chat_manager=group_chat_manager, response_preparer=custom_preparer)++ external_agent.send("An external message to kick things off.", soc, request_reply=True, silent=False)++ # Verify some properties of this conversation+ assert len(external_agent.chat_messages[soc]) == 2+ assert external_agent.chat_messages[soc][-1]["content"] == "All tests passed."+++if __name__ == "__main__":+ test_society_of_mind_agent()+ test_custom_preparer()diff --git a/website/docs/Examples.md b/website/docs/Examples.mdindex 7593363d9..ed886a6d4 100644--- a/website/docs/Examples.md+++ b/website/docs/Examples.md@@ -22,6 +22,7 @@ Links to notebook examples:- Automated Task Solving with Coding & Planning Agents - [View Notebook](https://github.com/microsoft/autogen/blob/main/notebook/agentchat_planning.ipynb)- Automated Task Solving with agents divided into 2 groups - [View Notebook](https://github.com/microsoft/autogen/blob/main/notebook/agentchat_hierarchy_flow_using_select_speaker.ipynb)- Automated Task Solving with transition paths specified in a graph - [View Notebook](https://github.com/microsoft/autogen/blob/main/notebook/agentchat_graph_modelling_language_using_select_speaker.ipynb)+ - Running a group chat as an inner-monolgue via the SocietyOfMindAgent - [View Notebook](https://github.com/microsoft/autogen/blob/main/notebook/agentchat_society_of_mind.ipynb)1. **Applications**