From e6a428961473bc9a25ba18c893175a227486c449 Mon Sep 17 00:00:00 2001 From: zhhhhhhhy <1301195487@qq.com> Date: Wed, 9 Jul 2025 15:33:35 +0800 Subject: [PATCH 01/14] Add autogen.py --- mas_arena/agents/autogen.py | 129 ++++++++++++++++++++++++++++++++++++ 1 file changed, 129 insertions(+) create mode 100644 mas_arena/agents/autogen.py diff --git a/mas_arena/agents/autogen.py b/mas_arena/agents/autogen.py new file mode 100644 index 0000000..6e4cfb6 --- /dev/null +++ b/mas_arena/agents/autogen.py @@ -0,0 +1,129 @@ +import os +from typing import Dict, Any, List +import contextlib +# from openai import OpenAI +from openai import AsyncOpenAI +from dotenv import load_dotenv +from mas_arena.agents.base import AgentSystem, AgentSystemRegistry + +# Load environment variables +load_dotenv() + +class AutoGen(AgentSystem): + """ + AutoGen System + + This agent system implements a collaborative AutoGen framework similar to AutoGen, + where AutoGen agents with distinct roles interact to solve problems through conversation. + """ + def __init__(self, name: str = "autogen", config: Dict[str, Any] = None): + """Initialize the AutoGen System""" + super().__init__(name, config) + self.config = config or {} + + # Default model and agent configurations + self.model_name = self.config.get("model_name") or os.getenv("MODEL_NAME", "qwen-plus") + self.system_prompt = self.config.get("system_prompt", "") + self.format_prompt + + # Initialize OpenAI client + # self.client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"), base_url=os.getenv("OPENAI_API_BASE")) + self.client = AsyncOpenAI(api_key=os.getenv("OPENAI_API_KEY"), base_url=os.getenv("OPENAI_API_BASE")) + # Define AutoGen agents with distinct roles + self.agents = self.config.get("agents", [ + { + "name": "planner", + "role": "Creates a step-by-step plan to solve the problem.", + "system_prompt": "You are a Planner Agent. Your role is to analyze the problem and create a clear, step-by-step plan to solve it. Provide concise instructions for other agents to follow." + }, + { + "name": "executor", + "role": "Executes the plan and provides the final solution.", + "system_prompt": "You are an Executor Agent. Your role is to follow the plan provided by the Planner Agent and produce a detailed solution to the problem." + }, + { + "name": "reviewer", + "role": "Reviews the solution and suggests improvements.", + "system_prompt": "You are a Reviewer Agent. Your role is to evaluate the solution provided by the Executor Agent, identify any issues, and suggest improvements or confirm the solution is correct." + } + ]) + + # Maximum number of conversation rounds to prevent infinite loops + self.max_rounds = self.config.get("max_rounds", 5) + + async def run_agent(self, problem: Dict[str, Any], **kwargs) -> Dict[str, Any]: + """ + Run the AutoGen system on a given problem. + + Agents collaborate in a conversational loop, with each agent contributing based on its role. + + Args: + problem: Dictionary containing the problem data + + Returns: + Dictionary of run results including messages with usage metadata + """ + problem_text = problem["problem"] + messages = [ + {"role": "system", "content": self.system_prompt}, + {"role": "user", "content": f"Problem: {problem_text}"} + ] + conversation_history = messages.copy() + all_messages = [] + + # Conversation loop + for round_num in range(self.max_rounds): + for agent in self.agents: + agent_name = agent["name"] + agent_prompt = agent["system_prompt"] + + # Prepare messages for the current agent, including conversation history + agent_messages = [ + {"role": "system", "content": agent_prompt}, + *conversation_history + ] + + # Get response from the current agent + response = await self.client.chat.completions.create( + model=self.model_name, + messages=agent_messages + ) + + # Extract and clean response content + response_content = response.choices[0].message.content + response_content = response_content.replace('\r\n', '\n').replace('\r', '\n').strip() + with contextlib.suppress(UnicodeDecodeError): + response_content = response_content.encode('utf-8').decode('utf-8-sig') + + # Create message object with usage metadata + ai_message = { + 'content': response_content, + 'name': agent_name, + 'role': 'assistant', + 'message_type': 'ai_response', + 'usage_metadata': response.usage + } + + # Add to conversation history and all messages + conversation_history.append({"role": "assistant", "content": response_content, "name": agent_name}) + all_messages.append(ai_message) + + # Check if the reviewer has approved the solution (simplified termination condition) + if agent_name == "reviewer" and "Solution approved" in response_content.lower(): + return { + "messages": all_messages, + "final_answer": all_messages[-2]["content"] # Executor's solution + } + + # If max rounds reached, return the last executor's solution + final_answer = next( + (msg["content"] for msg in reversed(all_messages) if msg["name"] == "executor"), + "No solution found within maximum rounds." + ) + + return { + "messages": all_messages, + "final_answer": final_answer + } + +# Register the agent system +AgentSystemRegistry.register("autogen", AutoGen) \ No newline at end of file From 2f87542f55c08f1f6057eb78b53913d6e8964f52 Mon Sep 17 00:00:00 2001 From: zhhhhhhhy <1301195487@qq.com> Date: Tue, 15 Jul 2025 17:52:13 +0800 Subject: [PATCH 02/14] Modify the code of autogen #12 --- mas_arena/agents/autogen.py | 81 ++++++++++++------------------------- 1 file changed, 26 insertions(+), 55 deletions(-) diff --git a/mas_arena/agents/autogen.py b/mas_arena/agents/autogen.py index 6e4cfb6..f189906 100644 --- a/mas_arena/agents/autogen.py +++ b/mas_arena/agents/autogen.py @@ -6,16 +6,12 @@ from dotenv import load_dotenv from mas_arena.agents.base import AgentSystem, AgentSystemRegistry -# Load environment variables + load_dotenv() + class AutoGen(AgentSystem): - """ - AutoGen System - This agent system implements a collaborative AutoGen framework similar to AutoGen, - where AutoGen agents with distinct roles interact to solve problems through conversation. - """ def __init__(self, name: str = "autogen", config: Dict[str, Any] = None): """Initialize the AutoGen System""" super().__init__(name, config) @@ -23,78 +19,53 @@ def __init__(self, name: str = "autogen", config: Dict[str, Any] = None): # Default model and agent configurations self.model_name = self.config.get("model_name") or os.getenv("MODEL_NAME", "qwen-plus") - self.system_prompt = self.config.get("system_prompt", "") + self.format_prompt + + self.num_rounds = self.config.get("num_rounds", 5) - # Initialize OpenAI client - # self.client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"), base_url=os.getenv("OPENAI_API_BASE")) + # Initialize OpenAI client + """This implementation is not compatible with the tool usage. Please check the .extending.md""" self.client = AsyncOpenAI(api_key=os.getenv("OPENAI_API_KEY"), base_url=os.getenv("OPENAI_API_BASE")) # Define AutoGen agents with distinct roles - self.agents = self.config.get("agents", [ - { - "name": "planner", - "role": "Creates a step-by-step plan to solve the problem.", - "system_prompt": "You are a Planner Agent. Your role is to analyze the problem and create a clear, step-by-step plan to solve it. Provide concise instructions for other agents to follow." - }, + + self.agents = [ { - "name": "executor", - "role": "Executes the plan and provides the final solution.", - "system_prompt": "You are an Executor Agent. Your role is to follow the plan provided by the Planner Agent and produce a detailed solution to the problem." + "name": "primary", + "system_prompt": "You are a helpful AI assistant, skilled at generating creative and accurate content." }, { - "name": "reviewer", - "role": "Reviews the solution and suggests improvements.", - "system_prompt": "You are a Reviewer Agent. Your role is to evaluate the solution provided by the Executor Agent, identify any issues, and suggest improvements or confirm the solution is correct." - } - ]) - - # Maximum number of conversation rounds to prevent infinite loops - self.max_rounds = self.config.get("max_rounds", 5) + "name": "critic", + "system_prompt": "Provide constructive feedback on the content provided. Respond with 'APPROVE' when the content meets high standards or your feedback has been addressed." + } + ] async def run_agent(self, problem: Dict[str, Any], **kwargs) -> Dict[str, Any]: - """ - Run the AutoGen system on a given problem. - - Agents collaborate in a conversational loop, with each agent contributing based on its role. - Args: - problem: Dictionary containing the problem data - - Returns: - Dictionary of run results including messages with usage metadata - """ problem_text = problem["problem"] messages = [ - {"role": "system", "content": self.system_prompt}, {"role": "user", "content": f"Problem: {problem_text}"} ] conversation_history = messages.copy() + all_messages = [] + final_answer = "" - # Conversation loop - for round_num in range(self.max_rounds): - for agent in self.agents: + for _ in range(self.num_rounds): + for n, agent in enumerate(self.agents): agent_name = agent["name"] agent_prompt = agent["system_prompt"] - # Prepare messages for the current agent, including conversation history agent_messages = [ {"role": "system", "content": agent_prompt}, *conversation_history ] - # Get response from the current agent response = await self.client.chat.completions.create( model=self.model_name, messages=agent_messages ) - - # Extract and clean response content + response_content = response.choices[0].message.content - response_content = response_content.replace('\r\n', '\n').replace('\r', '\n').strip() - with contextlib.suppress(UnicodeDecodeError): - response_content = response_content.encode('utf-8').decode('utf-8-sig') - # Create message object with usage metadata ai_message = { 'content': response_content, 'name': agent_name, @@ -103,20 +74,21 @@ async def run_agent(self, problem: Dict[str, Any], **kwargs) -> Dict[str, Any]: 'usage_metadata': response.usage } - # Add to conversation history and all messages conversation_history.append({"role": "assistant", "content": response_content, "name": agent_name}) + + if(agent_name == "primary"): + final_answer = ai_message["content"] all_messages.append(ai_message) - # Check if the reviewer has approved the solution (simplified termination condition) - if agent_name == "reviewer" and "Solution approved" in response_content.lower(): + if agent_name == "critic" and "approve" in response_content.lower(): return { "messages": all_messages, - "final_answer": all_messages[-2]["content"] # Executor's solution + "final_answer": final_answer } - # If max rounds reached, return the last executor's solution + final_answer = next( - (msg["content"] for msg in reversed(all_messages) if msg["name"] == "executor"), + (msg["content"] for msg in reversed(all_messages) if msg["name"] == "primary"), "No solution found within maximum rounds." ) @@ -125,5 +97,4 @@ async def run_agent(self, problem: Dict[str, Any], **kwargs) -> Dict[str, Any]: "final_answer": final_answer } -# Register the agent system AgentSystemRegistry.register("autogen", AutoGen) \ No newline at end of file From d649092624636d5ebe1d4a42c6149ed108c13a6a Mon Sep 17 00:00:00 2001 From: zhhhhhhhy <1301195487@qq.com> Date: Tue, 15 Jul 2025 18:06:33 +0800 Subject: [PATCH 03/14] modify autogen.py #12 --- mas_arena/agents/autogen.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mas_arena/agents/autogen.py b/mas_arena/agents/autogen.py index f189906..a93ba8d 100644 --- a/mas_arena/agents/autogen.py +++ b/mas_arena/agents/autogen.py @@ -37,7 +37,7 @@ def __init__(self, name: str = "autogen", config: Dict[str, Any] = None): "system_prompt": "Provide constructive feedback on the content provided. Respond with 'APPROVE' when the content meets high standards or your feedback has been addressed." } ] - + async def run_agent(self, problem: Dict[str, Any], **kwargs) -> Dict[str, Any]: problem_text = problem["problem"] From 43872e824f80be23dd5e2ab8199b3183d2a8070a Mon Sep 17 00:00:00 2001 From: zhhhhhhhy <1301195487@qq.com> Date: Tue, 15 Jul 2025 20:07:41 +0800 Subject: [PATCH 04/14] add autogen.py #12 --- mas_arena/agents/autogen.py | 100 ++++++++++++++++++++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100644 mas_arena/agents/autogen.py diff --git a/mas_arena/agents/autogen.py b/mas_arena/agents/autogen.py new file mode 100644 index 0000000..a93ba8d --- /dev/null +++ b/mas_arena/agents/autogen.py @@ -0,0 +1,100 @@ +import os +from typing import Dict, Any, List +import contextlib +# from openai import OpenAI +from openai import AsyncOpenAI +from dotenv import load_dotenv +from mas_arena.agents.base import AgentSystem, AgentSystemRegistry + + +load_dotenv() + + +class AutoGen(AgentSystem): + + def __init__(self, name: str = "autogen", config: Dict[str, Any] = None): + """Initialize the AutoGen System""" + super().__init__(name, config) + self.config = config or {} + + # Default model and agent configurations + self.model_name = self.config.get("model_name") or os.getenv("MODEL_NAME", "qwen-plus") + + self.num_rounds = self.config.get("num_rounds", 5) + + # Initialize OpenAI client + """This implementation is not compatible with the tool usage. Please check the .extending.md""" + self.client = AsyncOpenAI(api_key=os.getenv("OPENAI_API_KEY"), base_url=os.getenv("OPENAI_API_BASE")) + # Define AutoGen agents with distinct roles + + self.agents = [ + { + "name": "primary", + "system_prompt": "You are a helpful AI assistant, skilled at generating creative and accurate content." + }, + { + "name": "critic", + "system_prompt": "Provide constructive feedback on the content provided. Respond with 'APPROVE' when the content meets high standards or your feedback has been addressed." + } + ] + + async def run_agent(self, problem: Dict[str, Any], **kwargs) -> Dict[str, Any]: + + problem_text = problem["problem"] + messages = [ + {"role": "user", "content": f"Problem: {problem_text}"} + ] + conversation_history = messages.copy() + + all_messages = [] + final_answer = "" + + for _ in range(self.num_rounds): + for n, agent in enumerate(self.agents): + agent_name = agent["name"] + agent_prompt = agent["system_prompt"] + + agent_messages = [ + {"role": "system", "content": agent_prompt}, + *conversation_history + ] + + response = await self.client.chat.completions.create( + model=self.model_name, + messages=agent_messages + ) + + response_content = response.choices[0].message.content + + ai_message = { + 'content': response_content, + 'name': agent_name, + 'role': 'assistant', + 'message_type': 'ai_response', + 'usage_metadata': response.usage + } + + conversation_history.append({"role": "assistant", "content": response_content, "name": agent_name}) + + if(agent_name == "primary"): + final_answer = ai_message["content"] + all_messages.append(ai_message) + + if agent_name == "critic" and "approve" in response_content.lower(): + return { + "messages": all_messages, + "final_answer": final_answer + } + + + final_answer = next( + (msg["content"] for msg in reversed(all_messages) if msg["name"] == "primary"), + "No solution found within maximum rounds." + ) + + return { + "messages": all_messages, + "final_answer": final_answer + } + +AgentSystemRegistry.register("autogen", AutoGen) \ No newline at end of file From 74895fc82c5d5965dcf5b95831a74afaa9c151bf Mon Sep 17 00:00:00 2001 From: zhhhhhhhy <1301195487@qq.com> Date: Tue, 15 Jul 2025 20:24:56 +0800 Subject: [PATCH 05/14] Revert "add autogen.py #12" This reverts commit 43872e824f80be23dd5e2ab8199b3183d2a8070a. --- mas_arena/agents/autogen.py | 100 ------------------------------------ 1 file changed, 100 deletions(-) delete mode 100644 mas_arena/agents/autogen.py diff --git a/mas_arena/agents/autogen.py b/mas_arena/agents/autogen.py deleted file mode 100644 index a93ba8d..0000000 --- a/mas_arena/agents/autogen.py +++ /dev/null @@ -1,100 +0,0 @@ -import os -from typing import Dict, Any, List -import contextlib -# from openai import OpenAI -from openai import AsyncOpenAI -from dotenv import load_dotenv -from mas_arena.agents.base import AgentSystem, AgentSystemRegistry - - -load_dotenv() - - -class AutoGen(AgentSystem): - - def __init__(self, name: str = "autogen", config: Dict[str, Any] = None): - """Initialize the AutoGen System""" - super().__init__(name, config) - self.config = config or {} - - # Default model and agent configurations - self.model_name = self.config.get("model_name") or os.getenv("MODEL_NAME", "qwen-plus") - - self.num_rounds = self.config.get("num_rounds", 5) - - # Initialize OpenAI client - """This implementation is not compatible with the tool usage. Please check the .extending.md""" - self.client = AsyncOpenAI(api_key=os.getenv("OPENAI_API_KEY"), base_url=os.getenv("OPENAI_API_BASE")) - # Define AutoGen agents with distinct roles - - self.agents = [ - { - "name": "primary", - "system_prompt": "You are a helpful AI assistant, skilled at generating creative and accurate content." - }, - { - "name": "critic", - "system_prompt": "Provide constructive feedback on the content provided. Respond with 'APPROVE' when the content meets high standards or your feedback has been addressed." - } - ] - - async def run_agent(self, problem: Dict[str, Any], **kwargs) -> Dict[str, Any]: - - problem_text = problem["problem"] - messages = [ - {"role": "user", "content": f"Problem: {problem_text}"} - ] - conversation_history = messages.copy() - - all_messages = [] - final_answer = "" - - for _ in range(self.num_rounds): - for n, agent in enumerate(self.agents): - agent_name = agent["name"] - agent_prompt = agent["system_prompt"] - - agent_messages = [ - {"role": "system", "content": agent_prompt}, - *conversation_history - ] - - response = await self.client.chat.completions.create( - model=self.model_name, - messages=agent_messages - ) - - response_content = response.choices[0].message.content - - ai_message = { - 'content': response_content, - 'name': agent_name, - 'role': 'assistant', - 'message_type': 'ai_response', - 'usage_metadata': response.usage - } - - conversation_history.append({"role": "assistant", "content": response_content, "name": agent_name}) - - if(agent_name == "primary"): - final_answer = ai_message["content"] - all_messages.append(ai_message) - - if agent_name == "critic" and "approve" in response_content.lower(): - return { - "messages": all_messages, - "final_answer": final_answer - } - - - final_answer = next( - (msg["content"] for msg in reversed(all_messages) if msg["name"] == "primary"), - "No solution found within maximum rounds." - ) - - return { - "messages": all_messages, - "final_answer": final_answer - } - -AgentSystemRegistry.register("autogen", AutoGen) \ No newline at end of file From 7ad4b6251ce52937404c9844afc7cc1584a51f5d Mon Sep 17 00:00:00 2001 From: zhhhhhhhy <1301195487@qq.com> Date: Tue, 15 Jul 2025 20:56:18 +0800 Subject: [PATCH 06/14] modify autogen.py #12 --- mas_arena/agents/autogen.py | 100 ++++++++++++++++++++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100644 mas_arena/agents/autogen.py diff --git a/mas_arena/agents/autogen.py b/mas_arena/agents/autogen.py new file mode 100644 index 0000000..a93ba8d --- /dev/null +++ b/mas_arena/agents/autogen.py @@ -0,0 +1,100 @@ +import os +from typing import Dict, Any, List +import contextlib +# from openai import OpenAI +from openai import AsyncOpenAI +from dotenv import load_dotenv +from mas_arena.agents.base import AgentSystem, AgentSystemRegistry + + +load_dotenv() + + +class AutoGen(AgentSystem): + + def __init__(self, name: str = "autogen", config: Dict[str, Any] = None): + """Initialize the AutoGen System""" + super().__init__(name, config) + self.config = config or {} + + # Default model and agent configurations + self.model_name = self.config.get("model_name") or os.getenv("MODEL_NAME", "qwen-plus") + + self.num_rounds = self.config.get("num_rounds", 5) + + # Initialize OpenAI client + """This implementation is not compatible with the tool usage. Please check the .extending.md""" + self.client = AsyncOpenAI(api_key=os.getenv("OPENAI_API_KEY"), base_url=os.getenv("OPENAI_API_BASE")) + # Define AutoGen agents with distinct roles + + self.agents = [ + { + "name": "primary", + "system_prompt": "You are a helpful AI assistant, skilled at generating creative and accurate content." + }, + { + "name": "critic", + "system_prompt": "Provide constructive feedback on the content provided. Respond with 'APPROVE' when the content meets high standards or your feedback has been addressed." + } + ] + + async def run_agent(self, problem: Dict[str, Any], **kwargs) -> Dict[str, Any]: + + problem_text = problem["problem"] + messages = [ + {"role": "user", "content": f"Problem: {problem_text}"} + ] + conversation_history = messages.copy() + + all_messages = [] + final_answer = "" + + for _ in range(self.num_rounds): + for n, agent in enumerate(self.agents): + agent_name = agent["name"] + agent_prompt = agent["system_prompt"] + + agent_messages = [ + {"role": "system", "content": agent_prompt}, + *conversation_history + ] + + response = await self.client.chat.completions.create( + model=self.model_name, + messages=agent_messages + ) + + response_content = response.choices[0].message.content + + ai_message = { + 'content': response_content, + 'name': agent_name, + 'role': 'assistant', + 'message_type': 'ai_response', + 'usage_metadata': response.usage + } + + conversation_history.append({"role": "assistant", "content": response_content, "name": agent_name}) + + if(agent_name == "primary"): + final_answer = ai_message["content"] + all_messages.append(ai_message) + + if agent_name == "critic" and "approve" in response_content.lower(): + return { + "messages": all_messages, + "final_answer": final_answer + } + + + final_answer = next( + (msg["content"] for msg in reversed(all_messages) if msg["name"] == "primary"), + "No solution found within maximum rounds." + ) + + return { + "messages": all_messages, + "final_answer": final_answer + } + +AgentSystemRegistry.register("autogen", AutoGen) \ No newline at end of file From d1495ff31472d729f3d07200b7abdcded702428c Mon Sep 17 00:00:00 2001 From: zhhhhhhhy <1301195487@qq.com> Date: Tue, 15 Jul 2025 21:26:39 +0800 Subject: [PATCH 07/14] modify autogen.py(#12) --- mas_arena/agents/autogen.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mas_arena/agents/autogen.py b/mas_arena/agents/autogen.py index a93ba8d..f6890aa 100644 --- a/mas_arena/agents/autogen.py +++ b/mas_arena/agents/autogen.py @@ -9,7 +9,7 @@ load_dotenv() - + class AutoGen(AgentSystem): def __init__(self, name: str = "autogen", config: Dict[str, Any] = None): From 2a25acd9e6fc2f89128376d0bf13da130fa08ca7 Mon Sep 17 00:00:00 2001 From: zhhhhhhhy <1301195487@qq.com> Date: Wed, 23 Jul 2025 20:27:13 +0800 Subject: [PATCH 08/14] modify autogen.py --- mas_arena/agents/autogen.py | 21 +++++++-------------- 1 file changed, 7 insertions(+), 14 deletions(-) diff --git a/mas_arena/agents/autogen.py b/mas_arena/agents/autogen.py index a93ba8d..ac0961a 100644 --- a/mas_arena/agents/autogen.py +++ b/mas_arena/agents/autogen.py @@ -1,7 +1,6 @@ import os from typing import Dict, Any, List import contextlib -# from openai import OpenAI from openai import AsyncOpenAI from dotenv import load_dotenv from mas_arena.agents.base import AgentSystem, AgentSystemRegistry @@ -17,20 +16,16 @@ def __init__(self, name: str = "autogen", config: Dict[str, Any] = None): super().__init__(name, config) self.config = config or {} - # Default model and agent configurations self.model_name = self.config.get("model_name") or os.getenv("MODEL_NAME", "qwen-plus") self.num_rounds = self.config.get("num_rounds", 5) - # Initialize OpenAI client - """This implementation is not compatible with the tool usage. Please check the .extending.md""" self.client = AsyncOpenAI(api_key=os.getenv("OPENAI_API_KEY"), base_url=os.getenv("OPENAI_API_BASE")) - # Define AutoGen agents with distinct roles - + self.agents = [ { "name": "primary", - "system_prompt": "You are a helpful AI assistant, skilled at generating creative and accurate content." + "system_prompt": """You are a helpful AI assistant, skilled at generating creative and accurate content.""" }, { "name": "critic", @@ -78,20 +73,18 @@ async def run_agent(self, problem: Dict[str, Any], **kwargs) -> Dict[str, Any]: if(agent_name == "primary"): final_answer = ai_message["content"] - all_messages.append(ai_message) + if agent_name == "critic" and "approve" in response_content.lower(): + print(all_messages) + print("------------") + print(final_answer) return { "messages": all_messages, "final_answer": final_answer } - + all_messages.append(ai_message) - final_answer = next( - (msg["content"] for msg in reversed(all_messages) if msg["name"] == "primary"), - "No solution found within maximum rounds." - ) - return { "messages": all_messages, "final_answer": final_answer From 7d244ddf970265086a773f867e34993b55198d2a Mon Sep 17 00:00:00 2001 From: zhhhhhhhy <1301195487@qq.com> Date: Wed, 23 Jul 2025 21:46:25 +0800 Subject: [PATCH 09/14] test --- autogen_autogen.py | 68 +++++++++++++ mas_arena/agents/autogen_autogen.py | 122 +++++++++++++++++++++++ mas_arena/agents/autogen_to_autogen.py | 124 +++++++++++++++++++++++ mas_arena/agents/camel.py | 131 +++++++++++++++++++++++++ 4 files changed, 445 insertions(+) create mode 100644 autogen_autogen.py create mode 100644 mas_arena/agents/autogen_autogen.py create mode 100644 mas_arena/agents/autogen_to_autogen.py create mode 100644 mas_arena/agents/camel.py diff --git a/autogen_autogen.py b/autogen_autogen.py new file mode 100644 index 0000000..e322b62 --- /dev/null +++ b/autogen_autogen.py @@ -0,0 +1,68 @@ +import asyncio +from autogen_agentchat.agents import AssistantAgent +from autogen_ext.models.openai import OpenAIChatCompletionClient +import os +from dotenv import load_dotenv +from autogen_agentchat.teams import RoundRobinGroupChat +from autogen_agentchat.conditions import TextMentionTermination + +load_dotenv() + +api_key = "sk-3WoJwFaztEeXC3gdkzxwc4c3RKwcpVjtwsJs6YmKzfDuMG6j" +base_url="https://zjuapi.com/v1" + +def termination_condition(messages): + if messages: + last_message = messages[-1].content if hasattr(messages[-1], 'content') else str(messages[-1]) + return "APPROVE" in last_message.upper() + return False +def convert_to_ai_message(self,messages): + allmessage = [] + for msg in messages: + ai_message = { + 'content': msg.content, # 使用点号访问属性 + 'name': msg.source, # 使用点号访问属性 + 'role': 'assistant', + 'message_type': 'ai_response', + 'usage_metadata': msg.models_usage # 使用点号访问属性 + } + allmessage.append(ai_message) + return allmessage + +async def main() -> None: + model_client = OpenAIChatCompletionClient(model="gpt-4o",api_key=api_key,base_url=base_url) + primary = AssistantAgent( + name="primary", + model_client=model_client, + system_message="You are a helpful AI assistant, skilled at generating creative and accurate content." + ) + + critic = AssistantAgent( + name="critic", + model_client=model_client, + system_message="Provide constructive feedback on the content provided. Respond with 'APPROVE' when the content meets high standards or your feedback has been addressed." + ) + # system_message="Provide constructive feedback on the content provided. Respond with 'APPROVE' when the content meets high standards or your feedback has been addressed." + + group_chat = RoundRobinGroupChat( + participants=[primary, critic], + termination_condition=TextMentionTermination(text="APPROVE"), + max_turns=3 + ) + + question = "什么是人工智能?" + + result = await group_chat.run(task=question) + allmessage = convert_to_ai_message(result.messages) + primary_messages = [] + + for msg in allmessage: + if msg['name'] == 'primary': + primary_messages.append(msg) + + + final_answer = primary_messages[-1]['content'] + print("final_answer:",final_answer) + await model_client.close() + +asyncio.run(main()) diff --git a/mas_arena/agents/autogen_autogen.py b/mas_arena/agents/autogen_autogen.py new file mode 100644 index 0000000..c343755 --- /dev/null +++ b/mas_arena/agents/autogen_autogen.py @@ -0,0 +1,122 @@ +import asyncio +from typing import Dict, Any, List + +from autogen_agentchat.agents import AssistantAgent +from autogen_ext.models.openai import OpenAIChatCompletionClient +from openai.types.completion_usage import CompletionUsage,CompletionTokensDetails,PromptTokensDetails +import os +from dotenv import load_dotenv +from autogen_agentchat.teams import RoundRobinGroupChat +from autogen_agentchat.conditions import TextMentionTermination +from mas_arena.agents.base import AgentSystem, AgentSystemRegistry + +load_dotenv() + + +class DDD(AgentSystem): + def __init__(self, name: str = "ddd", config: Dict[str, Any] = None): + """Initialize the AutoGen System""" + super().__init__(name, config) + self.config = config or {} + + # Default model and agent configurations + self.model_name = self.config.get("model_name") or os.getenv("MODEL_NAME", "qwen-plus") + + self.max_turns = self.config.get("max_turns", 10) + + + def convert_to_ai_message(self,messages): + allmessage = [] + for msg in messages: + # 构造 usage_metadata 使用 CompletionUsage 类 + usage_metadata = None + if msg.models_usage: + completion_tokens_details = CompletionTokensDetails( + accepted_prediction_tokens=0, + audio_tokens=0, + reasoning_tokens=0, + rejected_prediction_tokens=0 + ) + prompt_tokens_details = PromptTokensDetails( + audio_tokens=0, + cached_tokens=0 + ) + usage_metadata = CompletionUsage( + completion_tokens=msg.models_usage.completion_tokens, + prompt_tokens=msg.models_usage.prompt_tokens, + total_tokens=msg.models_usage.prompt_tokens + msg.models_usage.completion_tokens, + completion_tokens_details=completion_tokens_details, + prompt_tokens_details=prompt_tokens_details + ) + + ai_message = { + 'content': msg.content, + 'name': msg.source, + 'role': 'assistant', + 'message_type': 'ai_response', + 'usage_metadata': usage_metadata + } + allmessage.append(ai_message) + return allmessage + async def run_agent(self, problem: Dict[str, Any], **kwargs) -> Dict[str, Any]: + + problem_text = problem["problem"] + # Initialize OpenAI client + api_key=os.getenv("OPENAI_API_KEY") + base_url=os.getenv("OPENAI_API_BASE") + self.model_client = OpenAIChatCompletionClient(model=self.model_name,api_key=api_key,base_url=base_url) + + self.primary = AssistantAgent( + name="primary", + model_client=self.model_client, + system_message=""" +- Ensure the final answer is a single line with no extra whitespace or formatting. +- Match the answer format to the problem type, such as: + - Boolean problems: 'True' or 'False' + - date_understanding: '(A)', '(B)', '(C)', etc. + - Multiple-choice problems: '(A)', '(B)', '(C)', etc. + - Sequence completion problems: A sequence of closing brackets like `)`, `]`, `}`, or `>` + - Word sorting problems: Space-separated words in alphabetical order + - Causal judgment or web of lies problems: 'Yes' or 'No' + - Sports understanding problems: 'Yes' or 'No' + - Formal fallacies: 'valid' or 'invalid' + + +[Your final answer here] + +""" + ) + + self.critic = AssistantAgent( + name="critic", + model_client=self.model_client, + system_message="Provide constructive feedback on the content provided. Respond with 'APPROVE' when the content meets high standards or your feedback has been addressed." + ) + + self.group_chat = RoundRobinGroupChat( + participants=[self.primary, self.critic], + termination_condition=TextMentionTermination(text="APPROVE"), + max_turns=self.max_turns + ) + + result = await self.group_chat.run(task=problem_text) + + all_messages = self.convert_to_ai_message(result.messages) + + primary_messages = [] + + for msg in all_messages: + if msg['name'] == 'primary': + primary_messages.append(msg) + final_answer = primary_messages[-1]['content'] + + if("APPROVE" in all_messages[-1]["content"] ): + all_messages = all_messages[:-1] + + await self.model_client.close() + return { + "messages": all_messages, + "final_answer": final_answer + } + +AgentSystemRegistry.register("ddd", DDD) \ No newline at end of file diff --git a/mas_arena/agents/autogen_to_autogen.py b/mas_arena/agents/autogen_to_autogen.py new file mode 100644 index 0000000..b763912 --- /dev/null +++ b/mas_arena/agents/autogen_to_autogen.py @@ -0,0 +1,124 @@ + +import os +from typing import Dict, Any, List +from dotenv import load_dotenv +from autogen import AssistantAgent, UserProxyAgent +from mas_arena.agents.base import AgentSystem, AgentSystemRegistry + +load_dotenv() + +class Demo(AgentSystem): + def __init__(self, name: str = "demo", config: Dict[str, Any] = None): + """Initialize the AutoGen System""" + super().__init__(name, config) + self.config = config or {} + + # Default model and agent configurations + self.model_name = self.config.get("model_name") or os.getenv("MODEL_NAME", "gpt-4o") + self.num_rounds = self.config.get("num_rounds", 5) + + # LLM configuration + llm_config = { + "config_list": [{ + "model": self.model_name, + "api_key": os.getenv("OPENAI_API_KEY"), + "base_url": os.getenv("OPENAI_API_BASE") + }] + } + + # Define AutoGen agents with distinct roles + self.agents = [ + { + "name": "primary", + "agent": AssistantAgent( + name="primary", + system_message="You are a helpful AI assistant, skilled at generating creative and accurate content.", + llm_config=llm_config + ) + }, + { + "name": "critic", + "agent": AssistantAgent( + name="critic", + system_message="Provide constructive feedback on the content provided. Respond with 'APPROVE' when the content meets high standards or your feedback has been addressed.", + llm_config=llm_config + ) + } + ] + + # User proxy to initiate the chat + self.user_proxy = UserProxyAgent( + name="user_proxy", + code_execution_config=False + ) + + async def run_agent(self, problem: Dict[str, Any], **kwargs) -> Dict[str, Any]: + problem_text = problem["problem"] + messages = [ + {"role": "user", "content": f"Problem: {problem_text}"} + ] + conversation_history = messages.copy() + all_messages = [] + final_answer = "" + + + for _ in range(self.num_rounds): + for agent_info in self.agents: + agent_name = agent_info["name"] + agent = agent_info["agent"] + + # Prepare messages for the current agent + agent_messages = [ + {"role": "system", "content": agent.system_message}, + *conversation_history + ] + + # Initiate chat with the current agent + chat_result = await self.user_proxy.initiate_chat( + recipient=agent, + message=agent_messages[-1]["content"], # Use the latest message content + max_turns=1, + clear_history=True + ) + + # Process chat results + for message in chat_result.chat_history: + if message.get("role") == "assistant": + response_content = message.get("content", "") + ai_message = { + 'content': response_content, + 'name': agent_name, + 'role': 'assistant', + 'message_type': 'ai_response', + 'usage_metadata': getattr(chat_result, 'usage', None) + } + conversation_history.append({ + "role": "assistant", + "content": response_content, + "name": agent_name + }) + all_messages.append(ai_message) + + if agent_name == "primary": + final_answer = response_content + + # Check for critic approval + if agent_name == "critic" and "approve" in response_content.lower(): + print("Messages:", all_messages) + print("Final Answer:", final_answer) + return { + "messages": all_messages, + "final_answer": final_answer + } + + + + print("Messages:", all_messages) + print("Final Answer:", final_answer) + return { + "messages": all_messages, + "final_answer": final_answer + } + +AgentSystemRegistry.register("demo", Demo) + diff --git a/mas_arena/agents/camel.py b/mas_arena/agents/camel.py new file mode 100644 index 0000000..225c637 --- /dev/null +++ b/mas_arena/agents/camel.py @@ -0,0 +1,131 @@ +import os +from typing import Dict, Any, List +import contextlib +# from openai import OpenAI +from openai import AsyncOpenAI +from dotenv import load_dotenv +from mas_arena.agents.base import AgentSystem, AgentSystemRegistry + + +load_dotenv() + + +class AAA(AgentSystem): + + def __init__(self, name: str = "aaa", config: Dict[str, Any] = None): + super().__init__(name, config) + self.config = config or {} + + self.model_name = self.config.get("model_name") or os.getenv("MODEL_NAME", "qwen-plus") + + self.client = AsyncOpenAI(api_key=os.getenv("OPENAI_API_KEY"), base_url=os.getenv("OPENAI_API_BASE")) +# You are a helpful AI assistant, skilled at generating creative and accurate content. + self.agents = [ + { + "name": "TaskSpecifier", + "system_prompt": """You are a task specification agent. Based on the following problem description, specify a clear, specific, and executable task,""" + }, + { + "name": "TaskPlanner", + "system_prompt": "You are a task planning agent. Create a detailed sub-task plan for the following task. List specific steps." + }, + { + "name": "Assistant", + "system_prompt": "You are an Assistant, assisting the User to complete tasks. Your goal is to provide accurate and clear responses." + }, + { + "name": "User", + "system_prompt": "You are the User, collaborating with the Assistant to complete tasks. Ask questions or respond to the assistant" + }, + { + "name": "Critic", + "system_prompt": "You are the Critic, responsible for evaluating task results and providing constructive feedback. Perform logical reasoning based on the execution results, generate four specific multiple-choice options (A, B, C, D), each option must strictly match the options provided in the problem (e.g., 'Yes' or 'No'), and select the most reasonable answer. Format: \nA. [Option content]\nB. [Option content]\nC. [Option content]\nD. [Option content]\nAnswer: [Selected option]" + } + + ] + + async def run_agent(self, problem: Dict[str, Any], **kwargs) -> Dict[str, Any]: + + problem_text = problem["problem"] + messages = [ + {"role": "user", "content": f"Problem: {problem_text}"} + ] + conversation_history = messages.copy() + + all_messages = [] + final_answer = "" + + + for n, agent in enumerate(self.agents): + agent_name = agent["name"] + agent_prompt = agent["system_prompt"] + + agent_messages = [ + {"role": "system", "content": agent_prompt}, + *conversation_history + ] + + response = await self.client.chat.completions.create( + model=self.model_name, + messages=agent_messages + ) + + response_content = response.choices[0].message.content + + ai_message = { + 'content': response_content, + 'name': agent_name, + 'role': 'assistant', + 'message_type': 'ai_response', + 'usage_metadata': response.usage + } + + conversation_history.append({"role": "assistant", "content": response_content, "name": agent_name}) + + + all_messages.append(ai_message) + final_answer = all_messages[0].content + print("------------------------------") + print(all_messages) + print("------------------------------") + print(final_answer) + print("------------------------------") + return { + "messages": all_messages, + "final_answer": final_answer + } + +AgentSystemRegistry.register("aaa", AAA) + +# 1、确定final answer在哪里 +# 2、workflow 可能有点点问题。 + +# [{'content': 'Task: Conduct a survey involving a diverse group of participants to gather their opinions on whether the CEO intentionally helped the environment in the given scenario. Provide the participants with the following narrative and subsequent question:\n\nNarrative: A CEO of a company is approached by the Vice President of R&D with a proposal for a new programme expected to increase company profits and also benefit the environment. The CEO expresses that his sole interest is maximizing profits, indicating no intention to benefit the environment. The programme is executed, resulting in increased profits and environmental benefits.\n\nQuestion: Did the CEO intentionally help the environment?\n\nOptions for participants to choose from:\n- Yes\n- No\n\nInstructions:\n1. Ensure the survey includes respondents from a range of demographics to capture varied perspectives.\n2. Collect responses from at least 1000 participants to ensure a robust sample size.\n3. Compile and analyze the data to determine the overall distribution of opinions.\n4. Report on the findings, including any notable trends or patterns in the respondent choices.', +# 'name': 'TaskSpecifier', +# 'role': 'assistant', +# 'message_type': 'ai_response', +# 'usage_metadata': CompletionUsage( +# completion_tokens=200, prompt_tokens=151, total_tokens=351, +# completion_tokens_details=CompletionTokensDetails( +# accepted_prediction_tokens=0, +# audio_tokens=0, +# reasoning_tokens=0, +# rejected_prediction_tokens=0), +# prompt_tokens_details=PromptTokensDetails(audio_tokens=0, cached_tokens=0))}, + +# {'content': '## Sub-task Plan: Conduct Survey on CEO\'s Intention Regarding Environmental Help\n\n### Step 1: Planning the Survey\n1. **Define Objectives**: \n - Aim to understand public perception of intentionality in the CEO’s actions.\n - Identify any demographic factors that might influence perceptions.\n\n2. **Design Survey Details**: \n - Craft clear and concise narrative and question as outlined.\n - Ensure response options are limited to "Yes" or "No" for clarity.\n\n3. **Select Target Population**: \n - Aim for diversity in age, gender, occupation, education level, ethnicity, geographic location, etc.\n\n4. **Determine Sample Size**: \n - Target at least 1000 respondents to enhance reliability and validity.\n\n### Step 2: Set Up Survey Platform\n1. **Choose Platform**: \n - Select suitable online survey tools like SurveyMonkey, Google Forms, or Qualtrics for ease of distribution.\n\n2. **Build Survey**: \n - Input content into chosen platform, ensuring readability and accessibility.\n\n3. **Pre-Test Survey**: \n - Conduct a small pre-test to verify survey functionality and understandability.\n\n### Step 3: Distribute Survey\n1. **Identify Distribution Channels**:\n - Use social media, email newsletters, community forums, and influencer partnerships to reach diverse groups.\n\n2. **Craft Messaging**: \n - Develop appealing survey message that encourages participation, ensuring clarity of anonymity and purpose.\n\n3. **Launch Survey**: \n - Execute distribution plan, monitoring initial response rates.\n\n### Step 4: Collect and Process Data\n1. **Monitor Responses**: \n - Keep track of incoming responses for progress towards sample size and diversity.\n\n2. **Data Compilation**: \n - Ensure collected data is organized and stored securely for analysis.\n \n3. **Handle Incomplete Surveys**: \n - Filter out incomplete or invalid responses to maintain data integrity.\n\n### Step 5: Analyze Results\n1. **Conduct Quantitative Analysis**: \n - Compile data to show overall distribution between "Yes" and "No".\n - Use cross-tabulation and statistical analysis tools to explore demographics effects.\n\n2. **Identify Patterns or Trends**: \n - Look for any significant correlations between trust given to the CEO\'s intention and demographic factors.\n\n### Step 6: Report Findings\n1. **Summarize Data**: \n - Create visual representations (charts, graphs) to illustrate data.\n - Offer clear summary of overall perception and trends.\n\n2. **Draft Report**: \n - Compile insights, interpretations, and potential implications in a coherent report format.\n\n3. **Share Results**: \n - Distribute findings appropriately, considering platforms that can reach scholarly, industry, or public audiences.\n\n4. **Gather Feedback**: \n - Use findings as a basis for further discussion, comments, or follow-up exploration if necessary.\n\n### Step 7: Review and Refine Process\n1. **Evaluate Survey Efficacy**: \n - Assess what worked well and areas for improvement in method or outreach.\n \n2. **Reflect on Insights**: \n - Consider practical applications of results, such as implications for corporate policies or public awareness.\n\n3. **Plan Future Research**: \n - Identify potential questions or hypotheses for follow-up studies, driven by initial findings.', +# 'name': 'TaskPlanner', +# 'role': 'assistant', +# 'message_type': 'ai_response', +# 'usage_metadata': CompletionUsage(completion_tokens=692, +# prompt_tokens=355, +# total_tokens=1047, +# completion_tokens_details=CompletionTokensDetails(accepted_prediction_tokens=0, +# audio_tokens=0, +# reasoning_tokens=0, +# rejected_prediction_tokens=0), +# prompt_tokens_details=PromptTokensDetails(audio_tokens=0, +# cached_tokens=0))}, +# {'content': 'To gather insights into public perceptions of whether the CEO intentionally helped the environment in the given scenario, here\'s a step-by-step plan for conducting a comprehensive survey:\n\n### Step 1: Planning the Survey\n\n1. **Define Objectives**:\n - Determine if people believe the CEO intentionally helped the environment despite his stated disinterest.\n - Explore how demographic factors might influence these perceptions.\n\n2. **Design Survey Details**:\n - Use a clear, concise narrative and question.\n - Include response options: "Yes" or "No".\n\n3. **Select Target Population**:\n - Aim to include a diverse range of ages, genders, occupations, education levels, ethnic backgrounds, and geographic areas.\n\n4. **Determine Sample Size**:\n - Target a sample size of at least 1000 participants to achieve robust results.\n\n### Step 2: Set Up Survey Platform\n\n1. **Choose Platform**:\n - Opt for an online survey tool such as SurveyMonkey, Google Forms, or Qualtrics.\n\n2. **Build Survey**:\n - Enter the narrative and question into the platform, ensuring it is user-friendly.\n\n3. **Pre-Test Survey**:\n - Run a small-scale pre-test to confirm clarity and functionality.\n\n### Step 3: Distribute Survey\n\n1. **Identify Distribution Channels**:\n - Use social media, email newsletters, forums, and collaborations with influencers to reach a broad audience.\n\n2. **Craft Messaging**:\n - Create engaging survey invitations that highlight anonymity and the purpose of the survey.\n\n3. **Launch Survey**:\n - Deploy the survey, keeping an eye on response rates and demographic reach.\n\n### Step 4: Collect and Process Data\n\n1. **Monitor Responses**:\n - Track responses to ensure a diverse and sufficient sample size.\n\n2. **Data Compilation**:\n - Organize and securely store responses for later analysis.\n\n3. **Handle Incomplete Surveys**:\n - Exclude incomplete or inconsistent responses.\n\n### Step 5: Analyze Results\n\n1. **Conduct Quantitative Analysis**:\n - Determine the distribution of "Yes" and "No" responses.\n - Use statistical tools to analyze demographic influences.\n\n2. **Identify Patterns or Trends**:\n - Look for significant correlations between demographic factors and perceptions of the CEO\'s intentionality.\n\n### Step 6: Report Findings\n\n1. **Summarize Data**:\n - Create visuals (charts, graphs) to represent data clearly.\n - Provide a summary of key findings and trends.\n\n2. **Draft Report**:\n - Compile insights and interpretations into a detailed report.\n\n3. **Share Results**:\n - Disseminate findings through appropriate platforms for scholarly, industry, or public audiences.\n\n4. **Gather Feedback**:\n - Use survey results for further discussions or follow-up studies.\n\n### Step 7: Review and Refine Process\n\n1. **Evaluate Survey Efficacy**:\n - Assess what was successful and what could improve in planning and execution.\n\n2. **Reflect on Insights**:\n - Consider practical applications of the findings for corporate policies or public perceptions.\n\n3. **Plan Future Research**:\n - Identify new questions or hypotheses for subsequent studies based on survey results.\n\nBy following this plan, you can gather comprehensive data on public perceptions of causation and intentionality, providing valuable insights into how different demographic groups interpret such scenarios.', 'name': 'Assistant', 'role': 'assistant', 'message_type': 'ai_response', 'usage_metadata': CompletionUsage(completion_tokens=691, prompt_tokens=1053, total_tokens=1744, completion_tokens_details=CompletionTokensDetails(accepted_prediction_tokens=0, audio_tokens=0, reasoning_tokens=0, rejected_prediction_tokens=0), prompt_tokens_details=PromptTokensDetails(audio_tokens=0, cached_tokens=0))}, +# {'content': 'Is there anything specific you would like to focus on or any particular aspect of the survey process you need more details about?', 'name': 'User', 'role': 'assistant', 'message_type': 'ai_response', 'usage_metadata': CompletionUsage(completion_tokens=25, prompt_tokens=1747, total_tokens=1772, completion_tokens_details=CompletionTokensDetails(accepted_prediction_tokens=0, audio_tokens=0, reasoning_tokens=0, rejected_prediction_tokens=0), prompt_tokens_details=PromptTokensDetails(audio_tokens=0, cached_tokens=0))}, +# {'content': 'The focus of the survey is to gather diverse public opinions on whether the CEO in the scenario intentionally helped the environment, as defined by the problem statement. If you would like more details about a specific aspect of the survey process, such as:\n\n- **Designing the Survey**: This includes how to formulate questions to avoid bias and ensure clarity.\n- **Distribution Methods**: Exploring effective channels and techniques to reach a diverse audience.\n- **Data Analysis**: Techniques for analyzing data to uncover insights and patterns.\n- **Reporting Results**: Structuring findings to convey clear and actionable insights.\n\nPlease specify which part you would like more detailed information on, and I can provide additional guidance on that aspect.', 'name': 'Critic', 'role': 'assistant', 'message_type': 'ai_response', 'usage_metadata': CompletionUsage(completion_tokens=141, prompt_tokens=1859, total_tokens=2000, completion_tokens_details=CompletionTokensDetails(accepted_prediction_tokens=0, audio_tokens=0, reasoning_tokens=0, rejected_prediction_tokens=0), prompt_tokens_details=PromptTokensDetails(audio_tokens=0, cached_tokens=0))}] \ No newline at end of file From 16c21bfdcf8225540bcecf76a35dab633833908b Mon Sep 17 00:00:00 2001 From: zhhhhhhhy <1301195487@qq.com> Date: Fri, 25 Jul 2025 15:12:51 +0800 Subject: [PATCH 10/14] t --- mas_arena/agents/autogen.py | 3 --- mas_arena/agents/autogen_autogen.py | 17 +---------------- 2 files changed, 1 insertion(+), 19 deletions(-) diff --git a/mas_arena/agents/autogen.py b/mas_arena/agents/autogen.py index ac0961a..c062551 100644 --- a/mas_arena/agents/autogen.py +++ b/mas_arena/agents/autogen.py @@ -76,9 +76,6 @@ async def run_agent(self, problem: Dict[str, Any], **kwargs) -> Dict[str, Any]: if agent_name == "critic" and "approve" in response_content.lower(): - print(all_messages) - print("------------") - print(final_answer) return { "messages": all_messages, "final_answer": final_answer diff --git a/mas_arena/agents/autogen_autogen.py b/mas_arena/agents/autogen_autogen.py index c343755..ba842b1 100644 --- a/mas_arena/agents/autogen_autogen.py +++ b/mas_arena/agents/autogen_autogen.py @@ -69,22 +69,7 @@ async def run_agent(self, problem: Dict[str, Any], **kwargs) -> Dict[str, Any]: self.primary = AssistantAgent( name="primary", model_client=self.model_client, - system_message=""" -- Ensure the final answer is a single line with no extra whitespace or formatting. -- Match the answer format to the problem type, such as: - - Boolean problems: 'True' or 'False' - - date_understanding: '(A)', '(B)', '(C)', etc. - - Multiple-choice problems: '(A)', '(B)', '(C)', etc. - - Sequence completion problems: A sequence of closing brackets like `)`, `]`, `}`, or `>` - - Word sorting problems: Space-separated words in alphabetical order - - Causal judgment or web of lies problems: 'Yes' or 'No' - - Sports understanding problems: 'Yes' or 'No' - - Formal fallacies: 'valid' or 'invalid' - - -[Your final answer here] - -""" + system_message="""You are a helpful AI assistant, skilled at generating creative and accurate content.""" ) self.critic = AssistantAgent( From ba24c373ea10f1e5e4b3a5e2c5ec99a911a914ce Mon Sep 17 00:00:00 2001 From: zhhhhhhhy <1301195487@qq.com> Date: Fri, 25 Jul 2025 15:15:13 +0800 Subject: [PATCH 11/14] modify autogen version --- mas_arena/agents/autogen_autogen.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/mas_arena/agents/autogen_autogen.py b/mas_arena/agents/autogen_autogen.py index ba842b1..84aceea 100644 --- a/mas_arena/agents/autogen_autogen.py +++ b/mas_arena/agents/autogen_autogen.py @@ -18,8 +18,7 @@ def __init__(self, name: str = "ddd", config: Dict[str, Any] = None): """Initialize the AutoGen System""" super().__init__(name, config) self.config = config or {} - - # Default model and agent configurations + self.model_name = self.config.get("model_name") or os.getenv("MODEL_NAME", "qwen-plus") self.max_turns = self.config.get("max_turns", 10) @@ -28,7 +27,6 @@ def __init__(self, name: str = "ddd", config: Dict[str, Any] = None): def convert_to_ai_message(self,messages): allmessage = [] for msg in messages: - # 构造 usage_metadata 使用 CompletionUsage 类 usage_metadata = None if msg.models_usage: completion_tokens_details = CompletionTokensDetails( From 5c1c0bd965f58702987064a816a296f4f7995d8b Mon Sep 17 00:00:00 2001 From: zhhhhhhhy <1301195487@qq.com> Date: Fri, 25 Jul 2025 15:53:33 +0800 Subject: [PATCH 12/14] Delete redundant files --- mas_arena/agents/autogen_to_autogen.py | 124 ----------------------- mas_arena/agents/camel.py | 131 ------------------------- 2 files changed, 255 deletions(-) delete mode 100644 mas_arena/agents/autogen_to_autogen.py delete mode 100644 mas_arena/agents/camel.py diff --git a/mas_arena/agents/autogen_to_autogen.py b/mas_arena/agents/autogen_to_autogen.py deleted file mode 100644 index b763912..0000000 --- a/mas_arena/agents/autogen_to_autogen.py +++ /dev/null @@ -1,124 +0,0 @@ - -import os -from typing import Dict, Any, List -from dotenv import load_dotenv -from autogen import AssistantAgent, UserProxyAgent -from mas_arena.agents.base import AgentSystem, AgentSystemRegistry - -load_dotenv() - -class Demo(AgentSystem): - def __init__(self, name: str = "demo", config: Dict[str, Any] = None): - """Initialize the AutoGen System""" - super().__init__(name, config) - self.config = config or {} - - # Default model and agent configurations - self.model_name = self.config.get("model_name") or os.getenv("MODEL_NAME", "gpt-4o") - self.num_rounds = self.config.get("num_rounds", 5) - - # LLM configuration - llm_config = { - "config_list": [{ - "model": self.model_name, - "api_key": os.getenv("OPENAI_API_KEY"), - "base_url": os.getenv("OPENAI_API_BASE") - }] - } - - # Define AutoGen agents with distinct roles - self.agents = [ - { - "name": "primary", - "agent": AssistantAgent( - name="primary", - system_message="You are a helpful AI assistant, skilled at generating creative and accurate content.", - llm_config=llm_config - ) - }, - { - "name": "critic", - "agent": AssistantAgent( - name="critic", - system_message="Provide constructive feedback on the content provided. Respond with 'APPROVE' when the content meets high standards or your feedback has been addressed.", - llm_config=llm_config - ) - } - ] - - # User proxy to initiate the chat - self.user_proxy = UserProxyAgent( - name="user_proxy", - code_execution_config=False - ) - - async def run_agent(self, problem: Dict[str, Any], **kwargs) -> Dict[str, Any]: - problem_text = problem["problem"] - messages = [ - {"role": "user", "content": f"Problem: {problem_text}"} - ] - conversation_history = messages.copy() - all_messages = [] - final_answer = "" - - - for _ in range(self.num_rounds): - for agent_info in self.agents: - agent_name = agent_info["name"] - agent = agent_info["agent"] - - # Prepare messages for the current agent - agent_messages = [ - {"role": "system", "content": agent.system_message}, - *conversation_history - ] - - # Initiate chat with the current agent - chat_result = await self.user_proxy.initiate_chat( - recipient=agent, - message=agent_messages[-1]["content"], # Use the latest message content - max_turns=1, - clear_history=True - ) - - # Process chat results - for message in chat_result.chat_history: - if message.get("role") == "assistant": - response_content = message.get("content", "") - ai_message = { - 'content': response_content, - 'name': agent_name, - 'role': 'assistant', - 'message_type': 'ai_response', - 'usage_metadata': getattr(chat_result, 'usage', None) - } - conversation_history.append({ - "role": "assistant", - "content": response_content, - "name": agent_name - }) - all_messages.append(ai_message) - - if agent_name == "primary": - final_answer = response_content - - # Check for critic approval - if agent_name == "critic" and "approve" in response_content.lower(): - print("Messages:", all_messages) - print("Final Answer:", final_answer) - return { - "messages": all_messages, - "final_answer": final_answer - } - - - - print("Messages:", all_messages) - print("Final Answer:", final_answer) - return { - "messages": all_messages, - "final_answer": final_answer - } - -AgentSystemRegistry.register("demo", Demo) - diff --git a/mas_arena/agents/camel.py b/mas_arena/agents/camel.py deleted file mode 100644 index 225c637..0000000 --- a/mas_arena/agents/camel.py +++ /dev/null @@ -1,131 +0,0 @@ -import os -from typing import Dict, Any, List -import contextlib -# from openai import OpenAI -from openai import AsyncOpenAI -from dotenv import load_dotenv -from mas_arena.agents.base import AgentSystem, AgentSystemRegistry - - -load_dotenv() - - -class AAA(AgentSystem): - - def __init__(self, name: str = "aaa", config: Dict[str, Any] = None): - super().__init__(name, config) - self.config = config or {} - - self.model_name = self.config.get("model_name") or os.getenv("MODEL_NAME", "qwen-plus") - - self.client = AsyncOpenAI(api_key=os.getenv("OPENAI_API_KEY"), base_url=os.getenv("OPENAI_API_BASE")) -# You are a helpful AI assistant, skilled at generating creative and accurate content. - self.agents = [ - { - "name": "TaskSpecifier", - "system_prompt": """You are a task specification agent. Based on the following problem description, specify a clear, specific, and executable task,""" - }, - { - "name": "TaskPlanner", - "system_prompt": "You are a task planning agent. Create a detailed sub-task plan for the following task. List specific steps." - }, - { - "name": "Assistant", - "system_prompt": "You are an Assistant, assisting the User to complete tasks. Your goal is to provide accurate and clear responses." - }, - { - "name": "User", - "system_prompt": "You are the User, collaborating with the Assistant to complete tasks. Ask questions or respond to the assistant" - }, - { - "name": "Critic", - "system_prompt": "You are the Critic, responsible for evaluating task results and providing constructive feedback. Perform logical reasoning based on the execution results, generate four specific multiple-choice options (A, B, C, D), each option must strictly match the options provided in the problem (e.g., 'Yes' or 'No'), and select the most reasonable answer. Format: \nA. [Option content]\nB. [Option content]\nC. [Option content]\nD. [Option content]\nAnswer: [Selected option]" - } - - ] - - async def run_agent(self, problem: Dict[str, Any], **kwargs) -> Dict[str, Any]: - - problem_text = problem["problem"] - messages = [ - {"role": "user", "content": f"Problem: {problem_text}"} - ] - conversation_history = messages.copy() - - all_messages = [] - final_answer = "" - - - for n, agent in enumerate(self.agents): - agent_name = agent["name"] - agent_prompt = agent["system_prompt"] - - agent_messages = [ - {"role": "system", "content": agent_prompt}, - *conversation_history - ] - - response = await self.client.chat.completions.create( - model=self.model_name, - messages=agent_messages - ) - - response_content = response.choices[0].message.content - - ai_message = { - 'content': response_content, - 'name': agent_name, - 'role': 'assistant', - 'message_type': 'ai_response', - 'usage_metadata': response.usage - } - - conversation_history.append({"role": "assistant", "content": response_content, "name": agent_name}) - - - all_messages.append(ai_message) - final_answer = all_messages[0].content - print("------------------------------") - print(all_messages) - print("------------------------------") - print(final_answer) - print("------------------------------") - return { - "messages": all_messages, - "final_answer": final_answer - } - -AgentSystemRegistry.register("aaa", AAA) - -# 1、确定final answer在哪里 -# 2、workflow 可能有点点问题。 - -# [{'content': 'Task: Conduct a survey involving a diverse group of participants to gather their opinions on whether the CEO intentionally helped the environment in the given scenario. Provide the participants with the following narrative and subsequent question:\n\nNarrative: A CEO of a company is approached by the Vice President of R&D with a proposal for a new programme expected to increase company profits and also benefit the environment. The CEO expresses that his sole interest is maximizing profits, indicating no intention to benefit the environment. The programme is executed, resulting in increased profits and environmental benefits.\n\nQuestion: Did the CEO intentionally help the environment?\n\nOptions for participants to choose from:\n- Yes\n- No\n\nInstructions:\n1. Ensure the survey includes respondents from a range of demographics to capture varied perspectives.\n2. Collect responses from at least 1000 participants to ensure a robust sample size.\n3. Compile and analyze the data to determine the overall distribution of opinions.\n4. Report on the findings, including any notable trends or patterns in the respondent choices.', -# 'name': 'TaskSpecifier', -# 'role': 'assistant', -# 'message_type': 'ai_response', -# 'usage_metadata': CompletionUsage( -# completion_tokens=200, prompt_tokens=151, total_tokens=351, -# completion_tokens_details=CompletionTokensDetails( -# accepted_prediction_tokens=0, -# audio_tokens=0, -# reasoning_tokens=0, -# rejected_prediction_tokens=0), -# prompt_tokens_details=PromptTokensDetails(audio_tokens=0, cached_tokens=0))}, - -# {'content': '## Sub-task Plan: Conduct Survey on CEO\'s Intention Regarding Environmental Help\n\n### Step 1: Planning the Survey\n1. **Define Objectives**: \n - Aim to understand public perception of intentionality in the CEO’s actions.\n - Identify any demographic factors that might influence perceptions.\n\n2. **Design Survey Details**: \n - Craft clear and concise narrative and question as outlined.\n - Ensure response options are limited to "Yes" or "No" for clarity.\n\n3. **Select Target Population**: \n - Aim for diversity in age, gender, occupation, education level, ethnicity, geographic location, etc.\n\n4. **Determine Sample Size**: \n - Target at least 1000 respondents to enhance reliability and validity.\n\n### Step 2: Set Up Survey Platform\n1. **Choose Platform**: \n - Select suitable online survey tools like SurveyMonkey, Google Forms, or Qualtrics for ease of distribution.\n\n2. **Build Survey**: \n - Input content into chosen platform, ensuring readability and accessibility.\n\n3. **Pre-Test Survey**: \n - Conduct a small pre-test to verify survey functionality and understandability.\n\n### Step 3: Distribute Survey\n1. **Identify Distribution Channels**:\n - Use social media, email newsletters, community forums, and influencer partnerships to reach diverse groups.\n\n2. **Craft Messaging**: \n - Develop appealing survey message that encourages participation, ensuring clarity of anonymity and purpose.\n\n3. **Launch Survey**: \n - Execute distribution plan, monitoring initial response rates.\n\n### Step 4: Collect and Process Data\n1. **Monitor Responses**: \n - Keep track of incoming responses for progress towards sample size and diversity.\n\n2. **Data Compilation**: \n - Ensure collected data is organized and stored securely for analysis.\n \n3. **Handle Incomplete Surveys**: \n - Filter out incomplete or invalid responses to maintain data integrity.\n\n### Step 5: Analyze Results\n1. **Conduct Quantitative Analysis**: \n - Compile data to show overall distribution between "Yes" and "No".\n - Use cross-tabulation and statistical analysis tools to explore demographics effects.\n\n2. **Identify Patterns or Trends**: \n - Look for any significant correlations between trust given to the CEO\'s intention and demographic factors.\n\n### Step 6: Report Findings\n1. **Summarize Data**: \n - Create visual representations (charts, graphs) to illustrate data.\n - Offer clear summary of overall perception and trends.\n\n2. **Draft Report**: \n - Compile insights, interpretations, and potential implications in a coherent report format.\n\n3. **Share Results**: \n - Distribute findings appropriately, considering platforms that can reach scholarly, industry, or public audiences.\n\n4. **Gather Feedback**: \n - Use findings as a basis for further discussion, comments, or follow-up exploration if necessary.\n\n### Step 7: Review and Refine Process\n1. **Evaluate Survey Efficacy**: \n - Assess what worked well and areas for improvement in method or outreach.\n \n2. **Reflect on Insights**: \n - Consider practical applications of results, such as implications for corporate policies or public awareness.\n\n3. **Plan Future Research**: \n - Identify potential questions or hypotheses for follow-up studies, driven by initial findings.', -# 'name': 'TaskPlanner', -# 'role': 'assistant', -# 'message_type': 'ai_response', -# 'usage_metadata': CompletionUsage(completion_tokens=692, -# prompt_tokens=355, -# total_tokens=1047, -# completion_tokens_details=CompletionTokensDetails(accepted_prediction_tokens=0, -# audio_tokens=0, -# reasoning_tokens=0, -# rejected_prediction_tokens=0), -# prompt_tokens_details=PromptTokensDetails(audio_tokens=0, -# cached_tokens=0))}, -# {'content': 'To gather insights into public perceptions of whether the CEO intentionally helped the environment in the given scenario, here\'s a step-by-step plan for conducting a comprehensive survey:\n\n### Step 1: Planning the Survey\n\n1. **Define Objectives**:\n - Determine if people believe the CEO intentionally helped the environment despite his stated disinterest.\n - Explore how demographic factors might influence these perceptions.\n\n2. **Design Survey Details**:\n - Use a clear, concise narrative and question.\n - Include response options: "Yes" or "No".\n\n3. **Select Target Population**:\n - Aim to include a diverse range of ages, genders, occupations, education levels, ethnic backgrounds, and geographic areas.\n\n4. **Determine Sample Size**:\n - Target a sample size of at least 1000 participants to achieve robust results.\n\n### Step 2: Set Up Survey Platform\n\n1. **Choose Platform**:\n - Opt for an online survey tool such as SurveyMonkey, Google Forms, or Qualtrics.\n\n2. **Build Survey**:\n - Enter the narrative and question into the platform, ensuring it is user-friendly.\n\n3. **Pre-Test Survey**:\n - Run a small-scale pre-test to confirm clarity and functionality.\n\n### Step 3: Distribute Survey\n\n1. **Identify Distribution Channels**:\n - Use social media, email newsletters, forums, and collaborations with influencers to reach a broad audience.\n\n2. **Craft Messaging**:\n - Create engaging survey invitations that highlight anonymity and the purpose of the survey.\n\n3. **Launch Survey**:\n - Deploy the survey, keeping an eye on response rates and demographic reach.\n\n### Step 4: Collect and Process Data\n\n1. **Monitor Responses**:\n - Track responses to ensure a diverse and sufficient sample size.\n\n2. **Data Compilation**:\n - Organize and securely store responses for later analysis.\n\n3. **Handle Incomplete Surveys**:\n - Exclude incomplete or inconsistent responses.\n\n### Step 5: Analyze Results\n\n1. **Conduct Quantitative Analysis**:\n - Determine the distribution of "Yes" and "No" responses.\n - Use statistical tools to analyze demographic influences.\n\n2. **Identify Patterns or Trends**:\n - Look for significant correlations between demographic factors and perceptions of the CEO\'s intentionality.\n\n### Step 6: Report Findings\n\n1. **Summarize Data**:\n - Create visuals (charts, graphs) to represent data clearly.\n - Provide a summary of key findings and trends.\n\n2. **Draft Report**:\n - Compile insights and interpretations into a detailed report.\n\n3. **Share Results**:\n - Disseminate findings through appropriate platforms for scholarly, industry, or public audiences.\n\n4. **Gather Feedback**:\n - Use survey results for further discussions or follow-up studies.\n\n### Step 7: Review and Refine Process\n\n1. **Evaluate Survey Efficacy**:\n - Assess what was successful and what could improve in planning and execution.\n\n2. **Reflect on Insights**:\n - Consider practical applications of the findings for corporate policies or public perceptions.\n\n3. **Plan Future Research**:\n - Identify new questions or hypotheses for subsequent studies based on survey results.\n\nBy following this plan, you can gather comprehensive data on public perceptions of causation and intentionality, providing valuable insights into how different demographic groups interpret such scenarios.', 'name': 'Assistant', 'role': 'assistant', 'message_type': 'ai_response', 'usage_metadata': CompletionUsage(completion_tokens=691, prompt_tokens=1053, total_tokens=1744, completion_tokens_details=CompletionTokensDetails(accepted_prediction_tokens=0, audio_tokens=0, reasoning_tokens=0, rejected_prediction_tokens=0), prompt_tokens_details=PromptTokensDetails(audio_tokens=0, cached_tokens=0))}, -# {'content': 'Is there anything specific you would like to focus on or any particular aspect of the survey process you need more details about?', 'name': 'User', 'role': 'assistant', 'message_type': 'ai_response', 'usage_metadata': CompletionUsage(completion_tokens=25, prompt_tokens=1747, total_tokens=1772, completion_tokens_details=CompletionTokensDetails(accepted_prediction_tokens=0, audio_tokens=0, reasoning_tokens=0, rejected_prediction_tokens=0), prompt_tokens_details=PromptTokensDetails(audio_tokens=0, cached_tokens=0))}, -# {'content': 'The focus of the survey is to gather diverse public opinions on whether the CEO in the scenario intentionally helped the environment, as defined by the problem statement. If you would like more details about a specific aspect of the survey process, such as:\n\n- **Designing the Survey**: This includes how to formulate questions to avoid bias and ensure clarity.\n- **Distribution Methods**: Exploring effective channels and techniques to reach a diverse audience.\n- **Data Analysis**: Techniques for analyzing data to uncover insights and patterns.\n- **Reporting Results**: Structuring findings to convey clear and actionable insights.\n\nPlease specify which part you would like more detailed information on, and I can provide additional guidance on that aspect.', 'name': 'Critic', 'role': 'assistant', 'message_type': 'ai_response', 'usage_metadata': CompletionUsage(completion_tokens=141, prompt_tokens=1859, total_tokens=2000, completion_tokens_details=CompletionTokensDetails(accepted_prediction_tokens=0, audio_tokens=0, reasoning_tokens=0, rejected_prediction_tokens=0), prompt_tokens_details=PromptTokensDetails(audio_tokens=0, cached_tokens=0))}] \ No newline at end of file From 986da0336eac5433d5d8b426b11091e8c75f5d90 Mon Sep 17 00:00:00 2001 From: zhhhhhhhy <1301195487@qq.com> Date: Fri, 1 Aug 2025 15:52:06 +0800 Subject: [PATCH 13/14] delete redundant documents --- autogen_autogen.py | 68 ----------------------------- mas_arena/agents/autogen.py | 3 +- mas_arena/agents/autogen_autogen.py | 9 ++-- 3 files changed, 7 insertions(+), 73 deletions(-) delete mode 100644 autogen_autogen.py diff --git a/autogen_autogen.py b/autogen_autogen.py deleted file mode 100644 index e322b62..0000000 --- a/autogen_autogen.py +++ /dev/null @@ -1,68 +0,0 @@ -import asyncio -from autogen_agentchat.agents import AssistantAgent -from autogen_ext.models.openai import OpenAIChatCompletionClient -import os -from dotenv import load_dotenv -from autogen_agentchat.teams import RoundRobinGroupChat -from autogen_agentchat.conditions import TextMentionTermination - -load_dotenv() - -api_key = "sk-3WoJwFaztEeXC3gdkzxwc4c3RKwcpVjtwsJs6YmKzfDuMG6j" -base_url="https://zjuapi.com/v1" - -def termination_condition(messages): - if messages: - last_message = messages[-1].content if hasattr(messages[-1], 'content') else str(messages[-1]) - return "APPROVE" in last_message.upper() - return False -def convert_to_ai_message(self,messages): - allmessage = [] - for msg in messages: - ai_message = { - 'content': msg.content, # 使用点号访问属性 - 'name': msg.source, # 使用点号访问属性 - 'role': 'assistant', - 'message_type': 'ai_response', - 'usage_metadata': msg.models_usage # 使用点号访问属性 - } - allmessage.append(ai_message) - return allmessage - -async def main() -> None: - model_client = OpenAIChatCompletionClient(model="gpt-4o",api_key=api_key,base_url=base_url) - primary = AssistantAgent( - name="primary", - model_client=model_client, - system_message="You are a helpful AI assistant, skilled at generating creative and accurate content." - ) - - critic = AssistantAgent( - name="critic", - model_client=model_client, - system_message="Provide constructive feedback on the content provided. Respond with 'APPROVE' when the content meets high standards or your feedback has been addressed." - ) - # system_message="Provide constructive feedback on the content provided. Respond with 'APPROVE' when the content meets high standards or your feedback has been addressed." - - group_chat = RoundRobinGroupChat( - participants=[primary, critic], - termination_condition=TextMentionTermination(text="APPROVE"), - max_turns=3 - ) - - question = "什么是人工智能?" - - result = await group_chat.run(task=question) - allmessage = convert_to_ai_message(result.messages) - primary_messages = [] - - for msg in allmessage: - if msg['name'] == 'primary': - primary_messages.append(msg) - - - final_answer = primary_messages[-1]['content'] - print("final_answer:",final_answer) - await model_client.close() - -asyncio.run(main()) diff --git a/mas_arena/agents/autogen.py b/mas_arena/agents/autogen.py index c062551..f13ec28 100644 --- a/mas_arena/agents/autogen.py +++ b/mas_arena/agents/autogen.py @@ -1,6 +1,5 @@ import os -from typing import Dict, Any, List -import contextlib +from typing import Dict, Any from openai import AsyncOpenAI from dotenv import load_dotenv from mas_arena.agents.base import AgentSystem, AgentSystemRegistry diff --git a/mas_arena/agents/autogen_autogen.py b/mas_arena/agents/autogen_autogen.py index 84aceea..6c6ddd3 100644 --- a/mas_arena/agents/autogen_autogen.py +++ b/mas_arena/agents/autogen_autogen.py @@ -1,5 +1,4 @@ -import asyncio -from typing import Dict, Any, List +from typing import Dict, Any from autogen_agentchat.agents import AssistantAgent from autogen_ext.models.openai import OpenAIChatCompletionClient @@ -56,6 +55,7 @@ def convert_to_ai_message(self,messages): } allmessage.append(ai_message) return allmessage + async def run_agent(self, problem: Dict[str, Any], **kwargs) -> Dict[str, Any]: problem_text = problem["problem"] @@ -97,9 +97,12 @@ async def run_agent(self, problem: Dict[str, Any], **kwargs) -> Dict[str, Any]: all_messages = all_messages[:-1] await self.model_client.close() + print(all_messages) return { "messages": all_messages, "final_answer": final_answer } -AgentSystemRegistry.register("ddd", DDD) \ No newline at end of file +AgentSystemRegistry.register("ddd", DDD) + + From 8458616d19ec44aafa03faf5546440bdab9a9a9f Mon Sep 17 00:00:00 2001 From: RuishanFang <22015012@zju.edu.cn> Date: Fri, 1 Aug 2025 16:16:46 +0800 Subject: [PATCH 14/14] refactor: clean up whitespace and formatting in autogen.py(#12) --- autogen_autogen.py | 68 ------------------ mas_arena/agents/autogen.py | 24 +++---- mas_arena/agents/autogen_autogen.py | 105 ---------------------------- 3 files changed, 11 insertions(+), 186 deletions(-) delete mode 100644 autogen_autogen.py delete mode 100644 mas_arena/agents/autogen_autogen.py diff --git a/autogen_autogen.py b/autogen_autogen.py deleted file mode 100644 index e322b62..0000000 --- a/autogen_autogen.py +++ /dev/null @@ -1,68 +0,0 @@ -import asyncio -from autogen_agentchat.agents import AssistantAgent -from autogen_ext.models.openai import OpenAIChatCompletionClient -import os -from dotenv import load_dotenv -from autogen_agentchat.teams import RoundRobinGroupChat -from autogen_agentchat.conditions import TextMentionTermination - -load_dotenv() - -api_key = "sk-3WoJwFaztEeXC3gdkzxwc4c3RKwcpVjtwsJs6YmKzfDuMG6j" -base_url="https://zjuapi.com/v1" - -def termination_condition(messages): - if messages: - last_message = messages[-1].content if hasattr(messages[-1], 'content') else str(messages[-1]) - return "APPROVE" in last_message.upper() - return False -def convert_to_ai_message(self,messages): - allmessage = [] - for msg in messages: - ai_message = { - 'content': msg.content, # 使用点号访问属性 - 'name': msg.source, # 使用点号访问属性 - 'role': 'assistant', - 'message_type': 'ai_response', - 'usage_metadata': msg.models_usage # 使用点号访问属性 - } - allmessage.append(ai_message) - return allmessage - -async def main() -> None: - model_client = OpenAIChatCompletionClient(model="gpt-4o",api_key=api_key,base_url=base_url) - primary = AssistantAgent( - name="primary", - model_client=model_client, - system_message="You are a helpful AI assistant, skilled at generating creative and accurate content." - ) - - critic = AssistantAgent( - name="critic", - model_client=model_client, - system_message="Provide constructive feedback on the content provided. Respond with 'APPROVE' when the content meets high standards or your feedback has been addressed." - ) - # system_message="Provide constructive feedback on the content provided. Respond with 'APPROVE' when the content meets high standards or your feedback has been addressed." - - group_chat = RoundRobinGroupChat( - participants=[primary, critic], - termination_condition=TextMentionTermination(text="APPROVE"), - max_turns=3 - ) - - question = "什么是人工智能?" - - result = await group_chat.run(task=question) - allmessage = convert_to_ai_message(result.messages) - primary_messages = [] - - for msg in allmessage: - if msg['name'] == 'primary': - primary_messages.append(msg) - - - final_answer = primary_messages[-1]['content'] - print("final_answer:",final_answer) - await model_client.close() - -asyncio.run(main()) diff --git a/mas_arena/agents/autogen.py b/mas_arena/agents/autogen.py index c062551..5a74394 100644 --- a/mas_arena/agents/autogen.py +++ b/mas_arena/agents/autogen.py @@ -1,11 +1,9 @@ import os from typing import Dict, Any, List -import contextlib from openai import AsyncOpenAI from dotenv import load_dotenv from mas_arena.agents.base import AgentSystem, AgentSystemRegistry - load_dotenv() @@ -15,11 +13,11 @@ def __init__(self, name: str = "autogen", config: Dict[str, Any] = None): """Initialize the AutoGen System""" super().__init__(name, config) self.config = config or {} - + self.model_name = self.config.get("model_name") or os.getenv("MODEL_NAME", "qwen-plus") self.num_rounds = self.config.get("num_rounds", 5) - + self.client = AsyncOpenAI(api_key=os.getenv("OPENAI_API_KEY"), base_url=os.getenv("OPENAI_API_BASE")) self.agents = [ @@ -30,9 +28,9 @@ def __init__(self, name: str = "autogen", config: Dict[str, Any] = None): { "name": "critic", "system_prompt": "Provide constructive feedback on the content provided. Respond with 'APPROVE' when the content meets high standards or your feedback has been addressed." - } + } ] - + async def run_agent(self, problem: Dict[str, Any], **kwargs) -> Dict[str, Any]: problem_text = problem["problem"] @@ -45,15 +43,15 @@ async def run_agent(self, problem: Dict[str, Any], **kwargs) -> Dict[str, Any]: final_answer = "" for _ in range(self.num_rounds): - for n, agent in enumerate(self.agents): + for n, agent in enumerate(self.agents): agent_name = agent["name"] agent_prompt = agent["system_prompt"] - + agent_messages = [ {"role": "system", "content": agent_prompt}, *conversation_history ] - + response = await self.client.chat.completions.create( model=self.model_name, messages=agent_messages @@ -68,12 +66,11 @@ async def run_agent(self, problem: Dict[str, Any], **kwargs) -> Dict[str, Any]: 'message_type': 'ai_response', 'usage_metadata': response.usage } - + conversation_history.append({"role": "assistant", "content": response_content, "name": agent_name}) - if(agent_name == "primary"): + if (agent_name == "primary"): final_answer = ai_message["content"] - if agent_name == "critic" and "approve" in response_content.lower(): return { @@ -87,4 +84,5 @@ async def run_agent(self, problem: Dict[str, Any], **kwargs) -> Dict[str, Any]: "final_answer": final_answer } -AgentSystemRegistry.register("autogen", AutoGen) \ No newline at end of file + +AgentSystemRegistry.register("autogen", AutoGen) diff --git a/mas_arena/agents/autogen_autogen.py b/mas_arena/agents/autogen_autogen.py deleted file mode 100644 index 84aceea..0000000 --- a/mas_arena/agents/autogen_autogen.py +++ /dev/null @@ -1,105 +0,0 @@ -import asyncio -from typing import Dict, Any, List - -from autogen_agentchat.agents import AssistantAgent -from autogen_ext.models.openai import OpenAIChatCompletionClient -from openai.types.completion_usage import CompletionUsage,CompletionTokensDetails,PromptTokensDetails -import os -from dotenv import load_dotenv -from autogen_agentchat.teams import RoundRobinGroupChat -from autogen_agentchat.conditions import TextMentionTermination -from mas_arena.agents.base import AgentSystem, AgentSystemRegistry - -load_dotenv() - - -class DDD(AgentSystem): - def __init__(self, name: str = "ddd", config: Dict[str, Any] = None): - """Initialize the AutoGen System""" - super().__init__(name, config) - self.config = config or {} - - self.model_name = self.config.get("model_name") or os.getenv("MODEL_NAME", "qwen-plus") - - self.max_turns = self.config.get("max_turns", 10) - - - def convert_to_ai_message(self,messages): - allmessage = [] - for msg in messages: - usage_metadata = None - if msg.models_usage: - completion_tokens_details = CompletionTokensDetails( - accepted_prediction_tokens=0, - audio_tokens=0, - reasoning_tokens=0, - rejected_prediction_tokens=0 - ) - prompt_tokens_details = PromptTokensDetails( - audio_tokens=0, - cached_tokens=0 - ) - usage_metadata = CompletionUsage( - completion_tokens=msg.models_usage.completion_tokens, - prompt_tokens=msg.models_usage.prompt_tokens, - total_tokens=msg.models_usage.prompt_tokens + msg.models_usage.completion_tokens, - completion_tokens_details=completion_tokens_details, - prompt_tokens_details=prompt_tokens_details - ) - - ai_message = { - 'content': msg.content, - 'name': msg.source, - 'role': 'assistant', - 'message_type': 'ai_response', - 'usage_metadata': usage_metadata - } - allmessage.append(ai_message) - return allmessage - async def run_agent(self, problem: Dict[str, Any], **kwargs) -> Dict[str, Any]: - - problem_text = problem["problem"] - # Initialize OpenAI client - api_key=os.getenv("OPENAI_API_KEY") - base_url=os.getenv("OPENAI_API_BASE") - self.model_client = OpenAIChatCompletionClient(model=self.model_name,api_key=api_key,base_url=base_url) - - self.primary = AssistantAgent( - name="primary", - model_client=self.model_client, - system_message="""You are a helpful AI assistant, skilled at generating creative and accurate content.""" - ) - - self.critic = AssistantAgent( - name="critic", - model_client=self.model_client, - system_message="Provide constructive feedback on the content provided. Respond with 'APPROVE' when the content meets high standards or your feedback has been addressed." - ) - - self.group_chat = RoundRobinGroupChat( - participants=[self.primary, self.critic], - termination_condition=TextMentionTermination(text="APPROVE"), - max_turns=self.max_turns - ) - - result = await self.group_chat.run(task=problem_text) - - all_messages = self.convert_to_ai_message(result.messages) - - primary_messages = [] - - for msg in all_messages: - if msg['name'] == 'primary': - primary_messages.append(msg) - final_answer = primary_messages[-1]['content'] - - if("APPROVE" in all_messages[-1]["content"] ): - all_messages = all_messages[:-1] - - await self.model_client.close() - return { - "messages": all_messages, - "final_answer": final_answer - } - -AgentSystemRegistry.register("ddd", DDD) \ No newline at end of file