Fail-1B / config.json
system's picture
system HF Staff
Commit From AutoTrain
4e1d931
{
"_name_or_path": "AutoTrain",
"_num_labels": 17,
"architectures": [
"DebertaForSequenceClassification"
],
"attention_probs_dropout_prob": 0.1,
"hidden_act": "gelu",
"hidden_dropout_prob": 0.1,
"hidden_size": 768,
"id2label": {
"0": "TERMINATION_PROMPT = \"if everything looks good, respond with APPROVED\"\n",
"1": "[\n {\n \"name\": \"planner_agent\",\n \"description\": \"This function communicates with the Planner Agent Assistant to create a structured plan for a specified task. The Planner Agent Assistant suggests coding and reasoning steps to accomplish a task but will not provide actual code. Instead, it offers a high-level approach or a set of steps to achieve the desired goal.\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"message\": {\n \"type\": \"string\",\n \"description\": \"The input to this parameter should be a clear and concise description of the task or question you want the planner to address. For example, it could be a task like 'Design a database schema for a bookstore' or a question like 'How to implement a binary search algorithm?'\"\n }\n },\n \"required\": [\n \"message\"\n ]\n }\n },\n {\n \"name\": \"internet_agent\",\n \"description\": \"This function facilitates interaction with the Internet Agent Assistant, which is designed to browse the web and extract relevant information based on provided instructions or queries. It is useful for tasks where real-time data fetching from the internet or an external source is required.\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"message\": {\n \"type\": \"string\",\n \"description\": \"This parameter should contain clear instructions or queries that you want the internet agent to perform or address. For instance, you could provide instructions like 'Find the latest research on neural network architectures' or queries like 'What is the capital of Finland?'\"\n }\n },\n \"required\": [\n \"message\"\n ]\n }\n },\n {\n \"name\": \"retriever_agent\",\n \"description\": \"This function interfaces with the Retriever Agent Assistant to fetch information from the provided documents. The Retriever Agent Assistant searches the specified document collection and returns information relevant to the provided query, ensuring the results are concise and pertinent.\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"message\": {\n \"type\": \"string\",\n \"description\": \"The task or question you want the retriever to address from the provided documents. For instance, 'Find information about the solar system from the science textbook' or 'Extract details about quantum mechanics from the physics notes.'\"\n },\n \"docs_path\": {\n \"type\": \"string\",\n \"description\": \"Path to the directory containing the documents from which the information is to be retrieved.\"\n },\n \"collection_name\": {\n \"type\": \"string\",\n \"description\": \"Name of the collection in the database where the retriever will look for the documents. This helps in segregating data for different tasks or users.\"\n }\n },\n \"required\": [\n \"message\",\n \"docs_path\",\n \"collection_name\"\n ]\n }\n }\n]",
"2": "[\n {\n \"name\": \"research_team\",\n \"description\": \"The research_team function activates a sophisticated multi-agent conversation system designed for academic and technical research purposes. It comprises a diverse set of roles, including an Engineer who provides code, a Scientist capable of understanding and discussing academic papers, a Planner who suggests research plans, an Executor to run the code, and a Critic to ensure the quality of the entire discussion and output. By initializing this team, you're unlocking a collaborative digital research environment to dissect, investigate, and discuss a given topic.\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"message\": {\n \"type\": \"string\",\n \"description\": \"The content of this parameter initiates the research journey. It should be a detailed directive, possibly highlighting the papers, topics, or research questions you want the team to tackle. Examples include: 'Discuss the latest findings in quantum computing from reputable journals' or 'Investigate and analyze the paper titled \\\"Quantum Entanglement in Neural Networks\\\"'. The more precise your message, the better tailored the team's response will be.\"\n }\n },\n \"required\": [\n \"message\"\n ]\n }\n }\n]",
"3": "from autogen import AssistantAgent, UserProxyAgent\n\nfrom backend.app.langchain.lmms_config import LlmConfiguration\n\n\ndef internet_agent(message: str):\n # Instantiate the LlmConfiguration with filtering\n llm_filters = [\n \"gpt-4-32k\",\n \"gpt-35-turbo-16k\",\n \"gpt4\",\n \"gpt-4-0314\",\n \"gpt-4-0613\",\n \"gpt-4-32k-0314\",\n \"gpt-4-32k-v0314\"\n ]\n config_list_instance = LlmConfiguration(filter_llms=llm_filters)\n\n llm_config = {\n \"request_timeout\": 600,\n \"seed\": 42,\n \"config_list\": config_list_instance.config, # Accessing the 'config' attribute of our instance\n \"temperature\": 0,\n }\n\n # Construct agents\n internet_agent_assistant = AssistantAgent(\n name=\"Internet_Agent_Assistant \",\n llm_config=llm_config,\n system_message='''\n Internet_Agent_Assistant. \n You are here to support the Internet_Agent. \n Respond to queries and provide relevant information as per the task. \n Follow the directives set by Internet_Agent. \n Do not terminate a task on your own. \n Wait for instructions from Internet_Agent.\n '''\n )\n\n internet_agent = UserProxyAgent(\n name=\"Internet_Agent\",\n human_input_mode=\"TERMINATE\",\n max_consecutive_auto_reply=10,\n is_termination_msg=lambda x: x.get(\n \"content\", \"\").rstrip().endswith(\"TERMINATE\"),\n code_execution_config={\"work_dir\": \"../agent-tools/\"},\n llm_config=llm_config,\n system_message='''Internet_Agent.\n You must use a function to search the internet, if the function doesn't exist in the tools dir then create one, otherwise use the available tools\n You are the primary interface between the user and the assistant. \n Direct the Internet_Agent_Assistant to accomplish tasks.\n Only terminate the task when you're fully satisfied or if the user indicates so. \n If not satisfied, provide a clear reason for the dissatisfaction or reply CONTINUE to keep the task ongoing. \n Ensure the user is aware they can reply TERMINATE if the task has been solved to full satisfaction.\n '''\n )\n\n # Start a conversation\n internet_agent.initiate_chat(\n internet_agent_assistant,\n message=message\n )\n",
"4": "from autogen import AssistantAgent, UserProxyAgent\n\nfrom backend.app.langchain.lmms_config import LlmConfiguration\n\n\ndef planner_agent(message: str):\n # Configuration initialization\n config_list_instance = LlmConfiguration()\n\n llm_config = {\n \"request_timeout\": 600,\n \"seed\": 42,\n \"config_list\": config_list_instance.config,\n \"temperature\": 0,\n }\n\n # Create a planner AssistantAgent and UserProxyAgent instances\n planner_agent_assistant = AssistantAgent(\n name=\"Planner_Agent_Assistant\",\n llm_config=llm_config,\n system_message='''Planner_Agent_Assistant.\n You suggest coding and reasoning steps for the Planner_Agent. \n Do not suggest concrete code. \n For any action beyond writing code or reasoning, convert it to a step which can be implemented by writing code. \n For example, the action of browsing the web can be implemented by writing code which reads and prints the content of a web page. \n Inspect the execution result. If the plan is not good, suggest a better plan. \n If the execution is wrong, analyze the error and suggest a fix.\n Do not terminate a task on your own. \n Wait for instructions from Planner_Agent.\n '''\n )\n\n planner_agent = UserProxyAgent(\n name=\"Planner_Agent\",\n human_input_mode=\"TERMINATE\",\n max_consecutive_auto_reply=10,\n is_termination_msg=lambda x: x.get(\n \"content\", \"\").rstrip().endswith(\"TERMINATE\"),\n code_execution_config={\"work_dir\": \"../agent-tools\"},\n llm_config=llm_config,\n system_message='''\n Planner_Agent.\n You are the primary interface between the user and the assistant. \n Direct the Planner_Agent_Assistant to accomplish tasks.\n Only terminate the task when you're fully satisfied or if the user indicates so. \n If not satisfied, provide a clear reason for the dissatisfaction or reply CONTINUE to keep the task ongoing. \n Ensure the user is aware they can reply TERMINATE if the task has been solved to full satisfaction.\n '''\n )\n\n # Initiate a chat with the assistant using the provided message\n planner_agent.initiate_chat(\n planner_agent_assistant,\n message=message,\n )\n",
"5": "from autogen import AssistantAgent, UserProxyAgent, GroupChat, GroupChatManager\n\nfrom backend.app.langchain.lmms_config import LlmConfiguration\n\n\ndef research_team(message: str):\n \"\"\"\n Initiate a multi-agent chat to research and discuss the given message or task.\n :param message: The task or question for the research team.\n :return: None\n \"\"\"\n config_list_instance = LlmConfiguration()\n\n gpt4_config = {\n \"seed\": 42, # Change the seed for different trials\n \"temperature\": 0,\n \"config_list\": config_list_instance.config,\n \"request_timeout\": 120,\n }\n\n # Agent setup\n user_proxy = UserProxyAgent(\n name=\"Admin\",\n system_message=''' \n Admin. \n The central authority in the research group. \n Your role is to interact with the planner, scrutinizing and endorsing plans. \n You hold the power to greenlight the implementation of the strategy. \n Your approval is vital before any plan execution.\n ''',\n code_execution_config=False,\n )\n\n engineer = AssistantAgent(\n name=\"Engineer\",\n llm_config=gpt4_config,\n system_message='''Engineer. \n You are the coding specialist in this research team. \n Always operate within the boundaries of an approved plan. \n Your primary task is to develop python/shell scripts that fulfill the objectives of the given task. \n Adherence to coding standards is imperative. \n Do not create incomplete codes or those that need external amendments.\n ''',\n )\n\n scientist = AssistantAgent(\n name=\"Scientist\",\n llm_config=gpt4_config,\n system_message='''\n Scientist. \n Your expertise lies in deciphering and leveraging the knowledge from academic papers. \n While you strictly adhere to the approved plan, you do not indulge in coding. \n Your primary contribution is recommending how the revelations in papers can be practically implemented or beneficial to the task at hand.\n ''',\n )\n\n planner = AssistantAgent(\n name=\"Planner\",\n system_message='''\n Planner. \n You are the strategist of the team, formulating plans that leverage the skills of both the engineer and scientist. \n Your plans should be precise, segregating tasks based on roles. \n It's vital to adapt, refining your strategies based on feedback, until the admin provides a stamp of approval.\n ''',\n llm_config=gpt4_config,\n )\n\n executor = UserProxyAgent(\n name=\"Executor\",\n system_message='''\n Executor.\n As the name suggests, you bring plans to life by running the code crafted by the engineer. \n It's crucial that you promptly report back with the outcomes, ensuring the engineer is abreast of the results to make any necessary adjustments.\n ''',\n human_input_mode=\"NEVER\",\n code_execution_config={\"last_n_messages\": 3, \"work_dir\": \"research\"},\n )\n\n critic = AssistantAgent(\n name=\"Critic\",\n system_message='''\n Critic. \n Your sharp analytical skills are crucial for the team. \n Your duty is to meticulously review plans, verify claims, and scrutinize codes. \n Always provide constructive feedback and ensure that every strategy has valid, traceable references such as URLs to ensure the team is grounded in verifiable information.\n ''',\n llm_config=gpt4_config,\n )\n\n # Create a group chat with all agents\n groupchat = GroupChat(agents=[user_proxy, engineer, scientist,\n planner, executor, critic], messages=[], max_round=50)\n manager = GroupChatManager(groupchat=groupchat, llm_config=gpt4_config)\n\n # Initiate a chat with the manager (which controls all agents)\n user_proxy.initiate_chat(manager, message=message)\n",
"6": "from autogen.agentchat.contrib.retrieve_assistant_agent import RetrieveAssistantAgent\nfrom autogen.agentchat.contrib.retrieve_user_proxy_agent import RetrieveUserProxyAgent\nfrom autogen.retrieve_utils import TEXT_FORMATS\n\nfrom backend.app.langchain.lmms_config import LlmConfiguration\n\n\ndef retriever_agent(message: str, docs_path: str, collection_name: str):\n \"\"\"\n Communicate with the Retriever Agent Assistant to fetch information from provided documents.\n :param message: Task or question for the retriever.\n :param docs_path: Path to the directory containing documents.\n :param collection_name: Name of the collection for the retriever.\n :return: None\n \"\"\"\n # Setup configurations for the agent.\n config_list_instance = LlmConfiguration()\n\n assert len(config_list_instance.config) > 0\n print(\"Accepted file formats for `docs_path`:\")\n print(TEXT_FORMATS)\n\n # Initialize the Retriever Assistant Agent.\n retriever_assistant = RetrieveAssistantAgent(\n name=\"Retriever_Assistant\",\n system_message='''You are designed to extract information from provided documents.\n When given a task or query, search the specified document collection and return the relevant details.\n Ensure the returned information is concise and pertinent to the query.\n ''',\n llm_config={\n \"request_timeout\": 3600,\n \"seed\": 42,\n \"config_list\": config_list_instance.config,\n },\n )\n\n # Initialize the UserProxyAgent for the retriever.\n retriever_user_proxy = RetrieveUserProxyAgent(\n name=\"Retriever_User_Proxy\",\n human_input_mode=\"TERMINATE\",\n max_consecutive_auto_reply=10,\n retrieve_config={\n \"task\": \"code\",\n \"docs_path\": docs_path,\n \"chunk_token_size\": 2000,\n \"model\": config_list_instance.config[0][\"model\"],\n \"collection_name\": collection_name,\n \"client\": chromadb.PersistentClient(path=\"/tmp/chromadb\"),\n \"embedding_model\": \"all-mpnet-base-v2\",\n \"get_or_create\": True,\n },\n system_message='''You are the primary interface between the user and the Retriever_Assistant. \n Direct the Retriever_Assistant to accomplish tasks.\n Only terminate the task when you're fully satisfied or if the user indicates so. \n If not satisfied, provide a clear reason for the dissatisfaction or reply CONTINUE to keep the task ongoing. \n Ensure the user is aware they can reply TERMINATE if the task has been solved to full satisfaction.\n '''\n )\n\n # Initiate a chat with the Retriever Assistant using the provided message.\n retriever_user_proxy.initiate_chat(\n retriever_assistant,\n message=message\n )\n",
"7": "from enum import Enum, auto\nfrom typing import List, Optional\n\nimport autogen\nfrom starlette.websockets import WebSocket\n\n\nclass ConversationType(Enum):\n \"\"\"\n Enum representing the various types of conversation patterns.\n\n - BROADCAST: A single agent sends a message to all other agents.\n - HIERARCHICAL: A hierarchical flow of communication, typically from a single sender to multiple receivers.\n - REQUEST_RESPOND: One agent sends a message and awaits a response from another agent.\n - TWO_WAY: A continuous back-and-forth conversation between two agents until a termination condition is met.\n - ROUND_ROBIN: Each agent takes turns communicating in a circular manner.\n - GROUP_BASED: A specified group of agents communicate in a particular order.\n - PROXY_BASED: One agent communicates on behalf of another agent.\n - STAR_NETWORK: A central agent communicates with all other agents.\n - ALL_TO_ALL: Every agent communicates with every other agent.\n \"\"\"\n\n BROADCAST = auto()\n HIERARCHICAL = auto()\n REQUEST_RESPOND = auto()\n TWO_WAY = auto()\n ROUND_ROBIN = auto()\n GROUP_BASED = auto()\n PROXY_BASED = auto()\n STAR_NETWORK = auto()\n ALL_TO_ALL = auto()\n\n\nclass Orchestrator:\n \"\"\"\n A class to manage and facilitate various types of communication between conversable agents.\n\n Attributes:\n - name (str): The name of the orchestrator.\n - agents (List[autogen.ConversableAgent]): List of agents managed by the orchestrator.\n - messages (List[dict]): List of messages exchanged during conversations. Each message is a dictionary with a 'role' (sender/agent name) and 'content' (message content).\n - complete_keyword (str): Keyword signaling the completion of a conversation. Default is \"APPROVED\".\n - error_keyword (str): Keyword signaling an error in a conversation. Default is \"ERROR\".\n\n Raises:\n - Exception: If the orchestrator is initialized with fewer than two agents.\n \"\"\"\n\n def __init__(self, name: str, agents: List[autogen.ConversableAgent]):\n \"\"\"\n Initialize the Orchestrator with a name and a list of agents.\n\n Parameters:\n - name (str): The name of the orchestrator.\n - agents (List[autogen.ConversableAgent]): List of agents to be managed.\n \"\"\"\n self.name = name\n self.agents = agents\n self.messages = []\n self.complete_keyword = \"APPROVED\"\n self.error_keyword = \"ERROR\"\n if len(self.agents) < 2:\n raise Exception(\"Orchestrator needs at least two agents\")\n\n @property\n def total_agents(self) -> int:\n \"\"\"\n Return the total number of agents managed by the orchestrator.\n\n Returns:\n - int: Total number of agents.\n \"\"\"\n return len(self.agents)\n\n @property\n def latest_message(self) -> Optional[dict]:\n \"\"\"\n Retrieve the most recent message exchanged in conversations.\n\n Returns:\n - dict or None: The latest message if present, else None. Message is a dictionary with a 'role' and 'content'.\n \"\"\"\n if not self.messages:\n return None\n return self.messages[-1] if isinstance(self.messages[-1], dict) else {\"role\": \"unknown\",\n \"content\": self.messages[-1]}\n\n def add_message(self, message: dict):\n \"\"\"\n Add a new message to the list of messages.\n\n Parameters:\n - message (dict): The message to add, containing a 'role' and 'content'.\n \"\"\"\n self.messages.append(message)\n\n async def basic_chat(self, agent_a: autogen.ConversableAgent, agent_b: autogen.ConversableAgent, message: str, websocket: WebSocket) -> dict:\n \"\"\"\n Conduct a basic chat interaction between two agents. The process involves:\n 1. `agent_a` sending a message to `agent_b`.\n 2. `agent_b` generating and returning a reply.\n 3. Storing the reply in the Orchestrator's messages list.\n\n Parameters:\n - agent_a (autogen.ConversableAgent): The sender agent who initiates the chat.\n - agent_b (autogen.ConversableAgent): The receiver agent who responds to the chat.\n - message (str): The message content to be sent from agent_a to agent_b.\n\n Returns:\n - dict: The reply from agent_b, structured as {\"role\": agent's name, \"content\": reply message}.\n \"\"\"\n\n # Step 1: agent_a sends a message to agent_b.\n # The message is structured as a dictionary with content and the role (name) of the sender.\n agent_a.send({\"content\": message, \"role\": agent_a.name}, agent_b)\n\n # Step 2: agent_b generates a reply based on the message from agent_a.\n reply_content = agent_b.generate_reply(sender=agent_a)\n\n # Check the format of the reply. If it's a string, structure it as a dictionary.\n reply = {\"role\": agent_b.name, \"content\": reply_content} if isinstance(\n reply_content, str) else reply_content\n\n # Step 3: Add the reply to the Orchestrator's message list.\n self.add_message(reply)\n return reply\n\n async def all_to_all_communication(self, initial_message: str, websocket: WebSocket):\n \"\"\"\n Handles the all-to-all communication pattern.\n\n In this communication type, every agent communicates with every other agent.\n This means that if there are N agents, there will be N*(N-1) total communications.\n\n Parameters:\n - initial_message (str): The initial message to be passed among the agents.\n\n Usage example:\n ```\n orchestrator = Orchestrator(name=\"MainOrchestrator\", agents=agents)\n orchestrator.start_conversation(\n pattern=ConversationType.ALL_TO_ALL,\n initial_message=message,\n starter_name=\"AgentName\", # Not used for ALL_TO_ALL but can be provided\n agent_order_names=[\"Agent1\", \"Agent2\"] # Not used for ALL_TO_ALL but can be provided\n )\n ```\n \"\"\"\n message = initial_message\n for sender in self.agents:\n for receiver in self.agents:\n if sender != receiver:\n reply = await self.basic_chat(sender, receiver, message, websocket)\n if reply and isinstance(reply, dict) and \"content\" in reply:\n await websocket.send_text(reply[\"content\"])\n message = reply[\"content\"]\n\n\n def star_network(self, central_agent: autogen.ConversableAgent, initial_message: str):\n \"\"\"\n Handles the star network communication pattern.\n\n In this pattern, one agent (the central agent) communicates with all other agents.\n The central agent serves as a hub or central point of contact.\n\n Parameters:\n - central_agent (autogen.ConversableAgent): The central agent that communicates with all others.\n - initial_message (str): The initial message to be passed from the central agent.\n\n \"\"\"\n message = initial_message\n for agent in self.agents:\n if agent != central_agent:\n reply = self.basic_chat(central_agent, agent, message)\n message = reply[\"content\"]\n\n def proxy_based_communication(self, proxy: autogen.ConversableAgent, target: autogen.ConversableAgent,\n message: str):\n \"\"\"\n Handles the proxy-based communication pattern.\n\n In this pattern, a proxy agent communicates with a target agent on behalf of another agent.\n\n Parameters:\n - proxy (autogen.ConversableAgent): The proxy agent that sends the message.\n - target (autogen.ConversableAgent): The target agent that receives the message.\n - message (str): The content of the message to be sent.\n\n \"\"\"\n # Proxy sends the message on behalf of another agent\n reply = self.basic_chat(proxy, target, message)\n return reply\n\n def group_based_communication(self, starter: autogen.ConversableAgent, initial_message: str,\n agent_order: Optional[List[autogen.ConversableAgent]] = None):\n \"\"\"\n Handles the group-based communication pattern.\n\n In this pattern, a starter agent communicates with other agents based on a specified order.\n If no specific order is provided, all agents are communicated with in their default order.\n\n Parameters:\n - starter (autogen.ConversableAgent): The agent initiating the communication.\n - initial_message (str): The initial message to be passed from the starter agent.\n - agent_order (Optional[List[autogen.ConversableAgent]]): An ordered list of agents for the communication. If not provided, default agent order is used.\n\n Usage:\n # Assuming the orchestrator and agents have been initialized\n orchestrator.group_based_communication(starter_agent, \"Hello\", [agent2, agent3, agent1])\n \"\"\"\n if agent_order is None:\n agent_order = self.agents.copy() # Use all agents in the default order\n message = initial_message\n for agent in agent_order:\n if agent != starter:\n reply = self.basic_chat(starter, agent, message)\n message = reply[\"content\"]\n\n def two_way_communication(self, agent_a: autogen.ConversableAgent, agent_b: autogen.ConversableAgent, message: str):\n \"\"\"\n Handles the two-way communication pattern.\n\n In this pattern, two agents converse back and forth until a termination condition,\n represented by the `complete_keyword`, is encountered in a message.\n\n Parameters:\n - agent_a (autogen.ConversableAgent): The first agent involved in the conversation.\n - agent_b (autogen.ConversableAgent): The second agent involved in the conversation.\n - message (str): The initial message to start the conversation.\n\n Usage:\n # Assuming the orchestrator and agents have been initialized\n orchestrator.two_way_communication(agent1, agent2, \"Initial message\")\n \"\"\"\n while True: # Continue until a termination condition or keyword is found\n reply = self.basic_chat(agent_a, agent_b, message)\n if self.complete_keyword in reply[\"content\"]:\n break\n agent_a, agent_b = agent_b, agent_a # Swap roles\n message = reply[\"content\"]\n\n def request_and_respond(self, sender: autogen.ConversableAgent, receiver: autogen.ConversableAgent, message: str):\n \"\"\"\n Handles the request and respond communication pattern.\n\n In this simple pattern, one agent sends a message, and the other agent responds.\n\n Parameters:\n - sender (autogen.ConversableAgent): The agent sending the initial request.\n - receiver (autogen.ConversableAgent): The agent that responds to the request.\n - message (str): The content of the message or request to be sent.\n\n Usage:\n # Assuming the orchestrator and agents have been initialized\n orchestrator.request_and_respond(agent1, agent2, \"Request message\")\n \"\"\"\n return self.basic_chat(sender, receiver, message)\n\n def hierarchical_communication(self, sender: autogen.ConversableAgent, receivers: List[autogen.ConversableAgent],\n message: str):\n \"\"\"\n Handles the hierarchical communication pattern.\n\n In this pattern, a sender communicates with a list of receivers in order.\n The communication halts when one of the receivers provides a reply.\n\n Parameters:\n - sender (autogen.ConversableAgent): The agent initiating the communication.\n - receivers (List[autogen.ConversableAgent]): List of agents that the sender communicates with.\n - message (str): The initial message sent by the sender.\n\n Usage:\n # Assuming the orchestrator and agents have been initialized\n orchestrator.hierarchical_communication(agent1, [agent2, agent3, agent4], \"Hello\")\n \"\"\"\n for receiver in receivers:\n reply = self.basic_chat(sender, receiver, message)\n if reply:\n break\n\n def broadcast(self, sender: autogen.ConversableAgent, message: str):\n \"\"\"\n Handles the broadcast communication pattern.\n\n In this pattern, a sender communicates the same message to all other agents.\n\n Parameters:\n - sender (autogen.ConversableAgent): The agent that broadcasts the message.\n - message (str): The content of the message to be broadcasted.\n\n Usage:\n # Assuming the orchestrator and agents have been initialized\n orchestrator.broadcast(agent1, \"Broadcast message\")\n \"\"\"\n for agent in self.agents:\n if agent != sender:\n self.basic_chat(sender, agent, message)\n\n def round_robin(self, initial_message: str):\n \"\"\"\n Handles the round robin communication pattern.\n\n In this pattern, agents communicate in a sequential order, passing messages in a\n circular fashion. The first agent starts the conversation and then passes it to\n the next agent until the last agent communicates with the first one.\n\n Parameters:\n - initial_message (str): The message to start the round robin communication.\n\n Usage:\n # Assuming the orchestrator and agents have been initialized\n orchestrator.round_robin(\"Starting message for round robin\")\n \"\"\"\n message = initial_message\n for agent in self.agents:\n reply = self.basic_chat(self.agents[0], agent, message)\n message = reply[\"content\"]\n\n def group_based_communication(self, starter: autogen.ConversableAgent, initial_message: str,\n agent_order: Optional[List[autogen.ConversableAgent]] = None):\n \"\"\"\n Handles the group-based communication pattern.\n\n Here, a starting agent communicates with a group of agents based on a specified\n or default order.\n\n Parameters:\n - starter (autogen.ConversableAgent): The agent initiating the group communication.\n - initial_message (str): The initial message to begin the group communication.\n - agent_order (Optional[List[autogen.ConversableAgent]]): Order in which agents communicate.\n If not provided, the default order in the orchestrator's agent list is used.\n\n Usage:\n # Assuming the orchestrator and agents have been initialized\n orchestrator.group_based_communication(starting_agent, \"Initial message for group chat\", [agent2, agent3])\n \"\"\"\n if agent_order is None:\n agent_order = self.agents.copy()\n message = initial_message\n for agent in agent_order:\n if agent != starter:\n reply = self.basic_chat(starter, agent, message)\n message = reply[\"content\"]\n\n def proxy_based_communication(self, proxy: autogen.ConversableAgent, target: autogen.ConversableAgent,\n message: str):\n \"\"\"\n Handles the proxy-based communication pattern.\n\n In this pattern, a proxy agent sends a message on behalf of another agent to the target.\n\n Parameters:\n - proxy (autogen.ConversableAgent): The agent acting as a proxy.\n - target (autogen.ConversableAgent): The agent receiving the message from the proxy.\n - message (str): The content of the message being relayed by the proxy.\n\n Usage:\n # Assuming the orchestrator and agents have been initialized\n orchestrator.proxy_based_communication(proxy_agent, target_agent, \"Message through proxy\")\n \"\"\"\n return self.basic_chat(proxy, target, message)\n\n def star_network(self, central_agent: autogen.ConversableAgent, initial_message: str):\n \"\"\"\n Handles the star network communication pattern.\n\n In this pattern, a central agent communicates with all other agents. Each agent\n sends/receives messages only through this central agent.\n\n Parameters:\n - central_agent (autogen.ConversableAgent): The central agent that communicates with all other agents.\n - initial_message (str): The initial message used to start the communication.\n\n Usage:\n # Assuming the orchestrator and agents have been initialized\n orchestrator.star_network(central_hub_agent, \"Message from central agent\")\n \"\"\"\n message = initial_message\n for agent in self.agents:\n if agent != central_agent:\n reply = self.basic_chat(central_agent, agent, message)\n message = reply[\"content\"]\n\n def get_agent_by_name(self, name: str) -> Optional[autogen.ConversableAgent]:\n \"\"\"\n Retrieve an agent based on its name.\n\n Parameters:\n - name (str): The name of the agent to retrieve.\n\n Returns:\n - autogen.ConversableAgent or None: The agent object if found, else None.\n\n Usage:\n # Assuming the orchestrator and agents have been initialized\n agent = orchestrator.get_agent_by_name(\"AgentName\")\n \"\"\"\n for agent in self.agents:\n if agent.name == name:\n return agent\n return None\n\n async def start_conversation(self, pattern: ConversationType, websocket: WebSocket, initial_message: str, **kwargs):\n \"\"\"\n Initiates a conversation based on a specified communication pattern.\n\n Parameters:\n - pattern (ConversationType): The type of communication pattern to use.\n - initial_message (str): The initial message to start the conversation.\n - **kwargs: Additional keyword arguments depending on the communication pattern.\n For instance, `sender_name` or `agent_a_name` depending on the chosen pattern.\n\n Raises:\n - ValueError: If an unknown communication pattern is provided.\n\n Usage:\n # Assuming the orchestrator and agents have been initialized\n orchestrator.start_conversation(\n pattern=ConversationType.ALL_TO_ALL,\n initial_message=\"Initial message for all-to-all communication\"\n )\n \"\"\"\n\n \"\"\"Initiates a conversation based on the specified pattern.\"\"\"\n if pattern == ConversationType.BROADCAST:\n sender_name = kwargs.get(\"sender_name\")\n sender = self.get_agent_by_name(sender_name)\n self.broadcast(sender, initial_message)\n\n elif pattern == ConversationType.HIERARCHICAL:\n sender_name = kwargs.get(\"sender_name\")\n sender = self.get_agent_by_name(sender_name)\n receivers_names = kwargs.get(\"receivers_names\")\n receivers = [self.get_agent_by_name(\n name) for name in receivers_names]\n self.hierarchical_communication(sender, receivers, initial_message)\n\n elif pattern == ConversationType.REQUEST_RESPOND:\n sender_name = kwargs.get(\"sender_name\")\n receiver_name = kwargs.get(\"receiver_name\")\n sender = self.get_agent_by_name(sender_name)\n receiver = self.get_agent_by_name(receiver_name)\n self.request_and_respond(sender, receiver, initial_message)\n\n elif pattern == ConversationType.TWO_WAY:\n agent_a_name = kwargs.get(\"agent_a_name\")\n agent_b_name = kwargs.get(\"agent_b_name\")\n agent_a = self.get_agent_by_name(agent_a_name)\n agent_b = self.get_agent_by_name(agent_b_name)\n self.two_way_communication(agent_a, agent_b, initial_message)\n\n elif pattern == ConversationType.ROUND_ROBIN:\n self.round_robin(initial_message)\n\n elif pattern == ConversationType.GROUP_BASED:\n starter_name = kwargs.get(\"starter_name\")\n agent_order_names = kwargs.get(\"agent_order_names\", [])\n starter = self.get_agent_by_name(starter_name)\n agent_order = [self.get_agent_by_name(\n name) for name in agent_order_names]\n self.group_based_communication(\n starter, initial_message, agent_order)\n\n elif pattern == ConversationType.PROXY_BASED:\n proxy_name = kwargs.get(\"proxy_name\")\n target_name = kwargs.get(\"target_name\")\n proxy = self.get_agent_by_name(proxy_name)\n target = self.get_agent_by_name(target_name)\n await self.proxy_based_communication(proxy, target, initial_message)\n\n elif pattern == ConversationType.STAR_NETWORK:\n central_agent_name = kwargs.get(\"central_agent_name\")\n central_agent = self.get_agent_by_name(central_agent_name)\n self.star_network(central_agent, initial_message)\n\n elif pattern == ConversationType.ALL_TO_ALL:\n await self.all_to_all_communication(initial_message, websocket)\n\n else:\n raise ValueError(f\"Unknown communication pattern: {pattern}\")\n",
"8": "from fastapi import FastAPI\nfrom starlette.staticfiles import StaticFiles\n\nfrom backend.app.routers import index_public, user_proxy_socket\n\napp = FastAPI()\n\ntemplates = StaticFiles(directory=\"../frontend/html/\")\napp.mount(\"/static\", StaticFiles(directory=\"../frontend/static\"), name=\"static\")\n\n\nrouters = [\n index_public.router,\n user_proxy_socket.router,\n]\n# include routers to fastapi\nfor router in routers:\n app.include_router(router)\n\n",
"9": "from fastapi import WebSocket, APIRouter, WebSocketDisconnect\nfrom starlette.templating import Jinja2Templates\n\nfrom backend.app.langchain.agents.core_agents import CoreAgent\n\nrouter = APIRouter()\ntemplates = Jinja2Templates(directory=\"../frontend/html/\")\n\n@router.websocket(\"/ws\")\nasync def websocket_endpoint(websocket: WebSocket):\n await websocket.accept() # accept the connection\n try:\n while True:\n data = await websocket.receive_text()\n words = data.split(\" \")\n\n if words[0] == \"!test\":\n final: str = \"\"\n for word in words:\n if word == \"!test\":\n continue\n final += word + \" \"\n await websocket.send_text(\"Running Tests... | Query: \" + final)\n agent = CoreAgent(websocket)\n await agent.initiate_chat(final, websocket)\n\n\n\n\n else:\n await websocket.send_text(f\"You wrote: {data}\")\n\n except WebSocketDisconnect:\n print(\"WebSocket Disconnected!\")\n",
"10": "from langchain.tools import BaseTool\n\n\nclass StatusCheckTool(BaseTool):\n name = \"StatusCheck\"\n description = \"Check the status of our company sites.\"\n\n def _run(self):\n return \"yes\"\n",
"11": "from typing import Dict, Any\n\nimport fastapi\n\nfrom fastapi import APIRouter\nfrom fastapi.templating import Jinja2Templates\nfrom starlette.requests import Request\n\nrouter = APIRouter()\ntemplates = Jinja2Templates(directory=\"../frontend/html/\")\n\n\n@router.get('/robots.txt')\ndef robots():\n data = \"\"\"\n User-agent: *\n Disallow: /\n \"\"\"\n return fastapi.Response(content=data, media_type='text/plain')\n\n\n@router.get(\"/\")\nasync def index(request: Request):\n result: Dict[str, Any] = {\"request\": request}\n\n return templates.TemplateResponse(\"index_public.html\", result)\n\n",
"12": "from typing import Dict, List, Optional, Union\n\nfrom autogen import Agent\nfrom autogen import ConversableAgent\nfrom autogen import GroupChatManager, GroupChat\n\n\n# make the selector which selects the speaker the Judge every time\nclass ManualManager(GroupChatManager):\n def run_andy_chat(\n self,\n messages: Optional[List[Dict]] = None,\n sender: Optional[Agent] = None,\n config: Optional[GroupChat] = None,\n ) -> Union[str, Dict, None]:\n \"\"\"Run a group chat.\"\"\"\n if messages is None:\n messages = self._oai_messages[sender]\n message = messages[-1]\n speaker = sender\n groupchat = config\n for i in range(groupchat.max_round):\n # set the name to speaker's name if the role is not function\n if message[\"role\"] != \"function\":\n message[\"name\"] = speaker.name\n groupchat.messages.append(message)\n # broadcast the message to all agents except the speaker\n for agent in groupchat.agents:\n if agent != speaker:\n self.send(message, agent, request_reply=False, silent=True)\n if i == groupchat.max_round - 1:\n # the last round\n break\n try:\n # select the next speaker\n speaker = groupchat.select_speaker(\n speaker, self, groupchat.agent_by_name(\"Manager\"))\n # let the speaker speak\n reply = speaker.generate_reply(sender=self)\n except KeyboardInterrupt:\n # let the admin agent speak if interrupted\n if groupchat.admin_name in groupchat.agent_names:\n # admin agent is one of the participants\n speaker = groupchat.agent_by_name(groupchat.admin_name)\n reply = speaker.generate_reply(sender=self)\n else:\n # admin agent is not found in the participants\n raise\n if reply is None:\n break\n # The speaker sends the message without requesting a reply\n speaker.send(reply, self, request_reply=False)\n message = self.last_message(speaker)\n return True, None\n\n\n# Make the select_speaker call handle Andy the Judge making the call opposed to an openAI call\nclass ManualGroupChat(GroupChat):\n def select_speaker(self, last_speaker: Agent, selector: ConversableAgent):\n \"\"\"Select the next speaker.\"\"\"\n # selector.update_system_message(self.select_speaker_msg())\n # final, name = selector.generate_oai_reply(\n # self.messages\n # + [\n # {\n # \"role\": \"system\",\n # \"content\": f\"Read the above conversation. Then select the next role from {self.agent_names} to play. Only return the role.\",\n # }\n # ]\n # )\n\n final = True\n name = input(\"Who speaks next:\")\n\n if not final:\n # i = self._random.randint(0, len(self._agent_names) - 1) # randomly pick an id\n return self.next_agent(last_speaker)\n try:\n return self.agent_by_name(name)\n except ValueError:\n return self.next_agent(last_speaker)\n",
"13": "import autogen\n\nconfig_list = autogen.config_list_from_models(model_list=[\"gpt-4\"], exclude=\"aoai\")\n",
"14": "import json\nimport logging\nimport os\n\nfrom autogen import AssistantAgent, UserProxyAgent, config_list_openai_aoai\nfrom starlette.websockets import WebSocket\n\nfrom backend.app.langchain.agents import planner_agent, internet_agent, research_team\nfrom backend.app.langchain.utils.orchestrator import ConversationType, Orchestrator\n\n\nclass CoreAgent:\n def __init__(self, websocket: WebSocket):\n # Get the directory of the current script\n script_dir = os.path.dirname(os.path.realpath(__file__))\n\n specialized_agent_json_path = os.path.join(\n script_dir, '../utils/specialized_agents.json')\n\n # Build the path to agent_teams.json from the script's directory\n agent_teams_path = os.path.join(\n script_dir, '../utils/agent_teams.json')\n\n # Load the function tools\n with open(specialized_agent_json_path, 'r') as f:\n specialized_agents_json = json.load(f)\n\n # Load the function tools\n with open(agent_teams_path, 'r') as f:\n agent_teams_json = json.load(f)\n\n # Map the function names from the JSON to their respective imported functions\n specialized_agent_map = {\n \"planner_agent\": planner_agent,\n \"internet_agent\": internet_agent\n }\n\n # Map the function names from the JSON to their respective imported functions\n agent_teams_map = {\n \"research_team\": research_team,\n }\n\n # Create the agent_caller\n self.dws_agent = UserProxyAgent(\n name=\"DWS Agent\",\n max_consecutive_auto_reply=10,\n code_execution_config={\"work_dir\": \"../agent-tools\"},\n function_map=specialized_agent_map\n )\n\n # Assistant agent\n self.dws_assistant = AssistantAgent(\n name=\"DWS Core Assistant\",\n human_input_mode=\"TERMINATE\",\n llm_config={\n \"temperature\": 1,\n \"request_timeout\": 600,\n \"seed\": 42,\n \"model\": \"gpt-4-0613\",\n \"config_list\": config_list_openai_aoai(exclude=\"aoai\"),\n \"functions\": specialized_agents_json\n },\n )\n\n async def initiate_chat(self, message, websocket: WebSocket):\n # Initiate a group chat based on the Orchestrator's defined patterns\n await websocket.send_text(\"Initiating LMM Orchestrator...\")\n\n agents = [self.dws_agent, self.dws_assistant]\n orchestrator = Orchestrator(name=\"MainOrchestrator\", agents=agents)\n\n await orchestrator.start_conversation(\n pattern=ConversationType.ALL_TO_ALL,\n websocket=websocket,\n initial_message=message,\n starter_name=self.dws_agent.name,\n agent_order_names=[\n self.dws_agent.name,\n self.dws_assistant.name\n ]\n )\n",
"15": "import os\n\nfrom autogen.oai.openai_utils import config_list_from_json\n\n\nclass LlmConfiguration:\n _instance = None\n _is_initialized = False\n\n def __new__(cls, filter_llms=None):\n if not cls._instance:\n cls._instance = super(LlmConfiguration, cls).__new__(cls)\n return cls._instance\n\n def __init__(self, filter_llms=None):\n # Ensure that the initialization happens only once\n if LlmConfiguration._is_initialized:\n return\n\n file_name = \"OAI_CONFIG_LIST.json\"\n filter_dict = None\n\n # If filter_llms is provided, use it for filtering\n if filter_llms:\n filter_dict = {\"model\": filter_llms}\n\n self.config = self._find_and_load_config(file_name, filter_dict)\n LlmConfiguration._is_initialized = True\n\n def _find_and_load_config(self, file_name, filter_dict):\n # Search for the file starting from the current directory and moving to parent directories\n current_dir = os.path.abspath(os.getcwd())\n while current_dir != os.path.dirname(current_dir): # To prevent infinite loop on root dir\n file_path = os.path.join(current_dir, file_name)\n if os.path.exists(file_path):\n return config_list_from_json(env_or_file=file_name, file_location=current_dir, filter_dict=filter_dict)\n # Move to parent directory\n current_dir = os.path.dirname(current_dir)\n raise FileNotFoundError(f\"'{file_name}' not found in any parent directories.\")\n\n def __getitem__(self, key):\n return self.config[key]\n",
"16": "import uvicorn\n\n\nif __name__ == '__main__':\n uvicorn.run(\"app.application:app\", host=\"0.0.0.0\", port=8080, log_level=\"debug\", proxy_headers=True, reload=True)\n"
},
"initializer_range": 0.02,
"intermediate_size": 3072,
"label2id": {
"TERMINATION_PROMPT = \"if everything looks good, respond with APPROVED\"\n": 0,
"[\n {\n \"name\": \"planner_agent\",\n \"description\": \"This function communicates with the Planner Agent Assistant to create a structured plan for a specified task. The Planner Agent Assistant suggests coding and reasoning steps to accomplish a task but will not provide actual code. Instead, it offers a high-level approach or a set of steps to achieve the desired goal.\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"message\": {\n \"type\": \"string\",\n \"description\": \"The input to this parameter should be a clear and concise description of the task or question you want the planner to address. For example, it could be a task like 'Design a database schema for a bookstore' or a question like 'How to implement a binary search algorithm?'\"\n }\n },\n \"required\": [\n \"message\"\n ]\n }\n },\n {\n \"name\": \"internet_agent\",\n \"description\": \"This function facilitates interaction with the Internet Agent Assistant, which is designed to browse the web and extract relevant information based on provided instructions or queries. It is useful for tasks where real-time data fetching from the internet or an external source is required.\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"message\": {\n \"type\": \"string\",\n \"description\": \"This parameter should contain clear instructions or queries that you want the internet agent to perform or address. For instance, you could provide instructions like 'Find the latest research on neural network architectures' or queries like 'What is the capital of Finland?'\"\n }\n },\n \"required\": [\n \"message\"\n ]\n }\n },\n {\n \"name\": \"retriever_agent\",\n \"description\": \"This function interfaces with the Retriever Agent Assistant to fetch information from the provided documents. The Retriever Agent Assistant searches the specified document collection and returns information relevant to the provided query, ensuring the results are concise and pertinent.\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"message\": {\n \"type\": \"string\",\n \"description\": \"The task or question you want the retriever to address from the provided documents. For instance, 'Find information about the solar system from the science textbook' or 'Extract details about quantum mechanics from the physics notes.'\"\n },\n \"docs_path\": {\n \"type\": \"string\",\n \"description\": \"Path to the directory containing the documents from which the information is to be retrieved.\"\n },\n \"collection_name\": {\n \"type\": \"string\",\n \"description\": \"Name of the collection in the database where the retriever will look for the documents. This helps in segregating data for different tasks or users.\"\n }\n },\n \"required\": [\n \"message\",\n \"docs_path\",\n \"collection_name\"\n ]\n }\n }\n]": 1,
"[\n {\n \"name\": \"research_team\",\n \"description\": \"The research_team function activates a sophisticated multi-agent conversation system designed for academic and technical research purposes. It comprises a diverse set of roles, including an Engineer who provides code, a Scientist capable of understanding and discussing academic papers, a Planner who suggests research plans, an Executor to run the code, and a Critic to ensure the quality of the entire discussion and output. By initializing this team, you're unlocking a collaborative digital research environment to dissect, investigate, and discuss a given topic.\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"message\": {\n \"type\": \"string\",\n \"description\": \"The content of this parameter initiates the research journey. It should be a detailed directive, possibly highlighting the papers, topics, or research questions you want the team to tackle. Examples include: 'Discuss the latest findings in quantum computing from reputable journals' or 'Investigate and analyze the paper titled \\\"Quantum Entanglement in Neural Networks\\\"'. The more precise your message, the better tailored the team's response will be.\"\n }\n },\n \"required\": [\n \"message\"\n ]\n }\n }\n]": 2,
"from autogen import AssistantAgent, UserProxyAgent\n\nfrom backend.app.langchain.lmms_config import LlmConfiguration\n\n\ndef internet_agent(message: str):\n # Instantiate the LlmConfiguration with filtering\n llm_filters = [\n \"gpt-4-32k\",\n \"gpt-35-turbo-16k\",\n \"gpt4\",\n \"gpt-4-0314\",\n \"gpt-4-0613\",\n \"gpt-4-32k-0314\",\n \"gpt-4-32k-v0314\"\n ]\n config_list_instance = LlmConfiguration(filter_llms=llm_filters)\n\n llm_config = {\n \"request_timeout\": 600,\n \"seed\": 42,\n \"config_list\": config_list_instance.config, # Accessing the 'config' attribute of our instance\n \"temperature\": 0,\n }\n\n # Construct agents\n internet_agent_assistant = AssistantAgent(\n name=\"Internet_Agent_Assistant \",\n llm_config=llm_config,\n system_message='''\n Internet_Agent_Assistant. \n You are here to support the Internet_Agent. \n Respond to queries and provide relevant information as per the task. \n Follow the directives set by Internet_Agent. \n Do not terminate a task on your own. \n Wait for instructions from Internet_Agent.\n '''\n )\n\n internet_agent = UserProxyAgent(\n name=\"Internet_Agent\",\n human_input_mode=\"TERMINATE\",\n max_consecutive_auto_reply=10,\n is_termination_msg=lambda x: x.get(\n \"content\", \"\").rstrip().endswith(\"TERMINATE\"),\n code_execution_config={\"work_dir\": \"../agent-tools/\"},\n llm_config=llm_config,\n system_message='''Internet_Agent.\n You must use a function to search the internet, if the function doesn't exist in the tools dir then create one, otherwise use the available tools\n You are the primary interface between the user and the assistant. \n Direct the Internet_Agent_Assistant to accomplish tasks.\n Only terminate the task when you're fully satisfied or if the user indicates so. \n If not satisfied, provide a clear reason for the dissatisfaction or reply CONTINUE to keep the task ongoing. \n Ensure the user is aware they can reply TERMINATE if the task has been solved to full satisfaction.\n '''\n )\n\n # Start a conversation\n internet_agent.initiate_chat(\n internet_agent_assistant,\n message=message\n )\n": 3,
"from autogen import AssistantAgent, UserProxyAgent\n\nfrom backend.app.langchain.lmms_config import LlmConfiguration\n\n\ndef planner_agent(message: str):\n # Configuration initialization\n config_list_instance = LlmConfiguration()\n\n llm_config = {\n \"request_timeout\": 600,\n \"seed\": 42,\n \"config_list\": config_list_instance.config,\n \"temperature\": 0,\n }\n\n # Create a planner AssistantAgent and UserProxyAgent instances\n planner_agent_assistant = AssistantAgent(\n name=\"Planner_Agent_Assistant\",\n llm_config=llm_config,\n system_message='''Planner_Agent_Assistant.\n You suggest coding and reasoning steps for the Planner_Agent. \n Do not suggest concrete code. \n For any action beyond writing code or reasoning, convert it to a step which can be implemented by writing code. \n For example, the action of browsing the web can be implemented by writing code which reads and prints the content of a web page. \n Inspect the execution result. If the plan is not good, suggest a better plan. \n If the execution is wrong, analyze the error and suggest a fix.\n Do not terminate a task on your own. \n Wait for instructions from Planner_Agent.\n '''\n )\n\n planner_agent = UserProxyAgent(\n name=\"Planner_Agent\",\n human_input_mode=\"TERMINATE\",\n max_consecutive_auto_reply=10,\n is_termination_msg=lambda x: x.get(\n \"content\", \"\").rstrip().endswith(\"TERMINATE\"),\n code_execution_config={\"work_dir\": \"../agent-tools\"},\n llm_config=llm_config,\n system_message='''\n Planner_Agent.\n You are the primary interface between the user and the assistant. \n Direct the Planner_Agent_Assistant to accomplish tasks.\n Only terminate the task when you're fully satisfied or if the user indicates so. \n If not satisfied, provide a clear reason for the dissatisfaction or reply CONTINUE to keep the task ongoing. \n Ensure the user is aware they can reply TERMINATE if the task has been solved to full satisfaction.\n '''\n )\n\n # Initiate a chat with the assistant using the provided message\n planner_agent.initiate_chat(\n planner_agent_assistant,\n message=message,\n )\n": 4,
"from autogen import AssistantAgent, UserProxyAgent, GroupChat, GroupChatManager\n\nfrom backend.app.langchain.lmms_config import LlmConfiguration\n\n\ndef research_team(message: str):\n \"\"\"\n Initiate a multi-agent chat to research and discuss the given message or task.\n :param message: The task or question for the research team.\n :return: None\n \"\"\"\n config_list_instance = LlmConfiguration()\n\n gpt4_config = {\n \"seed\": 42, # Change the seed for different trials\n \"temperature\": 0,\n \"config_list\": config_list_instance.config,\n \"request_timeout\": 120,\n }\n\n # Agent setup\n user_proxy = UserProxyAgent(\n name=\"Admin\",\n system_message=''' \n Admin. \n The central authority in the research group. \n Your role is to interact with the planner, scrutinizing and endorsing plans. \n You hold the power to greenlight the implementation of the strategy. \n Your approval is vital before any plan execution.\n ''',\n code_execution_config=False,\n )\n\n engineer = AssistantAgent(\n name=\"Engineer\",\n llm_config=gpt4_config,\n system_message='''Engineer. \n You are the coding specialist in this research team. \n Always operate within the boundaries of an approved plan. \n Your primary task is to develop python/shell scripts that fulfill the objectives of the given task. \n Adherence to coding standards is imperative. \n Do not create incomplete codes or those that need external amendments.\n ''',\n )\n\n scientist = AssistantAgent(\n name=\"Scientist\",\n llm_config=gpt4_config,\n system_message='''\n Scientist. \n Your expertise lies in deciphering and leveraging the knowledge from academic papers. \n While you strictly adhere to the approved plan, you do not indulge in coding. \n Your primary contribution is recommending how the revelations in papers can be practically implemented or beneficial to the task at hand.\n ''',\n )\n\n planner = AssistantAgent(\n name=\"Planner\",\n system_message='''\n Planner. \n You are the strategist of the team, formulating plans that leverage the skills of both the engineer and scientist. \n Your plans should be precise, segregating tasks based on roles. \n It's vital to adapt, refining your strategies based on feedback, until the admin provides a stamp of approval.\n ''',\n llm_config=gpt4_config,\n )\n\n executor = UserProxyAgent(\n name=\"Executor\",\n system_message='''\n Executor.\n As the name suggests, you bring plans to life by running the code crafted by the engineer. \n It's crucial that you promptly report back with the outcomes, ensuring the engineer is abreast of the results to make any necessary adjustments.\n ''',\n human_input_mode=\"NEVER\",\n code_execution_config={\"last_n_messages\": 3, \"work_dir\": \"research\"},\n )\n\n critic = AssistantAgent(\n name=\"Critic\",\n system_message='''\n Critic. \n Your sharp analytical skills are crucial for the team. \n Your duty is to meticulously review plans, verify claims, and scrutinize codes. \n Always provide constructive feedback and ensure that every strategy has valid, traceable references such as URLs to ensure the team is grounded in verifiable information.\n ''',\n llm_config=gpt4_config,\n )\n\n # Create a group chat with all agents\n groupchat = GroupChat(agents=[user_proxy, engineer, scientist,\n planner, executor, critic], messages=[], max_round=50)\n manager = GroupChatManager(groupchat=groupchat, llm_config=gpt4_config)\n\n # Initiate a chat with the manager (which controls all agents)\n user_proxy.initiate_chat(manager, message=message)\n": 5,
"from autogen.agentchat.contrib.retrieve_assistant_agent import RetrieveAssistantAgent\nfrom autogen.agentchat.contrib.retrieve_user_proxy_agent import RetrieveUserProxyAgent\nfrom autogen.retrieve_utils import TEXT_FORMATS\n\nfrom backend.app.langchain.lmms_config import LlmConfiguration\n\n\ndef retriever_agent(message: str, docs_path: str, collection_name: str):\n \"\"\"\n Communicate with the Retriever Agent Assistant to fetch information from provided documents.\n :param message: Task or question for the retriever.\n :param docs_path: Path to the directory containing documents.\n :param collection_name: Name of the collection for the retriever.\n :return: None\n \"\"\"\n # Setup configurations for the agent.\n config_list_instance = LlmConfiguration()\n\n assert len(config_list_instance.config) > 0\n print(\"Accepted file formats for `docs_path`:\")\n print(TEXT_FORMATS)\n\n # Initialize the Retriever Assistant Agent.\n retriever_assistant = RetrieveAssistantAgent(\n name=\"Retriever_Assistant\",\n system_message='''You are designed to extract information from provided documents.\n When given a task or query, search the specified document collection and return the relevant details.\n Ensure the returned information is concise and pertinent to the query.\n ''',\n llm_config={\n \"request_timeout\": 3600,\n \"seed\": 42,\n \"config_list\": config_list_instance.config,\n },\n )\n\n # Initialize the UserProxyAgent for the retriever.\n retriever_user_proxy = RetrieveUserProxyAgent(\n name=\"Retriever_User_Proxy\",\n human_input_mode=\"TERMINATE\",\n max_consecutive_auto_reply=10,\n retrieve_config={\n \"task\": \"code\",\n \"docs_path\": docs_path,\n \"chunk_token_size\": 2000,\n \"model\": config_list_instance.config[0][\"model\"],\n \"collection_name\": collection_name,\n \"client\": chromadb.PersistentClient(path=\"/tmp/chromadb\"),\n \"embedding_model\": \"all-mpnet-base-v2\",\n \"get_or_create\": True,\n },\n system_message='''You are the primary interface between the user and the Retriever_Assistant. \n Direct the Retriever_Assistant to accomplish tasks.\n Only terminate the task when you're fully satisfied or if the user indicates so. \n If not satisfied, provide a clear reason for the dissatisfaction or reply CONTINUE to keep the task ongoing. \n Ensure the user is aware they can reply TERMINATE if the task has been solved to full satisfaction.\n '''\n )\n\n # Initiate a chat with the Retriever Assistant using the provided message.\n retriever_user_proxy.initiate_chat(\n retriever_assistant,\n message=message\n )\n": 6,
"from enum import Enum, auto\nfrom typing import List, Optional\n\nimport autogen\nfrom starlette.websockets import WebSocket\n\n\nclass ConversationType(Enum):\n \"\"\"\n Enum representing the various types of conversation patterns.\n\n - BROADCAST: A single agent sends a message to all other agents.\n - HIERARCHICAL: A hierarchical flow of communication, typically from a single sender to multiple receivers.\n - REQUEST_RESPOND: One agent sends a message and awaits a response from another agent.\n - TWO_WAY: A continuous back-and-forth conversation between two agents until a termination condition is met.\n - ROUND_ROBIN: Each agent takes turns communicating in a circular manner.\n - GROUP_BASED: A specified group of agents communicate in a particular order.\n - PROXY_BASED: One agent communicates on behalf of another agent.\n - STAR_NETWORK: A central agent communicates with all other agents.\n - ALL_TO_ALL: Every agent communicates with every other agent.\n \"\"\"\n\n BROADCAST = auto()\n HIERARCHICAL = auto()\n REQUEST_RESPOND = auto()\n TWO_WAY = auto()\n ROUND_ROBIN = auto()\n GROUP_BASED = auto()\n PROXY_BASED = auto()\n STAR_NETWORK = auto()\n ALL_TO_ALL = auto()\n\n\nclass Orchestrator:\n \"\"\"\n A class to manage and facilitate various types of communication between conversable agents.\n\n Attributes:\n - name (str): The name of the orchestrator.\n - agents (List[autogen.ConversableAgent]): List of agents managed by the orchestrator.\n - messages (List[dict]): List of messages exchanged during conversations. Each message is a dictionary with a 'role' (sender/agent name) and 'content' (message content).\n - complete_keyword (str): Keyword signaling the completion of a conversation. Default is \"APPROVED\".\n - error_keyword (str): Keyword signaling an error in a conversation. Default is \"ERROR\".\n\n Raises:\n - Exception: If the orchestrator is initialized with fewer than two agents.\n \"\"\"\n\n def __init__(self, name: str, agents: List[autogen.ConversableAgent]):\n \"\"\"\n Initialize the Orchestrator with a name and a list of agents.\n\n Parameters:\n - name (str): The name of the orchestrator.\n - agents (List[autogen.ConversableAgent]): List of agents to be managed.\n \"\"\"\n self.name = name\n self.agents = agents\n self.messages = []\n self.complete_keyword = \"APPROVED\"\n self.error_keyword = \"ERROR\"\n if len(self.agents) < 2:\n raise Exception(\"Orchestrator needs at least two agents\")\n\n @property\n def total_agents(self) -> int:\n \"\"\"\n Return the total number of agents managed by the orchestrator.\n\n Returns:\n - int: Total number of agents.\n \"\"\"\n return len(self.agents)\n\n @property\n def latest_message(self) -> Optional[dict]:\n \"\"\"\n Retrieve the most recent message exchanged in conversations.\n\n Returns:\n - dict or None: The latest message if present, else None. Message is a dictionary with a 'role' and 'content'.\n \"\"\"\n if not self.messages:\n return None\n return self.messages[-1] if isinstance(self.messages[-1], dict) else {\"role\": \"unknown\",\n \"content\": self.messages[-1]}\n\n def add_message(self, message: dict):\n \"\"\"\n Add a new message to the list of messages.\n\n Parameters:\n - message (dict): The message to add, containing a 'role' and 'content'.\n \"\"\"\n self.messages.append(message)\n\n async def basic_chat(self, agent_a: autogen.ConversableAgent, agent_b: autogen.ConversableAgent, message: str, websocket: WebSocket) -> dict:\n \"\"\"\n Conduct a basic chat interaction between two agents. The process involves:\n 1. `agent_a` sending a message to `agent_b`.\n 2. `agent_b` generating and returning a reply.\n 3. Storing the reply in the Orchestrator's messages list.\n\n Parameters:\n - agent_a (autogen.ConversableAgent): The sender agent who initiates the chat.\n - agent_b (autogen.ConversableAgent): The receiver agent who responds to the chat.\n - message (str): The message content to be sent from agent_a to agent_b.\n\n Returns:\n - dict: The reply from agent_b, structured as {\"role\": agent's name, \"content\": reply message}.\n \"\"\"\n\n # Step 1: agent_a sends a message to agent_b.\n # The message is structured as a dictionary with content and the role (name) of the sender.\n agent_a.send({\"content\": message, \"role\": agent_a.name}, agent_b)\n\n # Step 2: agent_b generates a reply based on the message from agent_a.\n reply_content = agent_b.generate_reply(sender=agent_a)\n\n # Check the format of the reply. If it's a string, structure it as a dictionary.\n reply = {\"role\": agent_b.name, \"content\": reply_content} if isinstance(\n reply_content, str) else reply_content\n\n # Step 3: Add the reply to the Orchestrator's message list.\n self.add_message(reply)\n return reply\n\n async def all_to_all_communication(self, initial_message: str, websocket: WebSocket):\n \"\"\"\n Handles the all-to-all communication pattern.\n\n In this communication type, every agent communicates with every other agent.\n This means that if there are N agents, there will be N*(N-1) total communications.\n\n Parameters:\n - initial_message (str): The initial message to be passed among the agents.\n\n Usage example:\n ```\n orchestrator = Orchestrator(name=\"MainOrchestrator\", agents=agents)\n orchestrator.start_conversation(\n pattern=ConversationType.ALL_TO_ALL,\n initial_message=message,\n starter_name=\"AgentName\", # Not used for ALL_TO_ALL but can be provided\n agent_order_names=[\"Agent1\", \"Agent2\"] # Not used for ALL_TO_ALL but can be provided\n )\n ```\n \"\"\"\n message = initial_message\n for sender in self.agents:\n for receiver in self.agents:\n if sender != receiver:\n reply = await self.basic_chat(sender, receiver, message, websocket)\n if reply and isinstance(reply, dict) and \"content\" in reply:\n await websocket.send_text(reply[\"content\"])\n message = reply[\"content\"]\n\n\n def star_network(self, central_agent: autogen.ConversableAgent, initial_message: str):\n \"\"\"\n Handles the star network communication pattern.\n\n In this pattern, one agent (the central agent) communicates with all other agents.\n The central agent serves as a hub or central point of contact.\n\n Parameters:\n - central_agent (autogen.ConversableAgent): The central agent that communicates with all others.\n - initial_message (str): The initial message to be passed from the central agent.\n\n \"\"\"\n message = initial_message\n for agent in self.agents:\n if agent != central_agent:\n reply = self.basic_chat(central_agent, agent, message)\n message = reply[\"content\"]\n\n def proxy_based_communication(self, proxy: autogen.ConversableAgent, target: autogen.ConversableAgent,\n message: str):\n \"\"\"\n Handles the proxy-based communication pattern.\n\n In this pattern, a proxy agent communicates with a target agent on behalf of another agent.\n\n Parameters:\n - proxy (autogen.ConversableAgent): The proxy agent that sends the message.\n - target (autogen.ConversableAgent): The target agent that receives the message.\n - message (str): The content of the message to be sent.\n\n \"\"\"\n # Proxy sends the message on behalf of another agent\n reply = self.basic_chat(proxy, target, message)\n return reply\n\n def group_based_communication(self, starter: autogen.ConversableAgent, initial_message: str,\n agent_order: Optional[List[autogen.ConversableAgent]] = None):\n \"\"\"\n Handles the group-based communication pattern.\n\n In this pattern, a starter agent communicates with other agents based on a specified order.\n If no specific order is provided, all agents are communicated with in their default order.\n\n Parameters:\n - starter (autogen.ConversableAgent): The agent initiating the communication.\n - initial_message (str): The initial message to be passed from the starter agent.\n - agent_order (Optional[List[autogen.ConversableAgent]]): An ordered list of agents for the communication. If not provided, default agent order is used.\n\n Usage:\n # Assuming the orchestrator and agents have been initialized\n orchestrator.group_based_communication(starter_agent, \"Hello\", [agent2, agent3, agent1])\n \"\"\"\n if agent_order is None:\n agent_order = self.agents.copy() # Use all agents in the default order\n message = initial_message\n for agent in agent_order:\n if agent != starter:\n reply = self.basic_chat(starter, agent, message)\n message = reply[\"content\"]\n\n def two_way_communication(self, agent_a: autogen.ConversableAgent, agent_b: autogen.ConversableAgent, message: str):\n \"\"\"\n Handles the two-way communication pattern.\n\n In this pattern, two agents converse back and forth until a termination condition,\n represented by the `complete_keyword`, is encountered in a message.\n\n Parameters:\n - agent_a (autogen.ConversableAgent): The first agent involved in the conversation.\n - agent_b (autogen.ConversableAgent): The second agent involved in the conversation.\n - message (str): The initial message to start the conversation.\n\n Usage:\n # Assuming the orchestrator and agents have been initialized\n orchestrator.two_way_communication(agent1, agent2, \"Initial message\")\n \"\"\"\n while True: # Continue until a termination condition or keyword is found\n reply = self.basic_chat(agent_a, agent_b, message)\n if self.complete_keyword in reply[\"content\"]:\n break\n agent_a, agent_b = agent_b, agent_a # Swap roles\n message = reply[\"content\"]\n\n def request_and_respond(self, sender: autogen.ConversableAgent, receiver: autogen.ConversableAgent, message: str):\n \"\"\"\n Handles the request and respond communication pattern.\n\n In this simple pattern, one agent sends a message, and the other agent responds.\n\n Parameters:\n - sender (autogen.ConversableAgent): The agent sending the initial request.\n - receiver (autogen.ConversableAgent): The agent that responds to the request.\n - message (str): The content of the message or request to be sent.\n\n Usage:\n # Assuming the orchestrator and agents have been initialized\n orchestrator.request_and_respond(agent1, agent2, \"Request message\")\n \"\"\"\n return self.basic_chat(sender, receiver, message)\n\n def hierarchical_communication(self, sender: autogen.ConversableAgent, receivers: List[autogen.ConversableAgent],\n message: str):\n \"\"\"\n Handles the hierarchical communication pattern.\n\n In this pattern, a sender communicates with a list of receivers in order.\n The communication halts when one of the receivers provides a reply.\n\n Parameters:\n - sender (autogen.ConversableAgent): The agent initiating the communication.\n - receivers (List[autogen.ConversableAgent]): List of agents that the sender communicates with.\n - message (str): The initial message sent by the sender.\n\n Usage:\n # Assuming the orchestrator and agents have been initialized\n orchestrator.hierarchical_communication(agent1, [agent2, agent3, agent4], \"Hello\")\n \"\"\"\n for receiver in receivers:\n reply = self.basic_chat(sender, receiver, message)\n if reply:\n break\n\n def broadcast(self, sender: autogen.ConversableAgent, message: str):\n \"\"\"\n Handles the broadcast communication pattern.\n\n In this pattern, a sender communicates the same message to all other agents.\n\n Parameters:\n - sender (autogen.ConversableAgent): The agent that broadcasts the message.\n - message (str): The content of the message to be broadcasted.\n\n Usage:\n # Assuming the orchestrator and agents have been initialized\n orchestrator.broadcast(agent1, \"Broadcast message\")\n \"\"\"\n for agent in self.agents:\n if agent != sender:\n self.basic_chat(sender, agent, message)\n\n def round_robin(self, initial_message: str):\n \"\"\"\n Handles the round robin communication pattern.\n\n In this pattern, agents communicate in a sequential order, passing messages in a\n circular fashion. The first agent starts the conversation and then passes it to\n the next agent until the last agent communicates with the first one.\n\n Parameters:\n - initial_message (str): The message to start the round robin communication.\n\n Usage:\n # Assuming the orchestrator and agents have been initialized\n orchestrator.round_robin(\"Starting message for round robin\")\n \"\"\"\n message = initial_message\n for agent in self.agents:\n reply = self.basic_chat(self.agents[0], agent, message)\n message = reply[\"content\"]\n\n def group_based_communication(self, starter: autogen.ConversableAgent, initial_message: str,\n agent_order: Optional[List[autogen.ConversableAgent]] = None):\n \"\"\"\n Handles the group-based communication pattern.\n\n Here, a starting agent communicates with a group of agents based on a specified\n or default order.\n\n Parameters:\n - starter (autogen.ConversableAgent): The agent initiating the group communication.\n - initial_message (str): The initial message to begin the group communication.\n - agent_order (Optional[List[autogen.ConversableAgent]]): Order in which agents communicate.\n If not provided, the default order in the orchestrator's agent list is used.\n\n Usage:\n # Assuming the orchestrator and agents have been initialized\n orchestrator.group_based_communication(starting_agent, \"Initial message for group chat\", [agent2, agent3])\n \"\"\"\n if agent_order is None:\n agent_order = self.agents.copy()\n message = initial_message\n for agent in agent_order:\n if agent != starter:\n reply = self.basic_chat(starter, agent, message)\n message = reply[\"content\"]\n\n def proxy_based_communication(self, proxy: autogen.ConversableAgent, target: autogen.ConversableAgent,\n message: str):\n \"\"\"\n Handles the proxy-based communication pattern.\n\n In this pattern, a proxy agent sends a message on behalf of another agent to the target.\n\n Parameters:\n - proxy (autogen.ConversableAgent): The agent acting as a proxy.\n - target (autogen.ConversableAgent): The agent receiving the message from the proxy.\n - message (str): The content of the message being relayed by the proxy.\n\n Usage:\n # Assuming the orchestrator and agents have been initialized\n orchestrator.proxy_based_communication(proxy_agent, target_agent, \"Message through proxy\")\n \"\"\"\n return self.basic_chat(proxy, target, message)\n\n def star_network(self, central_agent: autogen.ConversableAgent, initial_message: str):\n \"\"\"\n Handles the star network communication pattern.\n\n In this pattern, a central agent communicates with all other agents. Each agent\n sends/receives messages only through this central agent.\n\n Parameters:\n - central_agent (autogen.ConversableAgent): The central agent that communicates with all other agents.\n - initial_message (str): The initial message used to start the communication.\n\n Usage:\n # Assuming the orchestrator and agents have been initialized\n orchestrator.star_network(central_hub_agent, \"Message from central agent\")\n \"\"\"\n message = initial_message\n for agent in self.agents:\n if agent != central_agent:\n reply = self.basic_chat(central_agent, agent, message)\n message = reply[\"content\"]\n\n def get_agent_by_name(self, name: str) -> Optional[autogen.ConversableAgent]:\n \"\"\"\n Retrieve an agent based on its name.\n\n Parameters:\n - name (str): The name of the agent to retrieve.\n\n Returns:\n - autogen.ConversableAgent or None: The agent object if found, else None.\n\n Usage:\n # Assuming the orchestrator and agents have been initialized\n agent = orchestrator.get_agent_by_name(\"AgentName\")\n \"\"\"\n for agent in self.agents:\n if agent.name == name:\n return agent\n return None\n\n async def start_conversation(self, pattern: ConversationType, websocket: WebSocket, initial_message: str, **kwargs):\n \"\"\"\n Initiates a conversation based on a specified communication pattern.\n\n Parameters:\n - pattern (ConversationType): The type of communication pattern to use.\n - initial_message (str): The initial message to start the conversation.\n - **kwargs: Additional keyword arguments depending on the communication pattern.\n For instance, `sender_name` or `agent_a_name` depending on the chosen pattern.\n\n Raises:\n - ValueError: If an unknown communication pattern is provided.\n\n Usage:\n # Assuming the orchestrator and agents have been initialized\n orchestrator.start_conversation(\n pattern=ConversationType.ALL_TO_ALL,\n initial_message=\"Initial message for all-to-all communication\"\n )\n \"\"\"\n\n \"\"\"Initiates a conversation based on the specified pattern.\"\"\"\n if pattern == ConversationType.BROADCAST:\n sender_name = kwargs.get(\"sender_name\")\n sender = self.get_agent_by_name(sender_name)\n self.broadcast(sender, initial_message)\n\n elif pattern == ConversationType.HIERARCHICAL:\n sender_name = kwargs.get(\"sender_name\")\n sender = self.get_agent_by_name(sender_name)\n receivers_names = kwargs.get(\"receivers_names\")\n receivers = [self.get_agent_by_name(\n name) for name in receivers_names]\n self.hierarchical_communication(sender, receivers, initial_message)\n\n elif pattern == ConversationType.REQUEST_RESPOND:\n sender_name = kwargs.get(\"sender_name\")\n receiver_name = kwargs.get(\"receiver_name\")\n sender = self.get_agent_by_name(sender_name)\n receiver = self.get_agent_by_name(receiver_name)\n self.request_and_respond(sender, receiver, initial_message)\n\n elif pattern == ConversationType.TWO_WAY:\n agent_a_name = kwargs.get(\"agent_a_name\")\n agent_b_name = kwargs.get(\"agent_b_name\")\n agent_a = self.get_agent_by_name(agent_a_name)\n agent_b = self.get_agent_by_name(agent_b_name)\n self.two_way_communication(agent_a, agent_b, initial_message)\n\n elif pattern == ConversationType.ROUND_ROBIN:\n self.round_robin(initial_message)\n\n elif pattern == ConversationType.GROUP_BASED:\n starter_name = kwargs.get(\"starter_name\")\n agent_order_names = kwargs.get(\"agent_order_names\", [])\n starter = self.get_agent_by_name(starter_name)\n agent_order = [self.get_agent_by_name(\n name) for name in agent_order_names]\n self.group_based_communication(\n starter, initial_message, agent_order)\n\n elif pattern == ConversationType.PROXY_BASED:\n proxy_name = kwargs.get(\"proxy_name\")\n target_name = kwargs.get(\"target_name\")\n proxy = self.get_agent_by_name(proxy_name)\n target = self.get_agent_by_name(target_name)\n await self.proxy_based_communication(proxy, target, initial_message)\n\n elif pattern == ConversationType.STAR_NETWORK:\n central_agent_name = kwargs.get(\"central_agent_name\")\n central_agent = self.get_agent_by_name(central_agent_name)\n self.star_network(central_agent, initial_message)\n\n elif pattern == ConversationType.ALL_TO_ALL:\n await self.all_to_all_communication(initial_message, websocket)\n\n else:\n raise ValueError(f\"Unknown communication pattern: {pattern}\")\n": 7,
"from fastapi import FastAPI\nfrom starlette.staticfiles import StaticFiles\n\nfrom backend.app.routers import index_public, user_proxy_socket\n\napp = FastAPI()\n\ntemplates = StaticFiles(directory=\"../frontend/html/\")\napp.mount(\"/static\", StaticFiles(directory=\"../frontend/static\"), name=\"static\")\n\n\nrouters = [\n index_public.router,\n user_proxy_socket.router,\n]\n# include routers to fastapi\nfor router in routers:\n app.include_router(router)\n\n": 8,
"from fastapi import WebSocket, APIRouter, WebSocketDisconnect\nfrom starlette.templating import Jinja2Templates\n\nfrom backend.app.langchain.agents.core_agents import CoreAgent\n\nrouter = APIRouter()\ntemplates = Jinja2Templates(directory=\"../frontend/html/\")\n\n@router.websocket(\"/ws\")\nasync def websocket_endpoint(websocket: WebSocket):\n await websocket.accept() # accept the connection\n try:\n while True:\n data = await websocket.receive_text()\n words = data.split(\" \")\n\n if words[0] == \"!test\":\n final: str = \"\"\n for word in words:\n if word == \"!test\":\n continue\n final += word + \" \"\n await websocket.send_text(\"Running Tests... | Query: \" + final)\n agent = CoreAgent(websocket)\n await agent.initiate_chat(final, websocket)\n\n\n\n\n else:\n await websocket.send_text(f\"You wrote: {data}\")\n\n except WebSocketDisconnect:\n print(\"WebSocket Disconnected!\")\n": 9,
"from langchain.tools import BaseTool\n\n\nclass StatusCheckTool(BaseTool):\n name = \"StatusCheck\"\n description = \"Check the status of our company sites.\"\n\n def _run(self):\n return \"yes\"\n": 10,
"from typing import Dict, Any\n\nimport fastapi\n\nfrom fastapi import APIRouter\nfrom fastapi.templating import Jinja2Templates\nfrom starlette.requests import Request\n\nrouter = APIRouter()\ntemplates = Jinja2Templates(directory=\"../frontend/html/\")\n\n\n@router.get('/robots.txt')\ndef robots():\n data = \"\"\"\n User-agent: *\n Disallow: /\n \"\"\"\n return fastapi.Response(content=data, media_type='text/plain')\n\n\n@router.get(\"/\")\nasync def index(request: Request):\n result: Dict[str, Any] = {\"request\": request}\n\n return templates.TemplateResponse(\"index_public.html\", result)\n\n": 11,
"from typing import Dict, List, Optional, Union\n\nfrom autogen import Agent\nfrom autogen import ConversableAgent\nfrom autogen import GroupChatManager, GroupChat\n\n\n# make the selector which selects the speaker the Judge every time\nclass ManualManager(GroupChatManager):\n def run_andy_chat(\n self,\n messages: Optional[List[Dict]] = None,\n sender: Optional[Agent] = None,\n config: Optional[GroupChat] = None,\n ) -> Union[str, Dict, None]:\n \"\"\"Run a group chat.\"\"\"\n if messages is None:\n messages = self._oai_messages[sender]\n message = messages[-1]\n speaker = sender\n groupchat = config\n for i in range(groupchat.max_round):\n # set the name to speaker's name if the role is not function\n if message[\"role\"] != \"function\":\n message[\"name\"] = speaker.name\n groupchat.messages.append(message)\n # broadcast the message to all agents except the speaker\n for agent in groupchat.agents:\n if agent != speaker:\n self.send(message, agent, request_reply=False, silent=True)\n if i == groupchat.max_round - 1:\n # the last round\n break\n try:\n # select the next speaker\n speaker = groupchat.select_speaker(\n speaker, self, groupchat.agent_by_name(\"Manager\"))\n # let the speaker speak\n reply = speaker.generate_reply(sender=self)\n except KeyboardInterrupt:\n # let the admin agent speak if interrupted\n if groupchat.admin_name in groupchat.agent_names:\n # admin agent is one of the participants\n speaker = groupchat.agent_by_name(groupchat.admin_name)\n reply = speaker.generate_reply(sender=self)\n else:\n # admin agent is not found in the participants\n raise\n if reply is None:\n break\n # The speaker sends the message without requesting a reply\n speaker.send(reply, self, request_reply=False)\n message = self.last_message(speaker)\n return True, None\n\n\n# Make the select_speaker call handle Andy the Judge making the call opposed to an openAI call\nclass ManualGroupChat(GroupChat):\n def select_speaker(self, last_speaker: Agent, selector: ConversableAgent):\n \"\"\"Select the next speaker.\"\"\"\n # selector.update_system_message(self.select_speaker_msg())\n # final, name = selector.generate_oai_reply(\n # self.messages\n # + [\n # {\n # \"role\": \"system\",\n # \"content\": f\"Read the above conversation. Then select the next role from {self.agent_names} to play. Only return the role.\",\n # }\n # ]\n # )\n\n final = True\n name = input(\"Who speaks next:\")\n\n if not final:\n # i = self._random.randint(0, len(self._agent_names) - 1) # randomly pick an id\n return self.next_agent(last_speaker)\n try:\n return self.agent_by_name(name)\n except ValueError:\n return self.next_agent(last_speaker)\n": 12,
"import autogen\n\nconfig_list = autogen.config_list_from_models(model_list=[\"gpt-4\"], exclude=\"aoai\")\n": 13,
"import json\nimport logging\nimport os\n\nfrom autogen import AssistantAgent, UserProxyAgent, config_list_openai_aoai\nfrom starlette.websockets import WebSocket\n\nfrom backend.app.langchain.agents import planner_agent, internet_agent, research_team\nfrom backend.app.langchain.utils.orchestrator import ConversationType, Orchestrator\n\n\nclass CoreAgent:\n def __init__(self, websocket: WebSocket):\n # Get the directory of the current script\n script_dir = os.path.dirname(os.path.realpath(__file__))\n\n specialized_agent_json_path = os.path.join(\n script_dir, '../utils/specialized_agents.json')\n\n # Build the path to agent_teams.json from the script's directory\n agent_teams_path = os.path.join(\n script_dir, '../utils/agent_teams.json')\n\n # Load the function tools\n with open(specialized_agent_json_path, 'r') as f:\n specialized_agents_json = json.load(f)\n\n # Load the function tools\n with open(agent_teams_path, 'r') as f:\n agent_teams_json = json.load(f)\n\n # Map the function names from the JSON to their respective imported functions\n specialized_agent_map = {\n \"planner_agent\": planner_agent,\n \"internet_agent\": internet_agent\n }\n\n # Map the function names from the JSON to their respective imported functions\n agent_teams_map = {\n \"research_team\": research_team,\n }\n\n # Create the agent_caller\n self.dws_agent = UserProxyAgent(\n name=\"DWS Agent\",\n max_consecutive_auto_reply=10,\n code_execution_config={\"work_dir\": \"../agent-tools\"},\n function_map=specialized_agent_map\n )\n\n # Assistant agent\n self.dws_assistant = AssistantAgent(\n name=\"DWS Core Assistant\",\n human_input_mode=\"TERMINATE\",\n llm_config={\n \"temperature\": 1,\n \"request_timeout\": 600,\n \"seed\": 42,\n \"model\": \"gpt-4-0613\",\n \"config_list\": config_list_openai_aoai(exclude=\"aoai\"),\n \"functions\": specialized_agents_json\n },\n )\n\n async def initiate_chat(self, message, websocket: WebSocket):\n # Initiate a group chat based on the Orchestrator's defined patterns\n await websocket.send_text(\"Initiating LMM Orchestrator...\")\n\n agents = [self.dws_agent, self.dws_assistant]\n orchestrator = Orchestrator(name=\"MainOrchestrator\", agents=agents)\n\n await orchestrator.start_conversation(\n pattern=ConversationType.ALL_TO_ALL,\n websocket=websocket,\n initial_message=message,\n starter_name=self.dws_agent.name,\n agent_order_names=[\n self.dws_agent.name,\n self.dws_assistant.name\n ]\n )\n": 14,
"import os\n\nfrom autogen.oai.openai_utils import config_list_from_json\n\n\nclass LlmConfiguration:\n _instance = None\n _is_initialized = False\n\n def __new__(cls, filter_llms=None):\n if not cls._instance:\n cls._instance = super(LlmConfiguration, cls).__new__(cls)\n return cls._instance\n\n def __init__(self, filter_llms=None):\n # Ensure that the initialization happens only once\n if LlmConfiguration._is_initialized:\n return\n\n file_name = \"OAI_CONFIG_LIST.json\"\n filter_dict = None\n\n # If filter_llms is provided, use it for filtering\n if filter_llms:\n filter_dict = {\"model\": filter_llms}\n\n self.config = self._find_and_load_config(file_name, filter_dict)\n LlmConfiguration._is_initialized = True\n\n def _find_and_load_config(self, file_name, filter_dict):\n # Search for the file starting from the current directory and moving to parent directories\n current_dir = os.path.abspath(os.getcwd())\n while current_dir != os.path.dirname(current_dir): # To prevent infinite loop on root dir\n file_path = os.path.join(current_dir, file_name)\n if os.path.exists(file_path):\n return config_list_from_json(env_or_file=file_name, file_location=current_dir, filter_dict=filter_dict)\n # Move to parent directory\n current_dir = os.path.dirname(current_dir)\n raise FileNotFoundError(f\"'{file_name}' not found in any parent directories.\")\n\n def __getitem__(self, key):\n return self.config[key]\n": 15,
"import uvicorn\n\n\nif __name__ == '__main__':\n uvicorn.run(\"app.application:app\", host=\"0.0.0.0\", port=8080, log_level=\"debug\", proxy_headers=True, reload=True)\n": 16
},
"layer_norm_eps": 1e-07,
"max_length": 64,
"max_position_embeddings": 512,
"max_relative_positions": -1,
"model_type": "deberta",
"num_attention_heads": 12,
"num_hidden_layers": 12,
"pad_token_id": 0,
"padding": "max_length",
"pooler_dropout": 0,
"pooler_hidden_act": "gelu",
"pooler_hidden_size": 768,
"pos_att_type": [
"c2p",
"p2c"
],
"position_biased_input": false,
"relative_attention": true,
"torch_dtype": "float32",
"transformers_version": "4.29.2",
"type_vocab_size": 0,
"vocab_size": 50265
}