From 7119e514e115196dc82b70dc24aa14ac946bc71d Mon Sep 17 00:00:00 2001 From: Kye Gomez Date: Tue, 22 Jul 2025 00:21:14 -0700 Subject: [PATCH] docs improvement --- README.md | 44 +++ docs/mkdocs.yml | 48 +-- .../agent_multi_agent_communication.md | 205 ++++++++++++ examples/api/client_example.py | 2 +- .../agent_communication_examples.py | 302 ++++++++++++++++++ .../heavy_swarm_example.py | 16 - heavy_swarm_example.py | 16 + swarms/agents/agent_judge.py | 2 +- swarms/prompts/prompt_generator_optimizer.py | 11 +- swarms/structs/agent.py | 39 +-- 10 files changed, 597 insertions(+), 88 deletions(-) create mode 100644 docs/swarms/structs/agent_multi_agent_communication.md create mode 100644 examples/multi_agent/agent_communication_examples.py delete mode 100644 examples/multi_agent/heavy_swarm_examples/heavy_swarm_example.py create mode 100644 heavy_swarm_example.py diff --git a/README.md b/README.md index b5591b7a..f293622a 100644 --- a/README.md +++ b/README.md @@ -226,6 +226,7 @@ print(final_post) | **[ForestSwarm](https://docs.swarms.world/en/latest/swarms/structs/forest_swarm/)** | Dynamically selects the most suitable agent or tree of agents for a given task. | Task routing, optimizing for expertise, complex decision-making trees. | | **[SpreadSheetSwarm](https://docs.swarms.world/en/latest/swarms/structs/spreadsheet_swarm/)** | Manages thousands of agents concurrently, tracking tasks and outputs in a structured format. | Massive-scale parallel operations, large-scale data generation and analysis. | | **[HierarchicalSwarm](https://docs.swarms.world/en/latest/swarms/structs/hiearchical_swarm/)** | Orchestrates agents with a director that creates plans and distributes tasks to specialized worker agents. | Complex project management, team coordination, hierarchical decision-making with feedback loops. | +| **[HeavySwarm](https://docs.swarms.world/en/latest/swarms/structs/heavy_swarm/)** | Implements a 5-phase workflow with specialized agents (Research, Analysis, Alternatives, Verification) for comprehensive task analysis. | Complex research and analysis tasks, financial analysis, strategic planning, comprehensive reporting. | | **[SwarmRouter](https://docs.swarms.world/en/latest/swarms/structs/swarm_router/)** | Universal orchestrator that provides a single interface to run any type of swarm with dynamic selection. | Simplifying complex workflows, switching between swarm strategies, unified multi-agent management. | ----- @@ -537,6 +538,49 @@ The `HierarchicalSwarm` excels at: --- +### HeavySwarm + +`HeavySwarm` implements a sophisticated 5-phase workflow inspired by X.AI's Grok heavy implementation. It uses specialized agents (Research, Analysis, Alternatives, Verification) to provide comprehensive task analysis through intelligent question generation, parallel execution, and synthesis. This architecture excels at complex research and analysis tasks requiring thorough investigation and multiple perspectives. + +```python +from swarms import HeavySwarm + +# Initialize the HeavySwarm with configuration +swarm = HeavySwarm( + worker_model_name="gpt-4o-mini", # Model for worker agents + question_agent_model_name="gpt-4o-mini", # Model for question generation + loops_per_agent=1, # Number of loops per agent + show_dashboard=True, # Enable real-time dashboard +) + +# Run complex analysis task +result = swarm.run( + "Provide 3 publicly traded biotech companies that are currently trading below their cash value. " + "For each company identified, provide available data or projections for the next 6 months, " + "including any relevant financial metrics, upcoming catalysts, or events that could impact valuation. " + "Present your findings in a clear, structured format with ticker symbols, current prices, " + "cash values, and percentage differences." +) + +print(result) +``` + +The `HeavySwarm` provides: + +- **5-Phase Analysis**: Question generation, research, analysis, alternatives, and verification + +- **Specialized Agents**: Each phase uses purpose-built agents for optimal results + +- **Comprehensive Coverage**: Multiple perspectives and thorough investigation + +- **Real-time Dashboard**: Optional visualization of the analysis process + +- **Structured Output**: Well-organized and actionable results + +This architecture is perfect for financial analysis, strategic planning, research reports, and any task requiring deep, multi-faceted analysis. [Learn more about HeavySwarm](https://docs.swarms.world/en/latest/swarms/structs/heavy_swarm/) + +--- + ## Documentation Documentation is located here at: [docs.swarms.world](https://docs.swarms.world) diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml index 9385c5ed..0317bebf 100644 --- a/docs/mkdocs.yml +++ b/docs/mkdocs.yml @@ -157,34 +157,36 @@ nav: - Feature Set: "swarms/features.md" - Agents: - Overview: "swarms/agents/index.md" - - Concepts: - # - Managing Prompts in Production: "swarms/prompts/main.md" - - Introduction into The Agent Architecture: "swarms/framework/agents_explained.md" - # - Introduction to Tools: "swarms/tools/overview.md" - - Documentation: - - Agent Class Documentation: "swarms/structs/agent.md" - - Create and Run Agents from YAML: "swarms/agents/create_agents_yaml.md" - - Integrating Various Models into Your Agents: "swarms/models/agent_and_models.md" - - Tools: + - Architecture: "swarms/framework/agents_explained.md" + - Agent Class Reference: "swarms/structs/agent.md" + - LLM Providers: "swarms/models/agent_and_models.md" + - Tools and MCP: "swarms/tools/tools_examples.md" + - Multi-Agent Helpers: "swarms/structs/agent_multi_agent_communication.md" + - Build, Run, and Manage Agents With YAML: "swarms/agents/create_agents_yaml.md" + + + - Additional Capabilities: + - Tools Reference: - Overview: "swarms/tools/main.md" - What are tools?: "swarms/tools/build_tool.md" - Structured Outputs: "swarms/agents/structured_outputs.md" - Agent MCP Integration: "swarms/structs/agent_mcp.md" - - Comprehensive Tool Guide with MCP, Callables, and more: "swarms/tools/tools_examples.md" - - RAG || Long Term Memory: + - Long Term Memory Reference: - Integrating RAG with Agents: "swarms/memory/diy_memory.md" - - Third-Party Agent Integrations: - - OpenAI Assistant: "swarms/agents/openai_assistant.md" - - Integrating External Agents from Griptape, Langchain, etc: "swarms/agents/external_party_agents.md" - - Creating Custom Agents: "swarms/agents/new_agent.md" - - PreBuilt Reasoning Agents: - - Self Consistency Agent: "swarms/agents/consistency_agent.md" - - IRE Agent: "swarms/agents/iterative_agent.md" - - Reasoning Duo: "swarms/agents/reasoning_duo.md" - - Reasoning Agent Router: "swarms/agents/reasoning_agent_router.md" - - Reflexion Agent: "swarms/agents/reflexion_agent.md" - - GKP Agent: "swarms/agents/gkp_agent.md" - - Agent Judge: "swarms/agents/agent_judge.md" + + - Third-Party Agents: + - Creating Custom Agents: "swarms/agents/new_agent.md" + - OpenAI Assistant: "swarms/agents/openai_assistant.md" + - Integrating External Agents from Griptape, Langchain, etc: "swarms/agents/external_party_agents.md" + + - Specialized Reasoning Agents: + - Self Consistency Agent: "swarms/agents/consistency_agent.md" + - IRE Agent: "swarms/agents/iterative_agent.md" + - Reasoning Duo: "swarms/agents/reasoning_duo.md" + - Reflexion Agent: "swarms/agents/reflexion_agent.md" + - GKP Agent: "swarms/agents/gkp_agent.md" + - Agent Judge: "swarms/agents/agent_judge.md" + - Reasoning Agent Router: "swarms/agents/reasoning_agent_router.md" - Multi-Agent Architectures: - Introduction to Multi-Agent Collaboration: "swarms/concept/why.md" diff --git a/docs/swarms/structs/agent_multi_agent_communication.md b/docs/swarms/structs/agent_multi_agent_communication.md new file mode 100644 index 00000000..12a92001 --- /dev/null +++ b/docs/swarms/structs/agent_multi_agent_communication.md @@ -0,0 +1,205 @@ +# Agent Multi-Agent Communication Methods + +The Agent class provides powerful built-in methods for facilitating communication and collaboration between multiple agents. These methods enable agents to talk to each other, pass information, and coordinate complex multi-agent workflows seamlessly. + +## Overview + +Multi-agent communication is essential for building sophisticated AI systems where different agents need to collaborate, share information, and coordinate their actions. The Agent class provides several methods to facilitate this communication: + +| Method | Purpose | Use Case | +|--------|---------|----------| +| `talk_to` | Direct communication between two agents | Agent handoffs, expert consultation | +| `talk_to_multiple_agents` | Concurrent communication with multiple agents | Broadcasting, consensus building | +| `receive_message` | Process incoming messages from other agents | Message handling, task delegation | +| `send_agent_message` | Send formatted messages to other agents | Direct messaging, notifications | + +## Features + +| Feature | Description | +|---------------------------------|--------------------------------------------------------------------| +| **Direct Agent Communication** | Enable one-to-one conversations between agents | +| **Concurrent Multi-Agent Communication** | Broadcast messages to multiple agents simultaneously | +| **Message Processing** | Handle incoming messages with contextual formatting | +| **Error Handling** | Robust error handling for failed communications | +| **Threading Support** | Efficient concurrent processing using ThreadPoolExecutor | +| **Flexible Parameters** | Support for images, custom arguments, and kwargs | + +--- + +## Core Methods + +### `talk_to(agent, task, img=None, *args, **kwargs)` + +Enables direct communication between the current agent and another agent. The method processes the task, generates a response, and then passes that response to the target agent. + +**Parameters:** + +| Parameter | Type | Default | Description | +|-----------|------|---------|-------------| +| `agent` | `Any` | Required | The target agent instance to communicate with | +| `task` | `str` | Required | The task or message to send to the agent | +| `img` | `str` | `None` | Optional image path for multimodal communication | +| `*args` | `Any` | - | Additional positional arguments | +| `**kwargs` | `Any` | - | Additional keyword arguments | + +**Returns:** `Any` - The response from the target agent + +**Usage Example:** + +```python +from swarms import Agent + +# Create two specialized agents +researcher = Agent( + agent_name="Research-Agent", + system_prompt="You are a research specialist focused on gathering and analyzing information.", + max_loops=1, +) + +analyst = Agent( + agent_name="Analysis-Agent", + system_prompt="You are an analytical specialist focused on interpreting research data.", + max_loops=1, +) + +# Agent communication +research_result = researcher.talk_to( + agent=analyst, + task="Analyze the market trends for renewable energy stocks" +) + +print(research_result) +``` + +### `talk_to_multiple_agents(agents, task, *args, **kwargs)` + +Enables concurrent communication with multiple agents using ThreadPoolExecutor for efficient parallel processing. + +**Parameters:** + +| Parameter | Type | Default | Description | +|-----------|------|---------|-------------| +| `agents` | `List[Union[Any, Callable]]` | Required | List of agent instances to communicate with | +| `task` | `str` | Required | The task or message to send to all agents | +| `*args` | `Any` | - | Additional positional arguments | +| `**kwargs` | `Any` | - | Additional keyword arguments | + +**Returns:** `List[Any]` - List of responses from all agents (or None for failed communications) + +**Usage Example:** + +```python +from swarms import Agent + +# Create multiple specialized agents +agents = [ + Agent( + agent_name="Financial-Analyst", + system_prompt="You are a financial analysis expert.", + max_loops=1, + ), + Agent( + agent_name="Risk-Assessor", + system_prompt="You are a risk assessment specialist.", + max_loops=1, + ), + Agent( + agent_name="Market-Researcher", + system_prompt="You are a market research expert.", + max_loops=1, + ) +] + +coordinator = Agent( + agent_name="Coordinator-Agent", + system_prompt="You coordinate multi-agent analysis.", + max_loops=1, +) + +# Broadcast to multiple agents +responses = coordinator.talk_to_multiple_agents( + agents=agents, + task="Evaluate the investment potential of Tesla stock" +) + +# Process responses +for i, response in enumerate(responses): + if response: + print(f"Agent {i+1} Response: {response}") + else: + print(f"Agent {i+1} failed to respond") +``` + +### `receive_message(agent_name, task, *args, **kwargs)` + +Processes incoming messages from other agents with proper context formatting. + +**Parameters:** + +| Parameter | Type | Default | Description | +|-----------|------|---------|-------------| +| `agent_name` | `str` | Required | Name of the sending agent | +| `task` | `str` | Required | The message content | +| `*args` | `Any` | - | Additional positional arguments | +| `**kwargs` | `Any` | - | Additional keyword arguments | + +**Returns:** `Any` - The agent's response to the received message + +**Usage Example:** + +```python +from swarms import Agent + +# Create an agent that can receive messages +recipient_agent = Agent( + agent_name="Support-Agent", + system_prompt="You provide helpful support and assistance.", + max_loops=1, +) + +# Simulate receiving a message from another agent +response = recipient_agent.receive_message( + agent_name="Customer-Service-Agent", + task="A customer is asking about refund policies. Can you help?" +) + +print(response) +``` + +### `send_agent_message(agent_name, message, *args, **kwargs)` + +Sends a formatted message from the current agent to a specified target agent. + +**Parameters:** + +| Parameter | Type | Default | Description | +|-----------|------|---------|-------------| +| `agent_name` | `str` | Required | Name of the target agent | +| `message` | `str` | Required | The message to send | +| `*args` | `Any` | - | Additional positional arguments | +| `**kwargs` | `Any` | - | Additional keyword arguments | + +**Returns:** `Any` - The result of sending the message + +**Usage Example:** + +```python +from swarms import Agent + +sender_agent = Agent( + agent_name="Notification-Agent", + system_prompt="You send notifications and updates.", + max_loops=1, +) + +# Send a message to another agent +result = sender_agent.send_agent_message( + agent_name="Task-Manager-Agent", + message="Task XYZ has been completed successfully" +) + +print(result) +``` + + +This comprehensive guide covers all aspects of multi-agent communication using the Agent class methods. These methods provide the foundation for building sophisticated multi-agent systems with robust communication capabilities. \ No newline at end of file diff --git a/examples/api/client_example.py b/examples/api/client_example.py index 9f2b7b88..f0880586 100644 --- a/examples/api/client_example.py +++ b/examples/api/client_example.py @@ -35,6 +35,6 @@ agent_spec = AgentSpecParam( print(json.dumps(client.models.list_available(), indent=4)) print(json.dumps(client.health.check(), indent=4)) -print(json.dumps(client.client.get_logs(), indent=4)) +print(json.dumps(client.swarms.get_logs(), indent=4)) print(json.dumps(client.client.rate.get_limits(), indent=4)) print(json.dumps(client.swarms.check_available(), indent=4)) diff --git a/examples/multi_agent/agent_communication_examples.py b/examples/multi_agent/agent_communication_examples.py new file mode 100644 index 00000000..23703b54 --- /dev/null +++ b/examples/multi_agent/agent_communication_examples.py @@ -0,0 +1,302 @@ +""" +Agent Multi-Agent Communication Examples + +This file demonstrates the multi-agent communication methods available in the Agent class: +- talk_to: Direct communication between two agents +- talk_to_multiple_agents: Concurrent communication with multiple agents +- receive_message: Process incoming messages from other agents +- send_agent_message: Send formatted messages to other agents + +Run: python agent_communication_examples.py +""" + +import os +from swarms import Agent + +# Set up your API key +os.environ["OPENAI_API_KEY"] = "your-openai-api-key" + + +def example_1_direct_agent_communication(): + """Example 1: Direct communication between two agents using talk_to method""" + print("=" * 60) + print("Example 1: Direct Agent Communication") + print("=" * 60) + + # Create two specialized agents + researcher = Agent( + agent_name="Research-Agent", + system_prompt="You are a research specialist focused on gathering and analyzing information. Provide detailed, fact-based responses.", + max_loops=1, + verbose=False, + ) + + analyst = Agent( + agent_name="Analysis-Agent", + system_prompt="You are an analytical specialist focused on interpreting research data and providing strategic insights.", + max_loops=1, + verbose=False, + ) + + # Agent communication + print("Researcher talking to Analyst...") + research_result = researcher.talk_to( + agent=analyst, + task="Analyze the market trends for renewable energy stocks and provide investment recommendations", + ) + + print(f"\nFinal Analysis Result:\n{research_result}") + return research_result + + +def example_2_multiple_agent_communication(): + """Example 2: Broadcasting to multiple agents using talk_to_multiple_agents""" + print("\n" + "=" * 60) + print("Example 2: Multiple Agent Communication") + print("=" * 60) + + # Create multiple specialized agents + agents = [ + Agent( + agent_name="Financial-Analyst", + system_prompt="You are a financial analysis expert specializing in stock valuation and market trends.", + max_loops=1, + verbose=False, + ), + Agent( + agent_name="Risk-Assessor", + system_prompt="You are a risk assessment specialist focused on identifying potential investment risks.", + max_loops=1, + verbose=False, + ), + Agent( + agent_name="Market-Researcher", + system_prompt="You are a market research expert specializing in industry analysis and competitive intelligence.", + max_loops=1, + verbose=False, + ), + ] + + coordinator = Agent( + agent_name="Coordinator-Agent", + system_prompt="You coordinate multi-agent analysis and synthesize diverse perspectives into actionable insights.", + max_loops=1, + verbose=False, + ) + + # Broadcast to multiple agents + print("Coordinator broadcasting to multiple agents...") + responses = coordinator.talk_to_multiple_agents( + agents=agents, + task="Evaluate the investment potential of Tesla stock for the next quarter", + ) + + # Process responses + print("\nResponses from all agents:") + for i, response in enumerate(responses): + if response: + print(f"\n{agents[i].agent_name} Response:") + print("-" * 40) + print( + response[:200] + "..." + if len(response) > 200 + else response + ) + else: + print(f"\n{agents[i].agent_name}: Failed to respond") + + return responses + + +def example_3_message_handling(): + """Example 3: Message handling using receive_message and send_agent_message""" + print("\n" + "=" * 60) + print("Example 3: Message Handling") + print("=" * 60) + + # Create an agent that can receive messages + support_agent = Agent( + agent_name="Support-Agent", + system_prompt="You provide helpful support and assistance. Always be professional and solution-oriented.", + max_loops=1, + verbose=False, + ) + + notification_agent = Agent( + agent_name="Notification-Agent", + system_prompt="You send notifications and updates to other systems and agents.", + max_loops=1, + verbose=False, + ) + + # Example of receiving a message + print("Support agent receiving message...") + received_response = support_agent.receive_message( + agent_name="Customer-Service-Agent", + task="A customer is asking about our refund policies for software purchases. Can you provide guidance?", + ) + print(f"\nSupport Agent Response:\n{received_response}") + + # Example of sending a message + print("\nNotification agent sending message...") + sent_result = notification_agent.send_agent_message( + agent_name="Task-Manager-Agent", + message="Customer support ticket #12345 has been resolved successfully", + ) + print(f"\nNotification Result:\n{sent_result}") + + return received_response, sent_result + + +def example_4_sequential_workflow(): + """Example 4: Sequential agent workflow using communication methods""" + print("\n" + "=" * 60) + print("Example 4: Sequential Agent Workflow") + print("=" * 60) + + # Create specialized agents for a document processing workflow + extractor = Agent( + agent_name="Data-Extractor", + system_prompt="You extract key information and data points from documents. Focus on accuracy and completeness.", + max_loops=1, + verbose=False, + ) + + validator = Agent( + agent_name="Data-Validator", + system_prompt="You validate and verify extracted data for accuracy, completeness, and consistency.", + max_loops=1, + verbose=False, + ) + + formatter = Agent( + agent_name="Data-Formatter", + system_prompt="You format validated data into structured, professional reports and summaries.", + max_loops=1, + verbose=False, + ) + + # Sequential processing workflow + document_content = """ + Q3 Financial Report Summary: + - Revenue: $2.5M (up 15% from Q2) + - Expenses: $1.8M (operational costs increased by 8%) + - Net Profit: $700K (improved profit margin of 28%) + - New Customers: 1,200 (25% growth rate) + - Customer Retention: 92% + - Market Share: Increased to 12% in our sector + """ + + print("Starting sequential workflow...") + + # Step 1: Extract data + print("\nStep 1: Data Extraction") + extracted_data = extractor.run( + f"Extract key financial metrics from this report: {document_content}" + ) + print(f"Extracted: {extracted_data[:150]}...") + + # Step 2: Validate data + print("\nStep 2: Data Validation") + validated_data = extractor.talk_to( + agent=validator, + task=f"Please validate this extracted data for accuracy and completeness: {extracted_data}", + ) + print(f"Validated: {validated_data[:150]}...") + + # Step 3: Format data + print("\nStep 3: Data Formatting") + final_output = validator.talk_to( + agent=formatter, + task=f"Format this validated data into a structured executive summary: {validated_data}", + ) + + print(f"\nFinal Report:\n{final_output}") + return final_output + + +def example_5_error_handling(): + """Example 5: Robust communication with error handling""" + print("\n" + "=" * 60) + print("Example 5: Communication with Error Handling") + print("=" * 60) + + def safe_agent_communication(sender, receiver, message): + """Safely handle agent communication with comprehensive error handling""" + try: + print( + f"Attempting communication: {sender.agent_name} -> {receiver.agent_name}" + ) + response = sender.talk_to(agent=receiver, task=message) + return { + "success": True, + "response": response, + "error": None, + } + except Exception as e: + print(f"Communication failed: {e}") + return { + "success": False, + "response": None, + "error": str(e), + } + + # Create agents + agent_a = Agent( + agent_name="Agent-A", + system_prompt="You are a helpful assistant focused on providing accurate information.", + max_loops=1, + verbose=False, + ) + + agent_b = Agent( + agent_name="Agent-B", + system_prompt="You are a knowledgeable expert in technology and business trends.", + max_loops=1, + verbose=False, + ) + + # Safe communication + result = safe_agent_communication( + sender=agent_a, + receiver=agent_b, + message="What are the latest trends in artificial intelligence and how might they impact business operations?", + ) + + if result["success"]: + print("\nCommunication successful!") + print(f"Response: {result['response'][:200]}...") + else: + print(f"\nCommunication failed: {result['error']}") + + return result + + +def main(): + """Run all multi-agent communication examples""" + print("🤖 Agent Multi-Agent Communication Examples") + print( + "This demonstrates the communication methods available in the Agent class" + ) + + try: + # Run all examples + example_1_direct_agent_communication() + example_2_multiple_agent_communication() + example_3_message_handling() + example_4_sequential_workflow() + example_5_error_handling() + + print("\n" + "=" * 60) + print("✅ All examples completed successfully!") + print("=" * 60) + + except Exception as e: + print(f"\n❌ Error running examples: {e}") + print( + "Make sure to set your OPENAI_API_KEY environment variable" + ) + + +if __name__ == "__main__": + main() diff --git a/examples/multi_agent/heavy_swarm_examples/heavy_swarm_example.py b/examples/multi_agent/heavy_swarm_examples/heavy_swarm_example.py deleted file mode 100644 index 9c8bcb96..00000000 --- a/examples/multi_agent/heavy_swarm_examples/heavy_swarm_example.py +++ /dev/null @@ -1,16 +0,0 @@ -from swarms.structs.heavy_swarm import HeavySwarm - - -swarm = HeavySwarm( - worker_model_name="claude-3-5-sonnet-20240620", - show_dashboard=True, - question_agent_model_name="gpt-4.1", - loops_per_agent=1, -) - - -out = swarm.run( - "Identify the top 3 energy sector ETFs listed on US exchanges that offer the highest potential for growth over the next 3-5 years. Focus specifically on funds with significant exposure to companies in the nuclear, natural gas, or oil industries. For each ETF, provide the rationale for its selection, recent performance metrics, sector allocation breakdown, and any notable holdings related to nuclear, gas, or oil. Exclude broad-based energy ETFs that do not have a clear emphasis on these sub-sectors." -) - -print(out) diff --git a/heavy_swarm_example.py b/heavy_swarm_example.py new file mode 100644 index 00000000..57715ff7 --- /dev/null +++ b/heavy_swarm_example.py @@ -0,0 +1,16 @@ +from swarms.structs.heavy_swarm import HeavySwarm + + +swarm = HeavySwarm( + worker_model_name="claude-3-5-sonnet-20240620", + show_dashboard=True, + question_agent_model_name="gpt-4.1", + loops_per_agent=1, +) + + +out = swarm.run( + "Provide 3 publicly traded biotech companies that are currently trading below their cash value. For each company identified, provide available data or projections for the next 6 months, including any relevant financial metrics, upcoming catalysts, or events that could impact valuation. Present your findings in a clear, structured format. Be very specific and provide their ticker symbol, name, and the current price, cash value, and the percentage difference between the two." +) + +print(out) diff --git a/swarms/agents/agent_judge.py b/swarms/agents/agent_judge.py index 1cfdc033..f1cdfdb2 100644 --- a/swarms/agents/agent_judge.py +++ b/swarms/agents/agent_judge.py @@ -259,7 +259,7 @@ class AgentJudge: # 在任务说明中添加评估标准 if self.evaluation_criteria: - criteria_names = list(self.evaluation_criteria.keys()) + list(self.evaluation_criteria.keys()) task_instruction += "\nPlease use these specific evaluation criteria with their respective weights:\n" for ( criterion, diff --git a/swarms/prompts/prompt_generator_optimizer.py b/swarms/prompts/prompt_generator_optimizer.py index f89bc6de..9d115f3b 100644 --- a/swarms/prompts/prompt_generator_optimizer.py +++ b/swarms/prompts/prompt_generator_optimizer.py @@ -1,6 +1,3 @@ -from swarms.prompts.prompt import Prompt - - OPENAI_PROMPT_GENERATOR_SYS_PROMPT = """ Given a task description or existing prompt, produce a detailed system prompt to guide a language model in completing the task effectively. @@ -51,9 +48,5 @@ The final prompt you output should adhere to the following structure below. Do n """ -prompt_generator_sys_prompt = Prompt( - name="openai-prompt-generator-optimizer-prompt", - description="Generate and or optimize existing prompts", - content=OPENAI_PROMPT_GENERATOR_SYS_PROMPT, - autosave=True, -) + +prompt_generator_sys_prompt = OPENAI_PROMPT_GENERATOR_SYS_PROMPT diff --git a/swarms/structs/agent.py b/swarms/structs/agent.py index 224258c5..8ed7707a 100644 --- a/swarms/structs/agent.py +++ b/swarms/structs/agent.py @@ -1261,12 +1261,6 @@ class Agent: self, task: Optional[str] = None, img: Optional[str] = None, - is_last: bool = False, - device: str = "cpu", # gpu - device_id: int = 1, - all_cores: bool = True, - do_not_use_cluster_ops: bool = True, - all_gpus: bool = False, *args, **kwargs, ) -> Any: @@ -1337,37 +1331,6 @@ class Agent: ) return self.run(task=improved_prompt, *args, **kwargs) - # def parse_and_execute_tools(self, response: str, *args, **kwargs): - # max_retries = 3 # Maximum number of retries - # retries = 0 - # while retries < max_retries: - # try: - # logger.info("Executing tool...") - - # # try to Execute the tool and return a string - # out = parse_and_execute_json( - # functions=self.tools, - # json_string=response, - # parse_md=True, - # *args, - # **kwargs, - # ) - # logger.info(f"Tool Output: {out}") - # # Add the output to the memory - # # self.short_memory.add( - # # role="Tool Executor", - # # content=out, - # # ) - # return out - # except Exception as error: - # retries += 1 - # logger.error( - # f"Attempt {retries}: Error executing tool: {error}" - # ) - # if retries == max_retries: - # raise error - # time.sleep(1) # Wait for a bit before retrying - def add_memory(self, message: str): """Add a memory to the agent @@ -3241,7 +3204,7 @@ class Agent: f"Agent '{self.agent_name}' received None response from LLM in loop {loop_count}. " f"This may indicate an issue with the model or prompt. Skipping tool execution." ) - except Exception as e: + except AgentToolExecutionError as e: logger.error( f"Agent '{self.agent_name}' encountered error during tool execution in loop {loop_count}: {str(e)}. " f"Full traceback: {traceback.format_exc()}. "