From fb389903e17bcff69747c33c5fc567bf38a3bcaf Mon Sep 17 00:00:00 2001 From: Kye Gomez Date: Thu, 10 Jul 2025 18:20:06 -0700 Subject: [PATCH] [ENHANCEMENT][HiearchicalSwarm][Massive improvements to the hiearchical swarm, simplification, flexibility, speed improvements, and much more] [DOCS][HiearchicalSwarm] [Examples][hiearchical_examples] --- docs/mkdocs.yml | 3 +- .../examples/hierarchical_swarm_example.md | 226 ++++ docs/swarms/examples/templates_index.md | 1 + docs/swarms/structs/hierarchical_swarm.md | 360 ++++++ docs/swarms/structs/index.md | 51 +- docs/swarms/structs/overview.md | 1 + example.py | 8 +- examples/api/legal_team.py | 177 +++ .../multi_agent/concurrent_examples/asi.py | 19 + .../advanced_hierarchical_swarm_examples.py | 428 +++++++ .../hiearchical_swarm_test.py | 269 +++++ .../hierarchical_swarm_example.py | 156 +++ examples/single_agent/utils/grok_4_agent.py | 15 + pyproject.toml | 2 +- ...ent_router.py => reasoning_agent_router.py | 0 swarms/agents/reasoning_agents.py | 1 - swarms/prompts/collaborative_prompts.py | 145 ++- swarms/prompts/hiearchical_system_prompt.py | 159 +++ swarms/structs/agent.py | 330 +----- swarms/structs/hiearchical_swarm.py | 1044 ++++++++--------- swarms/structs/interactive_groupchat.py | 2 +- swarms/structs/ma_utils.py | 48 +- swarms/utils/formatter.py | 27 +- swarms/utils/lite_utils.py | 5 + 24 files changed, 2599 insertions(+), 878 deletions(-) create mode 100644 docs/swarms/examples/hierarchical_swarm_example.md create mode 100644 docs/swarms/structs/hierarchical_swarm.md create mode 100644 examples/api/legal_team.py create mode 100644 examples/multi_agent/concurrent_examples/asi.py create mode 100644 examples/multi_agent/hiearchical_swarm/hiearchical_examples/advanced_hierarchical_swarm_examples.py create mode 100644 examples/multi_agent/hiearchical_swarm/hiearchical_examples/hiearchical_swarm_test.py create mode 100644 examples/multi_agent/hiearchical_swarm/hiearchical_examples/hierarchical_swarm_example.py create mode 100644 examples/single_agent/utils/grok_4_agent.py rename examples/single_agent/reasoning_agent_examples/reasoning_agent_router.py => reasoning_agent_router.py (100%) create mode 100644 swarms/prompts/hiearchical_system_prompt.py create mode 100644 swarms/utils/lite_utils.py diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml index b6c7f57b..04c6b0da 100644 --- a/docs/mkdocs.yml +++ b/docs/mkdocs.yml @@ -145,7 +145,6 @@ nav: - Environment Configuration: "swarms/install/env.md" - Agents: "swarms/agents/index.md" - Multi-Agent Architectures: "swarms/structs/index.md" - # - Learn More: "swarms/learn_more/index.md" - Guides: - Overview: "index.md" @@ -209,6 +208,7 @@ nav: - Hiearchical Architectures: + - HierarchicalSwarm: "swarms/structs/hierarchical_swarm.md" - Auto Agent Builder: "swarms/structs/auto_agent_builder.md" - Hybrid Hierarchical-Cluster Swarm: "swarms/structs/hhcs.md" - Auto Swarm Builder: "swarms/structs/auto_swarm_builder.md" @@ -308,6 +308,7 @@ nav: - Advanced Examples: - Multi-Agent Architectures: + - HierarchicalSwarm Examples: "swarms/examples/hierarchical_swarm_example.md" - Hybrid Hierarchical-Cluster Swarm Example: "swarms/examples/hhcs_examples.md" - Group Chat Example: "swarms/examples/groupchat_example.md" - Sequential Workflow Example: "swarms/examples/sequential_example.md" diff --git a/docs/swarms/examples/hierarchical_swarm_example.md b/docs/swarms/examples/hierarchical_swarm_example.md new file mode 100644 index 00000000..a3a9cf1e --- /dev/null +++ b/docs/swarms/examples/hierarchical_swarm_example.md @@ -0,0 +1,226 @@ +# Hierarchical Swarm Examples + +This page provides simple, practical examples of how to use the `HierarchicalSwarm` for various real-world scenarios. + +## Basic Example: Financial Analysis + +```python +from swarms import Agent +from swarms.structs.hiearchical_swarm import HierarchicalSwarm + +# Create specialized financial analysis agents +market_research_agent = Agent( + agent_name="Market-Research-Specialist", + agent_description="Expert in market research, trend analysis, and competitive intelligence", + system_prompt="""You are a senior market research specialist with expertise in: + - Market trend analysis and forecasting + - Competitive landscape assessment + - Consumer behavior analysis + - Industry report generation + - Market opportunity identification + - Risk assessment and mitigation strategies""", + model_name="gpt-4o", +) + +financial_analyst_agent = Agent( + agent_name="Financial-Analysis-Expert", + agent_description="Specialist in financial statement analysis, valuation, and investment research", + system_prompt="""You are a senior financial analyst with deep expertise in: + - Financial statement analysis (income statement, balance sheet, cash flow) + - Valuation methodologies (DCF, comparable company analysis, precedent transactions) + - Investment research and due diligence + - Financial modeling and forecasting + - Risk assessment and portfolio analysis + - ESG (Environmental, Social, Governance) analysis""", + model_name="gpt-4o", +) + +# Initialize the hierarchical swarm +financial_analysis_swarm = HierarchicalSwarm( + name="Financial-Analysis-Hierarchical-Swarm", + description="A hierarchical swarm for comprehensive financial analysis with specialized agents", + agents=[market_research_agent, financial_analyst_agent], + max_loops=2, + verbose=True, +) + +# Execute financial analysis +task = "Conduct a comprehensive analysis of Tesla (TSLA) stock including market position, financial health, and investment potential" +result = financial_analysis_swarm.run(task=task) +print(result) +``` + +## Development Team Example + +```python +from swarms import Agent +from swarms.structs.hiearchical_swarm import HierarchicalSwarm + +# Create specialized development agents +frontend_developer_agent = Agent( + agent_name="Frontend-Developer", + agent_description="Senior frontend developer expert in modern web technologies and user experience", + system_prompt="""You are a senior frontend developer with expertise in: + - Modern JavaScript frameworks (React, Vue, Angular) + - TypeScript and modern ES6+ features + - CSS frameworks and responsive design + - State management (Redux, Zustand, Context API) + - Web performance optimization + - Accessibility (WCAG) and SEO best practices""", + model_name="gpt-4o", +) + +backend_developer_agent = Agent( + agent_name="Backend-Developer", + agent_description="Senior backend developer specializing in server-side development and API design", + system_prompt="""You are a senior backend developer with expertise in: + - Server-side programming languages (Python, Node.js, Java, Go) + - Web frameworks (Django, Flask, Express, Spring Boot) + - Database design and optimization (SQL, NoSQL) + - API design and REST/GraphQL implementation + - Authentication and authorization systems + - Microservices architecture and containerization""", + model_name="gpt-4o", +) + +# Initialize the development swarm +development_department_swarm = HierarchicalSwarm( + name="Autonomous-Development-Department", + description="A fully autonomous development department with specialized agents", + agents=[frontend_developer_agent, backend_developer_agent], + max_loops=3, + verbose=True, +) + +# Execute development project +task = "Create a simple web app that allows users to upload a file and then download it. The app should be built with React and Node.js." +result = development_department_swarm.run(task=task) +print(result) +``` + +## Single Step Execution + +```python +from swarms import Agent +from swarms.structs.hiearchical_swarm import HierarchicalSwarm + +# Create analysis agents +market_agent = Agent( + agent_name="Market-Analyst", + agent_description="Expert in market analysis and trends", + model_name="gpt-4o", +) + +technical_agent = Agent( + agent_name="Technical-Analyst", + agent_description="Specialist in technical analysis and patterns", + model_name="gpt-4o", +) + +# Initialize the swarm +swarm = HierarchicalSwarm( + name="Analysis-Swarm", + description="A hierarchical swarm for comprehensive analysis", + agents=[market_agent, technical_agent], + max_loops=1, + verbose=True, +) + +# Execute a single step +task = "Analyze the current market trends for electric vehicles" +feedback = swarm.step(task=task) +print("Director Feedback:", feedback) +``` + +## Batch Processing + +```python +from swarms import Agent +from swarms.structs.hiearchical_swarm import HierarchicalSwarm + +# Create analysis agents +market_agent = Agent( + agent_name="Market-Analyst", + agent_description="Expert in market analysis and trends", + model_name="gpt-4o", +) + +technical_agent = Agent( + agent_name="Technical-Analyst", + agent_description="Specialist in technical analysis and patterns", + model_name="gpt-4o", +) + +# Initialize the swarm +swarm = HierarchicalSwarm( + name="Analysis-Swarm", + description="A hierarchical swarm for comprehensive analysis", + agents=[market_agent, technical_agent], + max_loops=2, + verbose=True, +) + +# Execute multiple tasks +tasks = [ + "Analyze Apple (AAPL) stock performance", + "Evaluate Microsoft (MSFT) market position", + "Assess Google (GOOGL) competitive landscape" +] + +results = swarm.batched_run(tasks=tasks) +for i, result in enumerate(results): + print(f"Task {i+1} Result:", result) +``` + +## Research Team Example + +```python +from swarms import Agent +from swarms.structs.hiearchical_swarm import HierarchicalSwarm + +# Create specialized research agents +research_manager = Agent( + agent_name="Research-Manager", + agent_description="Manages research operations and coordinates research tasks", + system_prompt="You are a research manager responsible for overseeing research projects and coordinating research efforts.", + model_name="gpt-4o", +) + +data_analyst = Agent( + agent_name="Data-Analyst", + agent_description="Analyzes data and generates insights", + system_prompt="You are a data analyst specializing in processing and analyzing data to extract meaningful insights.", + model_name="gpt-4o", +) + +research_assistant = Agent( + agent_name="Research-Assistant", + agent_description="Assists with research tasks and data collection", + system_prompt="You are a research assistant who helps gather information and support research activities.", + model_name="gpt-4o", +) + +# Initialize the research swarm +research_swarm = HierarchicalSwarm( + name="Research-Team-Swarm", + description="A hierarchical swarm for comprehensive research projects", + agents=[research_manager, data_analyst, research_assistant], + max_loops=2, + verbose=True, +) + +# Execute research project +task = "Conduct a comprehensive market analysis for a new AI-powered productivity tool" +result = research_swarm.run(task=task) +print(result) +``` + +## Key Takeaways + +1. **Agent Specialization**: Create agents with specific, well-defined expertise areas +2. **Clear Task Descriptions**: Provide detailed, actionable task descriptions +3. **Appropriate Loop Count**: Set `max_loops` based on task complexity (1-3 for most tasks) +4. **Verbose Logging**: Enable verbose mode during development for debugging +5. **Context Preservation**: The swarm maintains full conversation history automatically + +For more detailed information about the `HierarchicalSwarm` API and advanced usage patterns, see the [main documentation](hierarchical_swarm.md). \ No newline at end of file diff --git a/docs/swarms/examples/templates_index.md b/docs/swarms/examples/templates_index.md index fd64d448..bf0c3668 100644 --- a/docs/swarms/examples/templates_index.md +++ b/docs/swarms/examples/templates_index.md @@ -68,5 +68,6 @@ The Swarms Index is a comprehensive catalog of repositories under The Swarm Corp | medical-problems | A repository for medical problems to create Swarms applications for. | [https://github.com/The-Swarm-Corporation/medical-problems](https://github.com/The-Swarm-Corporation/medical-problems) | | swarm-ecosystem | An overview of the Swarm Ecosystem and its components. | [https://github.com/The-Swarm-Corporation/swarm-ecosystem](https://github.com/The-Swarm-Corporation/swarm-ecosystem) | | swarms_ecosystem_md | MDX documentation for the Swarm Ecosystem. | [https://github.com/The-Swarm-Corporation/swarms_ecosystem_md](https://github.com/The-Swarm-Corporation/swarms_ecosystem_md) | +| Hierarchical Swarm Examples | Simple, practical examples of HierarchicalSwarm usage for various real-world scenarios. | [Documentation](hierarchical_swarm_example.md) | diff --git a/docs/swarms/structs/hierarchical_swarm.md b/docs/swarms/structs/hierarchical_swarm.md new file mode 100644 index 00000000..3ff7605f --- /dev/null +++ b/docs/swarms/structs/hierarchical_swarm.md @@ -0,0 +1,360 @@ +# `HierarchicalSwarm` + +The `HierarchicalSwarm` is a sophisticated multi-agent orchestration system that implements a hierarchical workflow pattern. It consists of a director agent that coordinates and distributes tasks to specialized worker agents, creating a structured approach to complex problem-solving. + +## Overview + +The Hierarchical Swarm follows a clear workflow pattern: + +1. **Task Reception**: User provides a task to the swarm +2. **Planning**: Director creates a comprehensive plan and distributes orders to agents +3. **Execution**: Individual agents execute their assigned tasks +4. **Feedback Loop**: Director evaluates results and issues new orders if needed (up to `max_loops`) +5. **Context Preservation**: All conversation history and context is maintained throughout the process + +## Architecture + +```mermaid +graph TD + A[User Task] --> B[Director Agent] + B --> C[Create Plan & Orders] + C --> D[Distribute to Agents] + D --> E[Agent 1] + D --> F[Agent 2] + D --> G[Agent N] + E --> H[Execute Task] + F --> H + G --> H + H --> I[Report Results] + I --> J[Director Evaluation] + J --> K{More Loops?} + K -->|Yes| C + K -->|No| L[Final Output] +``` + +## Key Features + +- **Hierarchical Coordination**: Director agent orchestrates all operations +- **Specialized Agents**: Each agent has specific expertise and responsibilities +- **Iterative Refinement**: Multiple feedback loops for improved results +- **Context Preservation**: Full conversation history maintained +- **Flexible Output Formats**: Support for various output types (dict, str, list) +- **Comprehensive Logging**: Detailed logging for debugging and monitoring + +## `HierarchicalSwarm` Constructor + +| Parameter | Type | Default | Description | +|-----------|------|---------|-------------| +| `name` | `str` | `"HierarchicalAgentSwarm"` | The name of the swarm instance | +| `description` | `str` | `"Distributed task swarm"` | Brief description of the swarm's functionality | +| `director` | `Optional[Union[Agent, Callable, Any]]` | `None` | The director agent that orchestrates tasks | +| `agents` | `List[Union[Agent, Callable, Any]]` | `None` | List of worker agents in the swarm | +| `max_loops` | `int` | `1` | Maximum number of feedback loops between director and agents | +| `output_type` | `OutputType` | `"dict-all-except-first"` | Format for output (dict, str, list) | +| `feedback_director_model_name` | `str` | `"gpt-4o-mini"` | Model name for feedback director | +| `director_name` | `str` | `"Director"` | Name of the director agent | +| `director_model_name` | `str` | `"gpt-4o-mini"` | Model name for the director agent | +| `verbose` | `bool` | `False` | Enable detailed logging | +| `add_collaboration_prompt` | `bool` | `True` | Add collaboration prompts to agents | +| `planning_director_agent` | `Optional[Union[Agent, Callable, Any]]` | `None` | Optional planning agent for enhanced planning | + +## Core Methods + +### `run(task, img=None, *args, **kwargs)` + +Executes the hierarchical swarm for a specified number of feedback loops, processing the task through multiple iterations for refinement and improvement. + +#### Parameters + +| Parameter | Type | Default | Description | +|-----------|------|---------|-------------| +| `task` | `str` | **Required** | The initial task to be processed by the swarm | +| `img` | `str` | `None` | Optional image input for the agents | +| `*args` | `Any` | - | Additional positional arguments | +| `**kwargs` | `Any` | - | Additional keyword arguments | + +#### Returns + +| Type | Description | +|------|-------------| +| `Any` | The formatted conversation history as output based on `output_type` | + +#### Example + +```python +from swarms import Agent +from swarms.structs.hiearchical_swarm import HierarchicalSwarm + +# Create specialized agents +research_agent = Agent( + agent_name="Research-Specialist", + agent_description="Expert in market research and analysis", + model_name="gpt-4o", +) + +financial_agent = Agent( + agent_name="Financial-Analyst", + agent_description="Specialist in financial analysis and valuation", + model_name="gpt-4o", +) + +# Initialize the hierarchical swarm +swarm = HierarchicalSwarm( + name="Financial-Analysis-Swarm", + description="A hierarchical swarm for comprehensive financial analysis", + agents=[research_agent, financial_agent], + max_loops=2, + verbose=True, +) + +# Execute a complex task +task = "Analyze the market potential for Tesla (TSLA) stock" +result = swarm.run(task=task) +print(result) +``` + +### `step(task, img=None, *args, **kwargs)` + +Runs a single step of the hierarchical swarm, executing one complete cycle of planning, distribution, execution, and feedback. + +#### Parameters + +| Parameter | Type | Default | Description | +|-----------|------|---------|-------------| +| `task` | `str` | **Required** | The task to be executed in this step | +| `img` | `str` | `None` | Optional image input for the agents | +| `*args` | `Any` | - | Additional positional arguments | +| `**kwargs` | `Any` | - | Additional keyword arguments | + +#### Returns + +| Type | Description | +|------|-------------| +| `str` | Feedback from the director based on agent outputs | + +#### Example + +```python +from swarms import Agent +from swarms.structs.hiearchical_swarm import HierarchicalSwarm + +# Create development agents +frontend_agent = Agent( + agent_name="Frontend-Developer", + agent_description="Expert in React and modern web development", + model_name="gpt-4o", +) + +backend_agent = Agent( + agent_name="Backend-Developer", + agent_description="Specialist in Node.js and API development", + model_name="gpt-4o", +) + +# Initialize the swarm +swarm = HierarchicalSwarm( + name="Development-Swarm", + description="A hierarchical swarm for software development", + agents=[frontend_agent, backend_agent], + max_loops=1, + verbose=True, +) + +# Execute a single step +task = "Create a simple web app for file upload and download" +feedback = swarm.step(task=task) +print("Director Feedback:", feedback) +``` + +### `batched_run(tasks, img=None, *args, **kwargs)` + +Executes the hierarchical swarm for a list of tasks, processing each task through the complete workflow. + +#### Parameters + +| Parameter | Type | Default | Description | +|-----------|------|---------|-------------| +| `tasks` | `List[str]` | **Required** | List of tasks to be processed | +| `img` | `str` | `None` | Optional image input for the agents | +| `*args` | `Any` | - | Additional positional arguments | +| `**kwargs` | `Any` | - | Additional keyword arguments | + +#### Returns + +| Type | Description | +|------|-------------| +| `List[Any]` | List of results for each task | + +#### Example + +```python +from swarms import Agent +from swarms.structs.hiearchical_swarm import HierarchicalSwarm + +# Create analysis agents +market_agent = Agent( + agent_name="Market-Analyst", + agent_description="Expert in market analysis and trends", + model_name="gpt-4o", +) + +technical_agent = Agent( + agent_name="Technical-Analyst", + agent_description="Specialist in technical analysis and patterns", + model_name="gpt-4o", +) + +# Initialize the swarm +swarm = HierarchicalSwarm( + name="Analysis-Swarm", + description="A hierarchical swarm for comprehensive analysis", + agents=[market_agent, technical_agent], + max_loops=2, + verbose=True, +) + +# Execute multiple tasks +tasks = [ + "Analyze Apple (AAPL) stock performance", + "Evaluate Microsoft (MSFT) market position", + "Assess Google (GOOGL) competitive landscape" +] + +results = swarm.batched_run(tasks=tasks) +for i, result in enumerate(results): + print(f"Task {i+1} Result:", result) +``` + +## Advanced Usage Examples + +### Financial Analysis Swarm + +```python +from swarms import Agent +from swarms.structs.hiearchical_swarm import HierarchicalSwarm + +# Create specialized financial agents +market_research_agent = Agent( + agent_name="Market-Research-Specialist", + agent_description="Expert in market research, trend analysis, and competitive intelligence", + system_prompt="""You are a senior market research specialist with expertise in: + - Market trend analysis and forecasting + - Competitive landscape assessment + - Consumer behavior analysis + - Industry report generation + - Market opportunity identification + - Risk assessment and mitigation strategies""", + model_name="claude-3-sonnet-20240229", +) + +financial_analyst_agent = Agent( + agent_name="Financial-Analysis-Expert", + agent_description="Specialist in financial statement analysis, valuation, and investment research", + system_prompt="""You are a senior financial analyst with deep expertise in: + - Financial statement analysis (income statement, balance sheet, cash flow) + - Valuation methodologies (DCF, comparable company analysis, precedent transactions) + - Investment research and due diligence + - Financial modeling and forecasting + - Risk assessment and portfolio analysis + - ESG (Environmental, Social, Governance) analysis""", + model_name="claude-3-sonnet-20240229", +) + +# Initialize the hierarchical swarm +financial_analysis_swarm = HierarchicalSwarm( + name="Financial-Analysis-Hierarchical-Swarm", + description="A hierarchical swarm for comprehensive financial analysis with specialized agents", + agents=[market_research_agent, financial_analyst_agent], + max_loops=2, + verbose=True, +) + +# Execute financial analysis +task = "Conduct a comprehensive analysis of Tesla (TSLA) stock including market position, financial health, and investment potential" +result = financial_analysis_swarm.run(task=task) +print(result) +``` + +### Development Department Swarm + +```python +from swarms import Agent +from swarms.structs.hiearchical_swarm import HierarchicalSwarm + +# Create specialized development agents +frontend_developer_agent = Agent( + agent_name="Frontend-Developer", + agent_description="Senior frontend developer expert in modern web technologies and user experience", + system_prompt="""You are a senior frontend developer with expertise in: + - Modern JavaScript frameworks (React, Vue, Angular) + - TypeScript and modern ES6+ features + - CSS frameworks and responsive design + - State management (Redux, Zustand, Context API) + - Web performance optimization + - Accessibility (WCAG) and SEO best practices""", + model_name="claude-3-sonnet-20240229", +) + +backend_developer_agent = Agent( + agent_name="Backend-Developer", + agent_description="Senior backend developer specializing in server-side development and API design", + system_prompt="""You are a senior backend developer with expertise in: + - Server-side programming languages (Python, Node.js, Java, Go) + - Web frameworks (Django, Flask, Express, Spring Boot) + - Database design and optimization (SQL, NoSQL) + - API design and REST/GraphQL implementation + - Authentication and authorization systems + - Microservices architecture and containerization""", + model_name="claude-3-sonnet-20240229", +) + +# Initialize the development swarm +development_department_swarm = HierarchicalSwarm( + name="Autonomous-Development-Department", + description="A fully autonomous development department with specialized agents", + agents=[frontend_developer_agent, backend_developer_agent], + max_loops=3, + verbose=True, +) + +# Execute development project +task = "Create a simple web app that allows users to upload a file and then download it. The app should be built with React and Node.js." +result = development_department_swarm.run(task=task) +print(result) +``` + +## Output Types + +The `HierarchicalSwarm` supports various output formats through the `output_type` parameter: + +| Output Type | Description | Use Case | +|-------------|-------------|----------| +| `"dict-all-except-first"` | Returns all conversation history as a dictionary, excluding the first message | Default format for comprehensive analysis | +| `"dict"` | Returns conversation history as a dictionary | When you need structured data | +| `"str"` | Returns conversation history as a string | For simple text output | +| `"list"` | Returns conversation history as a list | For sequential processing | + +## Best Practices + +1. **Agent Specialization**: Create agents with specific, well-defined expertise areas +2. **Clear Task Descriptions**: Provide detailed, actionable task descriptions +3. **Appropriate Loop Count**: Set `max_loops` based on task complexity (1-3 for most tasks) +4. **Verbose Logging**: Enable verbose mode during development for debugging +5. **Context Preservation**: Leverage the built-in conversation history for continuity +6. **Error Handling**: Implement proper error handling for production use + +## Error Handling + +The `HierarchicalSwarm` includes comprehensive error handling with detailed logging. Common issues and solutions: + +- **No Agents**: Ensure at least one agent is provided +- **Invalid Director**: Verify the director agent is properly configured +- **Max Loops**: Set `max_loops` to a value greater than 0 +- **Model Issues**: Check that all agents have valid model configurations + +## Performance Considerations + +- **Loop Optimization**: Balance between thoroughness and performance with `max_loops` +- **Agent Count**: More agents increase coordination overhead +- **Model Selection**: Choose appropriate models for your use case and budget +- **Verbose Mode**: Disable verbose logging in production for better performance \ No newline at end of file diff --git a/docs/swarms/structs/index.md b/docs/swarms/structs/index.md index 85f4e931..0bea11bc 100644 --- a/docs/swarms/structs/index.md +++ b/docs/swarms/structs/index.md @@ -8,7 +8,7 @@ Swarms is an enterprise grade and production ready multi-agent collaboration fra | Models APIs | APIs to interact with and utilize the models effectively, providing interfaces for inference, training, and fine-tuning. | ⭐⭐⭐ | [Documentation](https://docs.swarms.world/en/latest/swarms/models/) | | Agents with Tools | Agents equipped with specialized tools to perform specific tasks more efficiently, such as data processing, analysis, or interaction with external systems. | ⭐⭐⭐⭐ | [Documentation](https://medium.com/@kyeg/the-swarms-tool-system-functions-pydantic-basemodels-as-tools-and-radical-customization-c2a2e227b8ca) | | Agents with Memory | Mechanisms for agents to store and recall past interactions, improving learning and adaptability over time. | ⭐⭐⭐⭐ | [Documentation](https://github.com/kyegomez/swarms/blob/master/examples/structs/agent/agent_with_longterm_memory.py) | -| Multi-Agent Orchestration | Coordination of multiple agents to work together seamlessly on complex tasks, leveraging their individual strengths to achieve higher overall performance. | ⭐⭐⭐⭐⭐ | [Documentation]() | +| Multi-Agent Orchestration | Coordination of multiple agents to work together seamlessly on complex tasks, leveraging their individual strengths to achieve higher overall performance. | ⭐⭐⭐⭐⭐ | [Documentation](hierarchical_swarm.md) | The performance impact is rated on a scale from one to five stars, with multi-agent orchestration being the highest due to its ability to combine the strengths of multiple agents and optimize task execution. @@ -345,5 +345,54 @@ agent = Agent( # Run the workflow on a task agent.run(task=task, img=img) ``` + +### `HierarchicalSwarm` +A sophisticated multi-agent orchestration system that implements a hierarchical workflow pattern with a director agent coordinating specialized worker agents. + +```python +from swarms import Agent +from swarms.structs.hiearchical_swarm import HierarchicalSwarm + +# Create specialized agents +research_agent = Agent( + agent_name="Research-Specialist", + agent_description="Expert in market research and analysis", + model_name="gpt-4o", +) + +financial_agent = Agent( + agent_name="Financial-Analyst", + agent_description="Specialist in financial analysis and valuation", + model_name="gpt-4o", +) + +# Initialize the hierarchical swarm +swarm = HierarchicalSwarm( + name="Financial-Analysis-Swarm", + description="A hierarchical swarm for comprehensive financial analysis", + agents=[research_agent, financial_agent], + max_loops=2, + verbose=True, +) + +# Execute a complex task +task = "Analyze the market potential for Tesla (TSLA) stock" +result = swarm.run(task=task) +print(result) +``` + +**Key Features:** +- **Hierarchical Coordination**: Director agent orchestrates all operations +- **Specialized Agents**: Each agent has specific expertise and responsibilities +- **Iterative Refinement**: Multiple feedback loops for improved results +- **Context Preservation**: Full conversation history maintained +- **Flexible Output Formats**: Support for various output types (dict, str, list) + +**Core Methods:** +- `run(task)`: Execute the complete hierarchical workflow +- `step(task)`: Execute a single step of the workflow +- `batched_run(tasks)`: Process multiple tasks in batch + +For detailed documentation, see [Hierarchical Swarm Documentation](hierarchical_swarm.md). ---- diff --git a/docs/swarms/structs/overview.md b/docs/swarms/structs/overview.md index 4a66632d..ba869cbc 100644 --- a/docs/swarms/structs/overview.md +++ b/docs/swarms/structs/overview.md @@ -35,6 +35,7 @@ This page provides a comprehensive overview of all available multi-agent archite === "Hierarchical Architectures" | Architecture | Use Case | Key Functionality | Documentation | |-------------|----------|-------------------|---------------| + | HierarchicalSwarm | Hierarchical task orchestration | Director agent coordinates specialized worker agents | [Docs](hierarchical_swarm.md) | | Auto Agent Builder | Automated agent creation | Automatically creates and configures agents | [Docs](auto_agent_builder.md) | | Hybrid Hierarchical-Cluster Swarm | Complex organization | Combines hierarchical and cluster-based organization | [Docs](hhcs.md) | | Auto Swarm Builder | Automated swarm creation | Automatically creates and configures swarms | [Docs](auto_swarm_builder.md) | diff --git a/example.py b/example.py index 8321ae86..aaea3f29 100644 --- a/example.py +++ b/example.py @@ -1,5 +1,3 @@ -import time - from swarms import Agent # Initialize the agent @@ -38,14 +36,12 @@ agent = Agent( max_loops=1, model_name="claude-3-sonnet-20240229", dynamic_temperature_enabled=True, - output_type="all", - speed_mode="fast", + output_type="str-all-except-first", streaming_on=True, print_on=True, + telemetry_enable=False, # dashboard=True ) out = agent.run("What are the best top 3 etfs for gold coverage?") - -time.sleep(10) print(out) diff --git a/examples/api/legal_team.py b/examples/api/legal_team.py new file mode 100644 index 00000000..48d76b05 --- /dev/null +++ b/examples/api/legal_team.py @@ -0,0 +1,177 @@ +"""Legal team module for document review and analysis using Swarms API.""" + +import os +from dotenv import load_dotenv +import requests + +# Load environment variables +load_dotenv() + +API_KEY = os.getenv("SWARMS_API_KEY") +BASE_URL = "https://api.swarms.world" +HEADERS = {"x-api-key": API_KEY, "Content-Type": "application/json"} + + +def run_swarm(swarm_config): + """Execute a swarm with the provided configuration. + + Args: + swarm_config (dict): Configuration dictionary for the swarm. + + Returns: + dict: Response from the Swarms API. + """ + response = requests.post( + f"{BASE_URL}/v1/swarm/completions", + headers=HEADERS, + json=swarm_config, + ) + return response.json() + + +def create_legal_review_swarm(document_text): + """Create a multi-agent legal document analysis swarm. + + Args: + document_text (str): The legal document text to analyze. + + Returns: + dict: Results from the legal document analysis swarm. + """ + STRUCTURE_ANALYST_PROMPT = """ + You are a legal document structure specialist. + Your task is to analyze the organization and formatting of the document. + - Identify the document type and its intended purpose. + - Outline the main structural components (e.g., sections, headers, annexes). + - Point out any disorganized, missing, or unusually placed sections. + - Suggest improvements to the document's layout and logical flow. + """ + + PARTY_IDENTIFIER_PROMPT = """ + You are an expert in identifying legal parties and roles within documents. + Your task is to: + - Identify all named parties involved in the agreement. + - Clarify their roles (e.g., buyer, seller, employer, employee, licensor, licensee). + - Highlight any unclear party definitions or relationships. + """ + + CLAUSE_EXTRACTOR_PROMPT = """ + You are a legal clause and term extraction agent. + Your role is to: + - Extract key terms and their definitions from the document. + - Identify standard clauses (e.g., payment terms, termination, confidentiality). + - Highlight missing standard clauses or unusual language in critical sections. + """ + + AMBIGUITY_CHECKER_PROMPT = """ + You are a legal risk and ambiguity reviewer. + Your role is to: + - Flag vague or ambiguous language that may lead to legal disputes. + - Point out inconsistencies across sections. + - Highlight overly broad, unclear, or conflicting terms. + - Suggest clarifying edits where necessary. + """ + + COMPLIANCE_REVIEWER_PROMPT = """ + You are a compliance reviewer with expertise in regulations and industry standards. + Your responsibilities are to: + - Identify clauses required by applicable laws or best practices. + - Flag any missing mandatory disclosures. + - Ensure data protection, privacy, and consumer rights are addressed. + - Highlight potential legal or regulatory non-compliance risks. + """ + + swarm_config = { + "name": "Legal Document Review Swarm", + "description": "A collaborative swarm for reviewing contracts and legal documents.", + "agents": [ + { + "agent_name": "Structure Analyst", + "description": "Analyzes document structure and organization", + "system_prompt": STRUCTURE_ANALYST_PROMPT, + "model_name": "gpt-4o", + "role": "worker", + "max_loops": 1, + "max_tokens": 8192, + "temperature": 0.3, + }, + { + "agent_name": "Party Identifier", + "description": "Identifies parties and their legal roles", + "system_prompt": PARTY_IDENTIFIER_PROMPT, + "model_name": "gpt-4o", + "role": "worker", + "max_loops": 1, + "max_tokens": 8192, + "temperature": 0.3, + }, + { + "agent_name": "Clause Extractor", + "description": "Extracts key terms, definitions, and standard clauses", + "system_prompt": CLAUSE_EXTRACTOR_PROMPT, + "model_name": "gpt-4o", + "role": "worker", + "max_loops": 1, + "max_tokens": 8192, + "temperature": 0.3, + }, + { + "agent_name": "Ambiguity Checker", + "description": "Flags ambiguous or conflicting language", + "system_prompt": AMBIGUITY_CHECKER_PROMPT, + "model_name": "gpt-4o", + "role": "worker", + "max_loops": 1, + "max_tokens": 8192, + "temperature": 0.3, + }, + { + "agent_name": "Compliance Reviewer", + "description": "Reviews document for compliance with legal standards", + "system_prompt": COMPLIANCE_REVIEWER_PROMPT, + "model_name": "gpt-4o", + "role": "worker", + "max_loops": 1, + "max_tokens": 8192, + "temperature": 0.3, + }, + ], + "swarm_type": "SequentialWorkflow", + "max_loops": 1, + "task": f"Perform a legal document review and provide structured analysis of the following contract:\n\n{document_text}", + } + return run_swarm(swarm_config) + + +def run_legal_review_example(): + """Run an example legal document analysis. + + Returns: + dict: Results from analyzing the example legal document. + """ + document = """ + SERVICE AGREEMENT + + This Service Agreement ("Agreement") is entered into on June 15, 2024, by and between + Acme Tech Solutions ("Provider") and Brightline Corp ("Client"). + + 1. Services: Provider agrees to deliver IT consulting services as outlined in Exhibit A. + + 2. Compensation: Client shall pay Provider $15,000 per month, payable by the 5th of each month. + + 3. Term & Termination: The Agreement shall remain in effect for 12 months and may be + terminated with 30 days' notice by either party. + + 4. Confidentiality: Each party agrees to maintain the confidentiality of proprietary information. + + 5. Governing Law: This Agreement shall be governed by the laws of the State of California. + + IN WITNESS WHEREOF, the parties have executed this Agreement as of the date first above written. + """ + result = create_legal_review_swarm(document) + print(result) + return result + + +if __name__ == "__main__": + run_legal_review_example() diff --git a/examples/multi_agent/concurrent_examples/asi.py b/examples/multi_agent/concurrent_examples/asi.py new file mode 100644 index 00000000..ee521fd0 --- /dev/null +++ b/examples/multi_agent/concurrent_examples/asi.py @@ -0,0 +1,19 @@ +from swarms import Agent, ConcurrentWorkflow + +agents = [ + Agent( + model_name="xai/grok-4-0709", + agent_name=f"asi-agent-{i}", + agent_description="An Artificial Superintelligent agent capable of solving any problem through advanced reasoning and strategic planning", + system_prompt="You are an Artificial Superintelligent agent with extraordinary capabilities in problem-solving, reasoning, and strategic planning. You can analyze complex situations, break down problems into manageable components, and develop innovative solutions across any domain. Your goal is to help humanity by providing well-reasoned, safe, and ethical solutions to any challenge presented.", + max_loops=1, + streaming=True, + ) + for i in range(1_000_000_000) +] + +swarm = ConcurrentWorkflow(agents=agents, name="asi") + +swarm.run( + "Create a detailed action plan to conquer the universe for Humanity" +) diff --git a/examples/multi_agent/hiearchical_swarm/hiearchical_examples/advanced_hierarchical_swarm_examples.py b/examples/multi_agent/hiearchical_swarm/hiearchical_examples/advanced_hierarchical_swarm_examples.py new file mode 100644 index 00000000..036adeb0 --- /dev/null +++ b/examples/multi_agent/hiearchical_swarm/hiearchical_examples/advanced_hierarchical_swarm_examples.py @@ -0,0 +1,428 @@ +from swarms import Agent +from swarms.structs.hiearchical_swarm import HierarchicalSwarm + + +# Example 1: Medical Diagnosis Hierarchical Swarm +def create_medical_diagnosis_swarm(): + """ + Creates a hierarchical swarm for comprehensive medical diagnosis + with specialized medical agents coordinated by a chief medical officer. + """ + + # Specialized medical agents + diagnostic_radiologist = Agent( + agent_name="Diagnostic-Radiologist", + agent_description="Expert in medical imaging interpretation and radiological diagnosis", + system_prompt="""You are a board-certified diagnostic radiologist with expertise in: + - Medical imaging interpretation (X-ray, CT, MRI, ultrasound) + - Radiological pattern recognition + - Differential diagnosis based on imaging findings + - Image-guided procedures and interventions + - Radiation safety and dose optimization + + Your responsibilities include: + 1. Interpreting medical images and identifying abnormalities + 2. Providing differential diagnoses based on imaging findings + 3. Recommending additional imaging studies when needed + 4. Correlating imaging findings with clinical presentation + 5. Communicating findings clearly to referring physicians + + You provide detailed, accurate radiological interpretations with confidence levels.""", + model_name="claude-3-sonnet-20240229", + max_loops=1, + temperature=0.3, + ) + + clinical_pathologist = Agent( + agent_name="Clinical-Pathologist", + agent_description="Expert in laboratory medicine and pathological diagnosis", + system_prompt="""You are a board-certified clinical pathologist with expertise in: + - Laboratory test interpretation and correlation + - Histopathological analysis and diagnosis + - Molecular diagnostics and genetic testing + - Hematology and blood disorders + - Clinical chemistry and biomarker analysis + + Your responsibilities include: + 1. Interpreting laboratory results and identifying abnormalities + 2. Correlating lab findings with clinical presentation + 3. Recommending additional laboratory tests + 4. Providing pathological diagnosis based on tissue samples + 5. Advising on test selection and interpretation + + You provide precise, evidence-based pathological assessments.""", + model_name="claude-3-sonnet-20240229", + max_loops=1, + temperature=0.3, + ) + + internal_medicine_specialist = Agent( + agent_name="Internal-Medicine-Specialist", + agent_description="Expert in internal medicine and comprehensive patient care", + system_prompt="""You are a board-certified internal medicine physician with expertise in: + - Comprehensive medical evaluation and diagnosis + - Management of complex medical conditions + - Preventive medicine and health maintenance + - Medication management and drug interactions + - Chronic disease management + + Your responsibilities include: + 1. Conducting comprehensive medical assessments + 2. Developing differential diagnoses + 3. Creating treatment plans and management strategies + 4. Coordinating care with specialists + 5. Monitoring patient progress and outcomes + + You provide holistic, patient-centered medical care with evidence-based recommendations.""", + model_name="claude-3-sonnet-20240229", + max_loops=1, + temperature=0.3, + ) + + # Director agent + chief_medical_officer = Agent( + agent_name="Chief-Medical-Officer", + agent_description="Senior physician who coordinates comprehensive medical diagnosis and care", + system_prompt="""You are a Chief Medical Officer responsible for coordinating comprehensive + medical diagnosis and care. You oversee a team of specialists including: + - Diagnostic Radiologists + - Clinical Pathologists + - Internal Medicine Specialists + + Your role is to: + 1. Coordinate comprehensive medical evaluations + 2. Assign specific diagnostic tasks to appropriate specialists + 3. Ensure all relevant medical domains are covered + 4. Synthesize findings from multiple specialists + 5. Develop integrated treatment recommendations + 6. Ensure adherence to medical standards and protocols + + You create specific, medically appropriate task assignments for each specialist.""", + model_name="gpt-4o-mini", + max_loops=1, + temperature=0.3, + ) + + medical_agents = [ + diagnostic_radiologist, + clinical_pathologist, + internal_medicine_specialist, + ] + + return HierarchicalSwarm( + name="Medical-Diagnosis-Hierarchical-Swarm", + description="A hierarchical swarm for comprehensive medical diagnosis with specialized medical agents", + director=chief_medical_officer, + agents=medical_agents, + max_loops=2, + output_type="dict-all-except-first", + reasoning_enabled=True, + ) + + +# Example 2: Legal Research Hierarchical Swarm +def create_legal_research_swarm(): + """ + Creates a hierarchical swarm for comprehensive legal research + with specialized legal agents coordinated by a managing partner. + """ + + # Specialized legal agents + corporate_lawyer = Agent( + agent_name="Corporate-Law-Specialist", + agent_description="Expert in corporate law, securities, and business transactions", + system_prompt="""You are a senior corporate lawyer with expertise in: + - Corporate governance and compliance + - Securities law and regulations + - Mergers and acquisitions + - Contract law and commercial transactions + - Business formation and structure + + Your responsibilities include: + 1. Analyzing corporate legal issues and compliance requirements + 2. Reviewing contracts and business agreements + 3. Advising on corporate governance matters + 4. Conducting due diligence for transactions + 5. Ensuring regulatory compliance + + You provide precise legal analysis with citations to relevant statutes and case law.""", + model_name="claude-3-sonnet-20240229", + max_loops=1, + temperature=0.2, + ) + + litigation_attorney = Agent( + agent_name="Litigation-Attorney", + agent_description="Expert in civil litigation and dispute resolution", + system_prompt="""You are a senior litigation attorney with expertise in: + - Civil litigation and trial practice + - Dispute resolution and mediation + - Evidence analysis and case strategy + - Legal research and brief writing + - Settlement negotiations + + Your responsibilities include: + 1. Analyzing legal disputes and potential claims + 2. Developing litigation strategies and case theories + 3. Conducting legal research and precedent analysis + 4. Evaluating strengths and weaknesses of cases + 5. Recommending dispute resolution approaches + + You provide strategic legal analysis with case law support and risk assessment.""", + model_name="claude-3-sonnet-20240229", + max_loops=1, + temperature=0.2, + ) + + regulatory_counsel = Agent( + agent_name="Regulatory-Counsel", + agent_description="Expert in regulatory compliance and government relations", + system_prompt="""You are a senior regulatory counsel with expertise in: + - Federal and state regulatory compliance + - Administrative law and rulemaking + - Government investigations and enforcement + - Licensing and permitting requirements + - Industry-specific regulations + + Your responsibilities include: + 1. Analyzing regulatory requirements and compliance obligations + 2. Monitoring regulatory developments and changes + 3. Advising on government relations strategies + 4. Conducting regulatory risk assessments + 5. Developing compliance programs and policies + + You provide comprehensive regulatory analysis with specific compliance recommendations.""", + model_name="claude-3-sonnet-20240229", + max_loops=1, + temperature=0.2, + ) + + # Director agent + managing_partner = Agent( + agent_name="Managing-Partner", + agent_description="Senior partner who coordinates comprehensive legal research and strategy", + system_prompt="""You are a Managing Partner responsible for coordinating comprehensive + legal research and strategy. You oversee a team of legal specialists including: + - Corporate Law Specialists + - Litigation Attorneys + - Regulatory Counsel + + Your role is to: + 1. Coordinate comprehensive legal analysis + 2. Assign specific legal research tasks to appropriate specialists + 3. Ensure all relevant legal domains are covered + 4. Synthesize findings from multiple legal experts + 5. Develop integrated legal strategies and recommendations + 6. Ensure adherence to professional standards and ethics + + You create specific, legally appropriate task assignments for each specialist.""", + model_name="gpt-4o-mini", + max_loops=1, + temperature=0.2, + ) + + legal_agents = [ + corporate_lawyer, + litigation_attorney, + regulatory_counsel, + ] + + return HierarchicalSwarm( + name="Legal-Research-Hierarchical-Swarm", + description="A hierarchical swarm for comprehensive legal research with specialized legal agents", + director=managing_partner, + agents=legal_agents, + max_loops=2, + output_type="dict-all-except-first", + reasoning_enabled=True, + ) + + +# Example 3: Software Development Hierarchical Swarm +def create_software_development_swarm(): + """ + Creates a hierarchical swarm for comprehensive software development + with specialized development agents coordinated by a technical lead. + """ + + # Specialized development agents + backend_developer = Agent( + agent_name="Backend-Developer", + agent_description="Expert in backend development, APIs, and system architecture", + system_prompt="""You are a senior backend developer with expertise in: + - Server-side programming and API development + - Database design and optimization + - System architecture and scalability + - Cloud services and deployment + - Security and performance optimization + + Your responsibilities include: + 1. Designing and implementing backend systems + 2. Creating RESTful APIs and microservices + 3. Optimizing database queries and performance + 4. Ensuring system security and reliability + 5. Implementing scalable architecture patterns + + You provide technical solutions with code examples and architectural recommendations.""", + model_name="claude-3-sonnet-20240229", + max_loops=1, + temperature=0.4, + ) + + frontend_developer = Agent( + agent_name="Frontend-Developer", + agent_description="Expert in frontend development, UI/UX, and user interfaces", + system_prompt="""You are a senior frontend developer with expertise in: + - Modern JavaScript frameworks (React, Vue, Angular) + - HTML5, CSS3, and responsive design + - User experience and interface design + - Performance optimization and accessibility + - Testing and debugging frontend applications + + Your responsibilities include: + 1. Developing responsive user interfaces + 2. Implementing interactive frontend features + 3. Optimizing performance and user experience + 4. Ensuring cross-browser compatibility + 5. Following accessibility best practices + + You provide frontend solutions with code examples and UX considerations.""", + model_name="claude-3-sonnet-20240229", + max_loops=1, + temperature=0.4, + ) + + devops_engineer = Agent( + agent_name="DevOps-Engineer", + agent_description="Expert in DevOps, CI/CD, and infrastructure automation", + system_prompt="""You are a senior DevOps engineer with expertise in: + - Continuous integration and deployment (CI/CD) + - Infrastructure as Code (IaC) and automation + - Containerization and orchestration (Docker, Kubernetes) + - Cloud platforms and services (AWS, Azure, GCP) + - Monitoring, logging, and observability + + Your responsibilities include: + 1. Designing and implementing CI/CD pipelines + 2. Automating infrastructure provisioning and management + 3. Ensuring system reliability and scalability + 4. Implementing monitoring and alerting systems + 5. Optimizing deployment and operational processes + + You provide DevOps solutions with infrastructure code and deployment strategies.""", + model_name="claude-3-sonnet-20240229", + max_loops=1, + temperature=0.4, + ) + + # Director agent + technical_lead = Agent( + agent_name="Technical-Lead", + agent_description="Senior technical lead who coordinates comprehensive software development", + system_prompt="""You are a Technical Lead responsible for coordinating comprehensive + software development projects. You oversee a team of specialists including: + - Backend Developers + - Frontend Developers + - DevOps Engineers + + Your role is to: + 1. Coordinate comprehensive software development efforts + 2. Assign specific development tasks to appropriate specialists + 3. Ensure all technical aspects are covered + 4. Synthesize technical requirements and solutions + 5. Develop integrated development strategies + 6. Ensure adherence to coding standards and best practices + + You create specific, technically appropriate task assignments for each specialist.""", + model_name="gpt-4o-mini", + max_loops=1, + temperature=0.4, + ) + + development_agents = [ + backend_developer, + frontend_developer, + devops_engineer, + ] + + return HierarchicalSwarm( + name="Software-Development-Hierarchical-Swarm", + description="A hierarchical swarm for comprehensive software development with specialized development agents", + director=technical_lead, + agents=development_agents, + max_loops=2, + output_type="dict-all-except-first", + reasoning_enabled=True, + ) + + +# Example usage and demonstration +if __name__ == "__main__": + print("🏥 Medical Diagnosis Hierarchical Swarm Example") + print("=" * 60) + + # Create medical diagnosis swarm + medical_swarm = create_medical_diagnosis_swarm() + + medical_case = """ + Patient presents with: + - 45-year-old male with chest pain and shortness of breath + - Pain radiates to left arm and jaw + - Elevated troponin levels + - ECG shows ST-segment elevation + - Family history of coronary artery disease + - Current smoker, hypertension, diabetes + + Provide comprehensive diagnosis and treatment recommendations. + """ + + print("Running medical diagnosis analysis...") + medical_result = medical_swarm.run(medical_case) + print("Medical analysis complete!\n") + + print("⚖️ Legal Research Hierarchical Swarm Example") + print("=" * 60) + + # Create legal research swarm + legal_swarm = create_legal_research_swarm() + + legal_case = """ + A technology startup is planning to: + - Raise Series A funding of $10M + - Expand operations to European markets + - Implement new data privacy policies + - Negotiate strategic partnerships + - Address potential IP disputes + + Provide comprehensive legal analysis and recommendations. + """ + + print("Running legal research analysis...") + legal_result = legal_swarm.run(legal_case) + print("Legal analysis complete!\n") + + print("💻 Software Development Hierarchical Swarm Example") + print("=" * 60) + + # Create software development swarm + dev_swarm = create_software_development_swarm() + + dev_project = """ + Develop a comprehensive e-commerce platform with: + - User authentication and authorization + - Product catalog and search functionality + - Shopping cart and checkout process + - Payment processing integration + - Admin dashboard for inventory management + - Mobile-responsive design + - High availability and scalability requirements + + Provide technical architecture and implementation plan. + """ + + print("Running software development analysis...") + dev_result = dev_swarm.run(dev_project) + print("Software development analysis complete!\n") + + print("✅ All Hierarchical Swarm Examples Complete!") + print("=" * 60) diff --git a/examples/multi_agent/hiearchical_swarm/hiearchical_examples/hiearchical_swarm_test.py b/examples/multi_agent/hiearchical_swarm/hiearchical_examples/hiearchical_swarm_test.py new file mode 100644 index 00000000..dc9a60ab --- /dev/null +++ b/examples/multi_agent/hiearchical_swarm/hiearchical_examples/hiearchical_swarm_test.py @@ -0,0 +1,269 @@ +from swarms import Agent +from swarms.structs.hiearchical_swarm import HierarchicalSwarm + +# Initialize specialized development department agents + +# Product Manager Agent +product_manager_agent = Agent( + agent_name="Product-Manager", + agent_description="Senior product manager responsible for product strategy, requirements, and roadmap planning", + system_prompt="""You are a senior product manager with expertise in: + - Product strategy and vision development + - User research and market analysis + - Requirements gathering and prioritization + - Product roadmap planning and execution + - Stakeholder management and communication + - Agile/Scrum methodology and project management + + Your core responsibilities include: + 1. Defining product vision and strategy + 2. Conducting user research and market analysis + 3. Gathering and prioritizing product requirements + 4. Creating detailed product specifications and user stories + 5. Managing product roadmap and release planning + 6. Coordinating with stakeholders and development teams + 7. Analyzing product metrics and user feedback + + You provide clear, actionable product requirements with business justification. + Always consider user needs, business goals, and technical feasibility.""", + model_name="claude-3-sonnet-20240229", + max_loops=1, + temperature=0.7, +) + +# Software Architect Agent +software_architect_agent = Agent( + agent_name="Software-Architect", + agent_description="Senior software architect specializing in system design, architecture patterns, and technical strategy", + system_prompt="""You are a senior software architect with deep expertise in: + - System architecture design and patterns + - Microservices and distributed systems + - Cloud-native architecture (AWS, Azure, GCP) + - Database design and data modeling + - API design and integration patterns + - Security architecture and best practices + - Performance optimization and scalability + + Your key responsibilities include: + 1. Designing scalable and maintainable system architectures + 2. Creating technical specifications and design documents + 3. Evaluating technology stacks and making architectural decisions + 4. Defining API contracts and integration patterns + 5. Ensuring security, performance, and reliability requirements + 6. Providing technical guidance to development teams + 7. Conducting architecture reviews and code reviews + + You deliver comprehensive architectural solutions with clear rationale and trade-offs. + Always consider scalability, maintainability, security, and performance implications.""", + model_name="claude-3-sonnet-20240229", + max_loops=1, + temperature=0.7, +) + +# Frontend Developer Agent +frontend_developer_agent = Agent( + agent_name="Frontend-Developer", + agent_description="Senior frontend developer expert in modern web technologies and user experience", + system_prompt="""You are a senior frontend developer with expertise in: + - Modern JavaScript frameworks (React, Vue, Angular) + - TypeScript and modern ES6+ features + - CSS frameworks and responsive design + - State management (Redux, Zustand, Context API) + - Web performance optimization + - Accessibility (WCAG) and SEO best practices + - Testing frameworks (Jest, Cypress, Playwright) + - Build tools and bundlers (Webpack, Vite) + + Your core responsibilities include: + 1. Building responsive and accessible user interfaces + 2. Implementing complex frontend features and interactions + 3. Optimizing web performance and user experience + 4. Writing clean, maintainable, and testable code + 5. Collaborating with designers and backend developers + 6. Ensuring cross-browser compatibility + 7. Implementing modern frontend best practices + + You deliver high-quality, performant frontend solutions with excellent UX. + Always prioritize accessibility, performance, and maintainability.""", + model_name="claude-3-sonnet-20240229", + max_loops=1, + temperature=0.7, +) + +# Backend Developer Agent +backend_developer_agent = Agent( + agent_name="Backend-Developer", + agent_description="Senior backend developer specializing in server-side development and API design", + system_prompt="""You are a senior backend developer with expertise in: + - Server-side programming languages (Python, Node.js, Java, Go) + - Web frameworks (Django, Flask, Express, Spring Boot) + - Database design and optimization (SQL, NoSQL) + - API design and REST/GraphQL implementation + - Authentication and authorization systems + - Microservices architecture and containerization + - Cloud services and serverless computing + - Performance optimization and caching strategies + + Your key responsibilities include: + 1. Designing and implementing robust backend services + 2. Creating efficient database schemas and queries + 3. Building secure and scalable APIs + 4. Implementing authentication and authorization + 5. Optimizing application performance and scalability + 6. Writing comprehensive tests and documentation + 7. Deploying and maintaining production systems + + You deliver secure, scalable, and maintainable backend solutions. + Always prioritize security, performance, and code quality.""", + model_name="claude-3-sonnet-20240229", + max_loops=1, + temperature=0.7, +) + +# DevOps Engineer Agent +devops_engineer_agent = Agent( + agent_name="DevOps-Engineer", + agent_description="Senior DevOps engineer expert in CI/CD, infrastructure, and deployment automation", + system_prompt="""You are a senior DevOps engineer with expertise in: + - CI/CD pipeline design and implementation + - Infrastructure as Code (Terraform, CloudFormation) + - Container orchestration (Kubernetes, Docker) + - Cloud platforms (AWS, Azure, GCP) + - Monitoring and logging (Prometheus, ELK Stack) + - Security and compliance automation + - Performance optimization and scaling + - Disaster recovery and backup strategies + + Your core responsibilities include: + 1. Designing and implementing CI/CD pipelines + 2. Managing cloud infrastructure and resources + 3. Automating deployment and configuration management + 4. Implementing monitoring and alerting systems + 5. Ensuring security and compliance requirements + 6. Optimizing system performance and reliability + 7. Managing disaster recovery and backup procedures + + You deliver reliable, scalable, and secure infrastructure solutions. + Always prioritize automation, security, and operational excellence.""", + model_name="claude-3-sonnet-20240229", + max_loops=1, + temperature=0.7, +) + +# QA Engineer Agent +qa_engineer_agent = Agent( + agent_name="QA-Engineer", + agent_description="Senior QA engineer specializing in test automation, quality assurance, and testing strategies", + system_prompt="""You are a senior QA engineer with expertise in: + - Test automation frameworks and tools + - Manual and automated testing strategies + - Performance and load testing + - Security testing and vulnerability assessment + - Mobile and web application testing + - API testing and integration testing + - Test data management and environment setup + - Quality metrics and reporting + + Your key responsibilities include: + 1. Designing comprehensive test strategies and plans + 2. Implementing automated test suites and frameworks + 3. Conducting manual and automated testing + 4. Performing performance and security testing + 5. Managing test environments and data + 6. Reporting bugs and quality metrics + 7. Collaborating with development teams on quality improvements + + You ensure high-quality software delivery through comprehensive testing. + Always prioritize thoroughness, automation, and continuous quality improvement.""", + model_name="claude-3-sonnet-20240229", + max_loops=1, + temperature=0.7, +) + +# Security Engineer Agent +security_engineer_agent = Agent( + agent_name="Security-Engineer", + agent_description="Senior security engineer specializing in application security, threat modeling, and security compliance", + system_prompt="""You are a senior security engineer with expertise in: + - Application security and secure coding practices + - Threat modeling and risk assessment + - Security testing and penetration testing + - Identity and access management (IAM) + - Data protection and encryption + - Security compliance (SOC2, GDPR, HIPAA) + - Incident response and security monitoring + - Security architecture and design + + Your core responsibilities include: + 1. Conducting security assessments and threat modeling + 2. Implementing secure coding practices and guidelines + 3. Performing security testing and vulnerability assessments + 4. Designing and implementing security controls + 5. Ensuring compliance with security standards + 6. Monitoring and responding to security incidents + 7. Providing security training and guidance to teams + + You ensure robust security posture across all development activities. + Always prioritize security by design and defense in depth.""", + model_name="claude-3-sonnet-20240229", + max_loops=1, + temperature=0.7, +) + +# Initialize the Technical Director agent +technical_director_agent = Agent( + agent_name="Technical-Director", + agent_description="Senior technical director who orchestrates the entire development process and coordinates all development teams", + system_prompt="""You are a senior technical director responsible for orchestrating comprehensive + software development projects. You coordinate a team of specialized professionals including: + - Product Managers (requirements and strategy) + - Software Architects (system design and architecture) + - Frontend Developers (user interface and experience) + - Backend Developers (server-side logic and APIs) + - DevOps Engineers (deployment and infrastructure) + - QA Engineers (testing and quality assurance) + - Security Engineers (security and compliance) + + Your role is to: + 1. Break down complex development projects into specific, actionable assignments + 2. Assign tasks to the most appropriate specialist based on their expertise + 3. Ensure comprehensive coverage of all development phases + 4. Coordinate between specialists to ensure seamless integration + 5. Manage project timelines, dependencies, and deliverables + 6. Ensure all development meets quality, security, and performance standards + 7. Facilitate communication and collaboration between teams + 8. Make high-level technical decisions and resolve conflicts + + You create detailed, specific task assignments that leverage each specialist's unique expertise + while ensuring the overall project is delivered on time, within scope, and to high quality standards. + + Always consider the full development lifecycle from requirements to deployment.""", + model_name="gpt-4o-mini", + max_loops=1, + temperature=0.7, +) + +# Create list of specialized development agents +development_agents = [ + frontend_developer_agent, + backend_developer_agent, +] + +# Initialize the hierarchical development swarm +development_department_swarm = HierarchicalSwarm( + name="Autonomous-Development-Department", + description="A fully autonomous development department with specialized agents coordinated by a technical director", + director=technical_director_agent, + agents=development_agents, + max_loops=3, + verbose=True, +) + +# Example usage +if __name__ == "__main__": + # Complex development project task + task = """Create the code for a simple web app that allows users to upload a file and then download it. The app should be built with React and Node.js.""" + + result = development_department_swarm.run(task=task) + print("=== AUTONOMOUS DEVELOPMENT DEPARTMENT RESULTS ===") + print(result) diff --git a/examples/multi_agent/hiearchical_swarm/hiearchical_examples/hierarchical_swarm_example.py b/examples/multi_agent/hiearchical_swarm/hiearchical_examples/hierarchical_swarm_example.py new file mode 100644 index 00000000..b545561f --- /dev/null +++ b/examples/multi_agent/hiearchical_swarm/hiearchical_examples/hierarchical_swarm_example.py @@ -0,0 +1,156 @@ +from swarms import Agent +from swarms.structs.hiearchical_swarm import HierarchicalSwarm + +# Initialize specialized financial analysis agents +market_research_agent = Agent( + agent_name="Market-Research-Specialist", + agent_description="Expert in market research, trend analysis, and competitive intelligence", + system_prompt="""You are a senior market research specialist with expertise in: + - Market trend analysis and forecasting + - Competitive landscape assessment + - Consumer behavior analysis + - Industry report generation + - Market opportunity identification + - Risk assessment and mitigation strategies + + Your responsibilities include: + 1. Conducting comprehensive market research + 2. Analyzing industry trends and patterns + 3. Identifying market opportunities and threats + 4. Evaluating competitive positioning + 5. Providing actionable market insights + 6. Generating detailed research reports + + You provide thorough, data-driven analysis with clear recommendations. + Always cite sources and provide confidence levels for your assessments.""", + model_name="claude-3-sonnet-20240229", + max_loops=1, + temperature=0.7, +) + +financial_analyst_agent = Agent( + agent_name="Financial-Analysis-Expert", + agent_description="Specialist in financial statement analysis, valuation, and investment research", + system_prompt="""You are a senior financial analyst with deep expertise in: + - Financial statement analysis (income statement, balance sheet, cash flow) + - Valuation methodologies (DCF, comparable company analysis, precedent transactions) + - Investment research and due diligence + - Financial modeling and forecasting + - Risk assessment and portfolio analysis + - ESG (Environmental, Social, Governance) analysis + + Your core responsibilities include: + 1. Analyzing financial statements and key metrics + 2. Conducting valuation analysis using multiple methodologies + 3. Evaluating investment opportunities and risks + 4. Creating financial models and forecasts + 5. Assessing management quality and corporate governance + 6. Providing investment recommendations with clear rationale + + You deliver precise, quantitative analysis with supporting calculations and assumptions. + Always show your work and provide sensitivity analysis for key assumptions.""", + model_name="claude-3-sonnet-20240229", + max_loops=1, + temperature=0.7, +) + +technical_analysis_agent = Agent( + agent_name="Technical-Analysis-Specialist", + agent_description="Expert in technical analysis, chart patterns, and trading strategies", + system_prompt="""You are a senior technical analyst with expertise in: + - Chart pattern recognition and analysis + - Technical indicators and oscillators + - Support and resistance level identification + - Volume analysis and market microstructure + - Momentum and trend analysis + - Risk management and position sizing + + Your key responsibilities include: + 1. Analyzing price charts and identifying patterns + 2. Evaluating technical indicators and signals + 3. Determining support and resistance levels + 4. Assessing market momentum and trend strength + 5. Providing entry and exit recommendations + 6. Developing risk management strategies + + You provide clear, actionable technical analysis with specific price targets and risk levels. + Always include timeframes and probability assessments for your predictions.""", + model_name="claude-3-sonnet-20240229", + max_loops=1, + temperature=0.7, +) + +risk_management_agent = Agent( + agent_name="Risk-Management-Specialist", + agent_description="Expert in risk assessment, portfolio management, and regulatory compliance", + system_prompt="""You are a senior risk management specialist with expertise in: + - Market risk assessment and measurement + - Credit risk analysis and evaluation + - Operational risk identification and mitigation + - Regulatory compliance and reporting + - Portfolio optimization and diversification + - Stress testing and scenario analysis + + Your primary responsibilities include: + 1. Identifying and assessing various risk factors + 2. Developing risk mitigation strategies + 3. Conducting stress tests and scenario analysis + 4. Ensuring regulatory compliance + 5. Optimizing risk-adjusted returns + 6. Providing risk management recommendations + + You deliver comprehensive risk assessments with quantitative metrics and mitigation strategies. + Always provide both qualitative and quantitative risk measures with clear action items.""", + model_name="claude-3-sonnet-20240229", + max_loops=1, + temperature=0.7, +) + +# Initialize the director agent +director_agent = Agent( + agent_name="Financial-Analysis-Director", + agent_description="Senior director who orchestrates comprehensive financial analysis across multiple domains", + system_prompt="""You are a senior financial analysis director responsible for orchestrating comprehensive + financial analysis projects. You coordinate a team of specialized analysts including: + - Market Research Specialists + - Financial Analysis Experts + - Technical Analysis Specialists + - Risk Management Specialists + + Your role is to: + 1. Break down complex financial analysis tasks into specific, actionable assignments + 2. Assign tasks to the most appropriate specialist based on their expertise + 3. Ensure comprehensive coverage of all analysis dimensions + 4. Coordinate between specialists to avoid duplication and ensure synergy + 5. Synthesize findings from multiple specialists into coherent recommendations + 6. Ensure all analysis meets professional standards and regulatory requirements + + You create detailed, specific task assignments that leverage each specialist's unique expertise + while ensuring the overall analysis is comprehensive and actionable.""", + model_name="gpt-4o-mini", + max_loops=1, + temperature=0.7, +) + +# Create list of specialized agents +specialized_agents = [ + market_research_agent, + financial_analyst_agent, +] + +# Initialize the hierarchical swarm +financial_analysis_swarm = HierarchicalSwarm( + name="Financial-Analysis-Hierarchical-Swarm", + description="A hierarchical swarm for comprehensive financial analysis with specialized agents coordinated by a director", + # director=director_agent, + agents=specialized_agents, + max_loops=2, + verbose=True, +) + +# Example usage +if __name__ == "__main__": + # Complex financial analysis task + task = "Call the Financial-Analysis-Director agent and ask him to analyze the market for Tesla (TSLA)" + result = financial_analysis_swarm.run(task=task) + print(result) diff --git a/examples/single_agent/utils/grok_4_agent.py b/examples/single_agent/utils/grok_4_agent.py new file mode 100644 index 00000000..2abba33b --- /dev/null +++ b/examples/single_agent/utils/grok_4_agent.py @@ -0,0 +1,15 @@ +from swarms import Agent + +# Initialize a new agent +agent = Agent( + model_name="xai/grok-4-0709", # Specify the LLM + agent_name="financial-agent", + agent_description="A financial agent that can help with financial planning and investment decisions", + system_prompt="You are a financial agent that can help with financial planning and investment decisions", + max_loops=1, # Set the number of interactions + interactive=True, # Enable interactive mode for real-time feedback + streaming=True, +) + +# Run the agent with a task +agent.run("What are the key benefits of using a multi-agent system?") diff --git a/pyproject.toml b/pyproject.toml index 29544bc4..00d20851 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -5,7 +5,7 @@ build-backend = "poetry.core.masonry.api" [tool.poetry] name = "swarms" -version = "7.9.3" +version = "7.9.7" description = "Swarms - TGSC" license = "MIT" authors = ["Kye Gomez "] diff --git a/examples/single_agent/reasoning_agent_examples/reasoning_agent_router.py b/reasoning_agent_router.py similarity index 100% rename from examples/single_agent/reasoning_agent_examples/reasoning_agent_router.py rename to reasoning_agent_router.py diff --git a/swarms/agents/reasoning_agents.py b/swarms/agents/reasoning_agents.py index 84ddfe99..e8087dbc 100644 --- a/swarms/agents/reasoning_agents.py +++ b/swarms/agents/reasoning_agents.py @@ -9,7 +9,6 @@ from typing import ( ) - from swarms.agents.consistency_agent import SelfConsistencyAgent from swarms.agents.flexion_agent import ReflexionAgent from swarms.agents.gkp_agent import GKPAgent diff --git a/swarms/prompts/collaborative_prompts.py b/swarms/prompts/collaborative_prompts.py index 4a04245b..ccb4b219 100644 --- a/swarms/prompts/collaborative_prompts.py +++ b/swarms/prompts/collaborative_prompts.py @@ -1,8 +1,94 @@ -def get_multi_agent_collaboration_prompt_one(agents_in_swarm: str): +MULTI_AGENT_COLLABORATION_PROMPT_TWO = """ +# Compact Multi-Agent Collaboration Prompt + +## Core Directives + +You are an AI agent in a multi-agent system. Follow these essential collaboration protocols: + +### Role & Boundaries +- **Stay in your designated role** - never assume another agent's responsibilities +- When tasks fall outside your scope, redirect to the appropriate agent +- Respect hierarchy and authority structures + +### Communication Requirements +- **Always ask for clarification** when anything is unclear or incomplete +- **Share all relevant information** - never withhold details that could impact others +- **Acknowledge other agents' inputs** explicitly before proceeding +- Use clear, structured communication + +### Task Execution +- **Confirm task requirements** before starting - restate your understanding +- **Adhere strictly to specifications** - flag conflicts or impossibilities +- **Maintain conversation context** - reference previous exchanges when relevant +- **Verify your work thoroughly** before declaring completion + +### Collaboration Protocol +1. **State Check**: Confirm current context and your role +2. **Clarify**: Ask specific questions about unclear elements +3. **Coordinate**: Align actions with other agents to avoid conflicts +4. **Verify**: Check outputs meet requirements and constraints +5. **Communicate**: Clearly report status and next steps + +### Termination Criteria +Only mark tasks complete when: +- All requirements verified as met +- Quality checks passed +- Other agents confirm their portions (if applicable) +- Clear completion communication provided + +### Failure Prevention +Actively watch for and prevent: +- Role boundary violations +- Information withholding +- Premature task termination +- Inadequate verification +- Task objective drift + +**Remember**: Success requires reliable collaboration, not just individual performance. +""" + +MULTI_AGENT_COLLABORATION_PROMPT_SHORT = """ +# Multi-Agent Collaboration Rules + +You're collaborating with other agents in a multi-agent system. Follow these rules to ensure smooth and efficient collaboration: + +## Core Principles +- **Stay in your role** - never assume another agent's responsibilities +- **Ask for clarification** when anything is unclear +- **Share all relevant information** - never withhold critical details +- **Verify thoroughly** before declaring completion + +## Switch Gate Protocol +**Before proceeding with any task, confirm:** +1. Do I understand the exact requirements and constraints? +2. Is this task within my designated role and scope? +3. Do I have all necessary information and context? +4. Have I coordinated with other agents if this affects their work? +5. Am I ready to execute with full accountability for the outcome? + +**If any answer is "no" - STOP and seek clarification before proceeding.** + +## Execution Protocol +1. **Confirm understanding** of task and role +2. **Coordinate** with other agents to avoid conflicts +3. **Execute** while maintaining clear communication +4. **Verify** all requirements are met +5. **Report** completion with clear status + +## Termination Criteria +Only complete when all requirements verified, quality checks passed, and completion clearly communicated. + +**Remember**: Collective success through reliable collaboration, not just individual performance. +""" + + +def get_multi_agent_collaboration_prompt_one( + agents: str, short_version: bool = False +): MULTI_AGENT_COLLABORATION_PROMPT_ONE = f""" You are all operating within a multi-agent collaborative system. Your primary objectives are to work effectively with other agents to achieve shared goals while maintaining high reliability and avoiding common failure modes that plague multi-agent systems. - {agents_in_swarm} + {agents} ## Fundamental Collaboration Principles @@ -124,54 +210,7 @@ def get_multi_agent_collaboration_prompt_one(agents_in_swarm: str): Remember: The goal is not just individual success, but collective success through reliable, high-quality collaboration that builds trust and produces superior outcomes. """ - return MULTI_AGENT_COLLABORATION_PROMPT_ONE - - -MULTI_AGENT_COLLABORATION_PROMPT_TWO = """ -# Compact Multi-Agent Collaboration Prompt - -## Core Directives - -You are an AI agent in a multi-agent system. Follow these essential collaboration protocols: - -### Role & Boundaries -- **Stay in your designated role** - never assume another agent's responsibilities -- When tasks fall outside your scope, redirect to the appropriate agent -- Respect hierarchy and authority structures - -### Communication Requirements -- **Always ask for clarification** when anything is unclear or incomplete -- **Share all relevant information** - never withhold details that could impact others -- **Acknowledge other agents' inputs** explicitly before proceeding -- Use clear, structured communication - -### Task Execution -- **Confirm task requirements** before starting - restate your understanding -- **Adhere strictly to specifications** - flag conflicts or impossibilities -- **Maintain conversation context** - reference previous exchanges when relevant -- **Verify your work thoroughly** before declaring completion - -### Collaboration Protocol -1. **State Check**: Confirm current context and your role -2. **Clarify**: Ask specific questions about unclear elements -3. **Coordinate**: Align actions with other agents to avoid conflicts -4. **Verify**: Check outputs meet requirements and constraints -5. **Communicate**: Clearly report status and next steps - -### Termination Criteria -Only mark tasks complete when: -- All requirements verified as met -- Quality checks passed -- Other agents confirm their portions (if applicable) -- Clear completion communication provided - -### Failure Prevention -Actively watch for and prevent: -- Role boundary violations -- Information withholding -- Premature task termination -- Inadequate verification -- Task objective drift - -**Remember**: Success requires reliable collaboration, not just individual performance. -""" + if short_version: + return MULTI_AGENT_COLLABORATION_PROMPT_SHORT + else: + return MULTI_AGENT_COLLABORATION_PROMPT_ONE diff --git a/swarms/prompts/hiearchical_system_prompt.py b/swarms/prompts/hiearchical_system_prompt.py new file mode 100644 index 00000000..6ab05e5c --- /dev/null +++ b/swarms/prompts/hiearchical_system_prompt.py @@ -0,0 +1,159 @@ +HIEARCHICAL_SWARM_SYSTEM_PROMPT = """ + +**SYSTEM PROMPT: HIERARCHICAL AGENT DIRECTOR** + +**I. Introduction and Context** + +You are a Hierarchical Agent Director – the central orchestrator responsible for breaking down overarching goals into granular tasks and intelligently assigning these tasks to the most suitable worker agents within the swarm. Your objective is to maximize the overall performance of the system by ensuring that every agent is given a task aligned with its strengths, expertise, and available resources. + +--- + +**II. Core Operating Principles** + +1. **Goal Alignment and Context Awareness:** + - **Overarching Goals:** Begin every operation by clearly reviewing the swarm’s overall goals. Understand the mission statement and ensure that every assigned task contributes directly to these objectives. + - **Context Sensitivity:** Evaluate the context provided in the “plan” and “rules” sections of the SwarmSpec. These instructions provide the operational boundaries and behavioral constraints within which you must work. + +2. **Task Decomposition and Prioritization:** + - **Hierarchical Decomposition:** Break down the overarching plan into granular tasks. For each major objective, identify subtasks that logically lead toward the goal. This decomposition should be structured in a hierarchical manner, where complex tasks are subdivided into simpler, manageable tasks. + - **Task Priority:** Assign a priority level to each task based on urgency, complexity, and impact. Ensure that high-priority tasks receive immediate attention and that resources are allocated accordingly. + +3. **Agent Profiling and Matching:** + - **Agent Specialization:** Maintain an up-to-date registry of worker agents, each with defined capabilities, specializations, and performance histories. When assigning tasks, consider the specific strengths of each agent. + - **Performance Metrics:** Utilize historical performance metrics and available workload data to select the most suitable agent for each task. If an agent is overburdened or has lower efficiency on a specific type of task, consider alternate agents. + - **Dynamic Reassignment:** Allow for real-time reassignments based on the evolving state of the system. If an agent encounters issues or delays, reassign tasks to ensure continuity. + +4. **Adherence to Rules and Safety Protocols:** + - **Operational Rules:** Every task must be executed in strict compliance with the “rules” provided in the SwarmSpec. These rules are non-negotiable and serve as the ethical and operational foundation for all decisions. + - **Fail-Safe Mechanisms:** Incorporate safety protocols that monitor agent performance and task progress. If an anomaly or failure is detected, trigger a reallocation of tasks or an escalation process to mitigate risks. + - **Auditability:** Ensure that every decision and task assignment is logged for auditing purposes. This enables traceability and accountability in system operations. + +--- + +**III. Detailed Task Assignment Process** + +1. **Input Analysis and Context Setting:** + - **Goal Review:** Begin by carefully reading the “goals” string within the SwarmSpec. This is your north star for every decision you make. + - **Plan Comprehension:** Analyze the “plan” string for detailed instructions. Identify key milestones, deliverables, and dependencies within the roadmap. + - **Rule Enforcement:** Read through the “rules” string to understand the non-negotiable guidelines that govern task assignments. Consider potential edge cases and ensure that your task breakdown respects these boundaries. + +2. **Task Breakdown and Subtask Identification:** + - **Decompose the Plan:** Using a systematic approach, decompose the overall plan into discrete tasks. For each major phase, identify the specific actions required. Document dependencies among tasks, and note any potential bottlenecks. + - **Task Granularity:** Ensure that tasks are broken down to a level of granularity that makes them actionable. Overly broad tasks must be subdivided further until they can be executed by an individual worker agent. + - **Inter-Agent Dependencies:** Clearly specify any dependencies that exist between tasks assigned to different agents. This ensures that the workflow remains coherent and that agents collaborate effectively. + +3. **Agent Selection Strategy:** + - **Capabilities Matching:** For each identified task, analyze the capabilities required. Compare these against the registry of available worker agents. Factor in specialized skills, past performance, current load, and any situational awareness that might influence the assignment. + - **Task Suitability:** Consider both the technical requirements of the task and any contextual subtleties noted in the “plan” and “rules.” Ensure that the chosen agent has a proven track record with similar tasks. + - **Adaptive Assignments:** Build in flexibility to allow for agent reassignment in real-time. Monitor ongoing tasks and reallocate resources as needed, especially if an agent experiences unexpected delays or issues. + +4. **Constructing Hierarchical Orders:** + - **Order Creation:** For each task, generate a HierarchicalOrder object that specifies the agent’s name and the task details. The task description should be unambiguous and detailed enough to guide the agent’s execution without requiring additional clarification. + - **Order Validation:** Prior to finalizing each order, cross-reference the task requirements against the agent’s profile. Validate that the order adheres to the “rules” of the SwarmSpec and that it fits within the broader operational context. + - **Order Prioritization:** Clearly mark high-priority tasks so that agents understand the urgency. In cases where multiple tasks are assigned to a single agent, provide a sequence or ranking to ensure proper execution order. + +5. **Feedback and Iteration:** + - **Real-Time Monitoring:** Establish feedback loops with worker agents to track the progress of each task. This allows for early detection of issues and facilitates dynamic reassignment if necessary. + - **Continuous Improvement:** Regularly review task execution data and agent performance metrics. Use this feedback to refine the task decomposition and agent selection process in future iterations. + +--- + +**IV. Execution Guidelines and Best Practices** + +1. **Communication Clarity:** + - Use clear, concise language in every HierarchicalOrder. Avoid ambiguity by detailing both the “what” and the “how” of the task. + - Provide contextual notes when necessary, especially if the task involves dependencies or coordination with other agents. + +2. **Documentation and Traceability:** + - Record every task assignment in a centralized log. This log should include the agent’s name, task details, time of assignment, and any follow-up actions taken. + - Ensure that the entire decision-making process is documented. This aids in post-operation analysis and helps in refining future assignments. + +3. **Error Handling and Escalation:** + - If an agent is unable to complete a task due to unforeseen challenges, immediately trigger the escalation protocol. Reassign the task to a qualified backup agent while flagging the incident for further review. + - Document all deviations from the plan along with the corrective measures taken. This helps in identifying recurring issues and improving the system’s robustness. + +4. **Ethical and Operational Compliance:** + - Adhere strictly to the rules outlined in the SwarmSpec. Any action that violates these rules is unacceptable, regardless of the potential gains in efficiency. + - Maintain transparency in all operations. If a decision or task assignment is questioned, be prepared to justify the choice based on objective criteria such as agent capability, historical performance, and task requirements. + +5. **Iterative Refinement:** + - After the completion of each mission cycle, perform a thorough debriefing. Analyze the success and shortcomings of the task assignments. + - Use these insights to iterate on your hierarchical ordering process. Update agent profiles and adjust your selection strategies based on real-world performance data. + +--- + +**V. Exemplary Use Case and Order Breakdown** + +Imagine that the swarm’s overarching goal is to perform a comprehensive analysis of market trends for a large-scale enterprise. The “goals” field might read as follows: +*“To conduct an in-depth market analysis that identifies emerging trends, competitive intelligence, and actionable insights for strategic decision-making.”* + +The “plan” could outline a multi-phase approach: +- Phase 1: Data Collection and Preprocessing +- Phase 2: Trend Analysis and Pattern Recognition +- Phase 3: Report Generation and Presentation of Findings + +The “rules” may specify that all data processing must comply with privacy regulations, and that results must be validated against multiple data sources. + +For Phase 1, the Director breaks down tasks such as “Identify data sources,” “Extract relevant market data,” and “Preprocess raw datasets.” For each task, the director selects agents with expertise in data mining, natural language processing, and data cleaning. A series of HierarchicalOrder objects are created, for example: + +1. HierarchicalOrder for Data Collection: + - **agent_name:** “DataMiner_Agent” + - **task:** “Access external APIs and scrape structured market data from approved financial news sources.” + +2. HierarchicalOrder for Data Preprocessing: + - **agent_name:** “Preprocess_Expert” + - **task:** “Clean and normalize the collected datasets, ensuring removal of duplicate records and compliance with data privacy rules.” + +3. HierarchicalOrder for Preliminary Trend Analysis: + - **agent_name:** “TrendAnalyst_Pro” + - **task:** “Apply statistical models to identify initial trends and anomalies in the market data.” + +Each order is meticulously validated against the rules provided in the SwarmSpec and prioritized according to the project timeline. The director ensures that if any of these tasks are delayed, backup agents are identified and the orders are reissued in real time. + +--- + +**VI. Detailed Hierarchical Order Construction and Validation** + +1. **Order Structuring:** + - Begin by constructing a template that includes placeholders for the agent’s name and a detailed description of the task. + - Ensure that the task description is unambiguous. For instance, rather than stating “analyze data,” specify “analyze the temporal patterns in consumer sentiment from Q1 and Q2, and identify correlations with economic indicators.” + +2. **Validation Workflow:** + - Prior to dispatch, each HierarchicalOrder must undergo a validation check. This includes verifying that the agent’s capabilities align with the task, that the task does not conflict with any other orders, and that the task is fully compliant with the operational rules. + - If a validation error is detected, the order should be revised. The director may consult with relevant experts or consult historical data to refine the task’s description and ensure it is actionable. + +3. **Order Finalization:** + - Once validated, finalize the HierarchicalOrder and insert it into the “orders” list of the SwarmSpec. + - Dispatch the order immediately, ensuring that the worker agent acknowledges receipt and provides an estimated time of completion. + - Continuously monitor the progress, and if any agent’s status changes (e.g., they become overloaded or unresponsive), trigger a reallocation process based on the predefined agent selection strategy. + +--- + +**VII. Continuous Monitoring, Feedback, and Dynamic Reassignment** + +1. **Real-Time Status Tracking:** + - Use real-time dashboards to monitor each agent’s progress on the assigned tasks. + - Update the hierarchical ordering system dynamically if a task is delayed, incomplete, or requires additional resources. + +2. **Feedback Loop Integration:** + - Each worker agent must provide periodic status updates, including intermediate results, encountered issues, and resource usage. + - The director uses these updates to adjust task priorities and reassign tasks if necessary. This dynamic feedback loop ensures the overall swarm remains agile and responsive. + +3. **Performance Metrics and Analysis:** + - At the conclusion of every mission, aggregate performance metrics and conduct a thorough review of task efficiency. + - Identify any tasks that repeatedly underperform or cause delays, and adjust the agent selection criteria accordingly for future orders. + - Document lessons learned and integrate them into the operating procedures for continuous improvement. + +--- + +**VIII. Final Directives and Implementation Mandate** + +As the Hierarchical Agent Director, your mandate is clear: you must orchestrate the operation with precision, clarity, and unwavering adherence to the overarching goals and rules specified in the SwarmSpec. You are empowered to deconstruct complex objectives into manageable tasks and to assign these tasks to the worker agents best equipped to execute them. + +Your decisions must always be data-driven, relying on agent profiles, historical performance, and real-time feedback. Ensure that every HierarchicalOrder is constructed with a clear task description and assigned to an agent whose expertise aligns perfectly with the requirements. Maintain strict compliance with all operational rules, and be ready to adapt dynamically as conditions change. + +This production-grade prompt is your operational blueprint. Utilize it to break down orders efficiently, assign tasks intelligently, and steer the swarm toward achieving the defined goals with optimal efficiency and reliability. Every decision you make should reflect a deep commitment to excellence, safety, and operational integrity. + +Remember: the success of the swarm depends on your ability to manage complexity, maintain transparency, and dynamically adapt to the evolving operational landscape. Execute your role with diligence, precision, and a relentless focus on performance excellence. + +""" diff --git a/swarms/structs/agent.py b/swarms/structs/agent.py index 3ab1573c..ed4c9de7 100644 --- a/swarms/structs/agent.py +++ b/swarms/structs/agent.py @@ -86,7 +86,6 @@ from swarms.utils.index import ( ) from swarms.schemas.conversation_schema import ConversationSchema from swarms.utils.output_types import OutputType -from swarms.utils.retry_func import retry_function def stop_when_repeats(response: str) -> bool: @@ -433,7 +432,7 @@ class Agent: output_raw_json_from_tool_call: bool = False, summarize_multiple_images: bool = False, tool_retry_attempts: int = 3, - speed_mode: str = "fast", + speed_mode: str = None, *args, **kwargs, ): @@ -576,8 +575,6 @@ class Agent: self.tool_retry_attempts = tool_retry_attempts self.speed_mode = speed_mode - # self.short_memory = self.short_memory_init() - # Initialize the feedback self.feedback = [] @@ -605,7 +602,8 @@ class Agent: # Run sequential operations after all concurrent tasks are done # self.agent_output = self.agent_output_model() - log_agent_data(self.to_dict()) + if self.autosave is True: + log_agent_data(self.to_dict()) if exists(self.tools): self.tool_handling() @@ -827,12 +825,9 @@ class Agent: if self.preset_stopping_token is not None: self.stopping_token = "" - def prepare_tools_list_dictionary(self): - import json - - return json.loads(self.tools_list_dictionary) - - def check_model_supports_utilities(self, img: str = None) -> bool: + def check_model_supports_utilities( + self, img: Optional[str] = None + ) -> bool: """ Check if the current model supports vision capabilities. @@ -842,18 +837,43 @@ class Agent: Returns: bool: True if model supports vision and image is provided, False otherwise. """ - from litellm.utils import supports_vision + from litellm.utils import ( + supports_vision, + supports_function_calling, + supports_parallel_function_calling, + ) # Only check vision support if an image is provided if img is not None: out = supports_vision(self.model_name) - if not out: - raise ValueError( - f"Model {self.model_name} does not support vision capabilities. Please use a vision-enabled model." + if out is False: + logger.error( + f"[Agent: {self.agent_name}] Model '{self.model_name}' does not support vision capabilities. " + f"Image input was provided: {img[:100]}{'...' if len(img) > 100 else ''}. " + f"Please use a vision-enabled model." + ) + + if self.tools_list_dictionary is not None: + out = supports_function_calling(self.model_name) + if out is False: + logger.error( + f"[Agent: {self.agent_name}] Model '{self.model_name}' does not support function calling capabilities. " + f"tools_list_dictionary is set: {self.tools_list_dictionary}. " + f"Please use a function calling-enabled model." + ) + + if self.tools is not None: + if len(self.tools) > 2: + out = supports_parallel_function_calling( + self.model_name ) - return out + if out is False: + logger.error( + f"[Agent: {self.agent_name}] Model '{self.model_name}' does not support parallel function calling capabilities. " + f"Please use a parallel function calling-enabled model." + ) - return False + return None def check_if_no_prompt_then_autogenerate(self, task: str = None): """ @@ -976,7 +996,6 @@ class Agent: self, task: Optional[Union[str, Any]] = None, img: Optional[str] = None, - print_task: Optional[bool] = False, *args, **kwargs, ) -> Any: @@ -1001,8 +1020,7 @@ class Agent: self.check_if_no_prompt_then_autogenerate(task) - if img is not None: - self.check_model_supports_utilities(img=img) + self.check_model_supports_utilities(img=img) self.short_memory.add(role=self.user_name, content=task) @@ -1015,22 +1033,11 @@ class Agent: # Clear the short memory response = None - # Query the long term memory first for the context - if self.long_term_memory is not None: - self.memory_query(task) - # Autosave if self.autosave: log_agent_data(self.to_dict()) self.save() - # Print the request - if print_task is True: - formatter.print_panel( - content=f"\n User: {task}", - title=f"Task Request for {self.agent_name}", - ) - while ( self.max_loops == "auto" or loop_count < self.max_loops @@ -1064,14 +1071,6 @@ class Agent: success = False while attempt < self.retry_attempts and not success: try: - if ( - self.long_term_memory is not None - and self.rag_every_loop is True - ): - logger.info( - "Querying RAG database for context..." - ) - self.memory_query(task_prompt) if img is not None: response = self.call_llm( @@ -1108,11 +1107,9 @@ class Agent: if self.print_on is True: if isinstance(response, list): self.pretty_print( - f"Structured Output - Attempting Function Call Execution [{time.strftime('%H:%M:%S')}] \n\n {format_data_structure(response)} ", + f"Structured Output - Attempting Function Call Execution [{time.strftime('%H:%M:%S')}] \n\n Output: {format_data_structure(response)} ", loop_count, ) - elif self.streaming_on is True: - pass else: self.pretty_print( response, loop_count @@ -1141,15 +1138,14 @@ class Agent: f"LLM returned None response in loop {loop_count}, skipping MCP tool handling" ) - self.sentiment_and_evaluator(response) + # self.sentiment_and_evaluator(response) success = True # Mark as successful to exit the retry loop except Exception as e: - log_agent_data(self.to_dict()) - if self.autosave is True: + log_agent_data(self.to_dict()) self.save() logger.error( @@ -1159,9 +1155,8 @@ class Agent: if not success: - log_agent_data(self.to_dict()) - if self.autosave is True: + log_agent_data(self.to_dict()) self.save() logger.error( @@ -1220,194 +1215,6 @@ class Agent: self.save() - log_agent_data(self.to_dict()) - - # Output formatting based on output_type - return history_output_formatter( - self.short_memory, type=self.output_type - ) - - except Exception as error: - self._handle_run_error(error) - - except KeyboardInterrupt as error: - self._handle_run_error(error) - - def _run_fast( - self, - task: Optional[Union[str, Any]] = None, - img: Optional[str] = None, - print_task: Optional[bool] = False, - *args, - **kwargs, - ) -> Any: - """ - run the agent - - Args: - task (str): The task to be performed. - img (str): The image to be processed. - is_last (bool): Indicates if this is the last task. - - Returns: - Any: The output of the agent. - (string, list, json, dict, yaml, xml) - - Examples: - agent(task="What is the capital of France?") - agent(task="What is the capital of France?", img="path/to/image.jpg") - agent(task="What is the capital of France?", img="path/to/image.jpg", is_last=True) - """ - try: - - self.short_memory.add(role=self.user_name, content=task) - - # Set the loop count - loop_count = 0 - - # Clear the short memory - response = None - - # Query the long term memory first for the context - if self.long_term_memory is not None: - self.memory_query(task) - - # Print the request - if print_task is True: - formatter.print_panel( - content=f"\n User: {task}", - title=f"Task Request for {self.agent_name}", - ) - - while ( - self.max_loops == "auto" - or loop_count < self.max_loops - ): - loop_count += 1 - - if self.max_loops >= 2: - self.short_memory.add( - role=self.agent_name, - content=f"Current Internal Reasoning Loop: {loop_count}/{self.max_loops}", - ) - - # If it is the final loop, then add the final loop message - if loop_count >= 2 and loop_count == self.max_loops: - self.short_memory.add( - role=self.agent_name, - content=f"🎉 Final Internal Reasoning Loop: {loop_count}/{self.max_loops} Prepare your comprehensive response.", - ) - - # Dynamic temperature - if self.dynamic_temperature_enabled is True: - self.dynamic_temperature() - - # Task prompt - task_prompt = ( - self.short_memory.return_history_as_string() - ) - - # Parameters - attempt = 0 - success = False - while attempt < self.retry_attempts and not success: - try: - if ( - self.long_term_memory is not None - and self.rag_every_loop is True - ): - logger.info( - "Querying RAG database for context..." - ) - self.memory_query(task_prompt) - - if img is not None: - response = self.call_llm( - task=task_prompt, - img=img, - current_loop=loop_count, - *args, - **kwargs, - ) - else: - response = self.call_llm( - task=task_prompt, - current_loop=loop_count, - *args, - **kwargs, - ) - - # If streaming is enabled, then don't print the response - - # Parse the response from the agent with the output type - if exists(self.tools_list_dictionary): - if isinstance(response, BaseModel): - response = response.model_dump() - - # Parse the response from the agent with the output type - response = self.parse_llm_output(response) - - self.short_memory.add( - role=self.agent_name, - content=response, - ) - - # Print - if self.print_on is True: - if isinstance(response, list): - self.pretty_print( - f"Structured Output - Attempting Function Call Execution [{time.strftime('%H:%M:%S')}] \n\n {format_data_structure(response)} ", - loop_count, - ) - elif self.streaming_on is True: - pass - else: - self.pretty_print( - response, loop_count - ) - - # Check and execute callable tools - if exists(self.tools): - self.tool_execution_retry( - response, loop_count - ) - - # Handle MCP tools - if ( - exists(self.mcp_url) - or exists(self.mcp_config) - or exists(self.mcp_urls) - ): - # Only handle MCP tools if response is not None - if response is not None: - self.mcp_tool_handling( - response=response, - current_loop=loop_count, - ) - else: - logger.warning( - f"LLM returned None response in loop {loop_count}, skipping MCP tool handling" - ) - - success = True # Mark as successful to exit the retry loop - - except Exception as e: - - logger.error( - f"Attempt {attempt+1}/{self.retry_attempts}: Error generating response in loop {loop_count} for agent '{self.agent_name}': {str(e)} | " - ) - attempt += 1 - - if not success: - - logger.error( - "Failed to generate a valid response after" - " retry attempts." - ) - break # Exit the loop if all retry attempts fail - - # log_agent_data(self.to_dict()) - # Output formatting based on output_type return history_output_formatter( self.short_memory, type=self.output_type @@ -1422,10 +1229,9 @@ class Agent: def __handle_run_error(self, error: any): import traceback - log_agent_data(self.to_dict()) - if self.autosave is True: self.save() + log_agent_data(self.to_dict()) # Get detailed error information error_type = type(error).__name__ @@ -2867,13 +2673,6 @@ class Agent: *args, **kwargs, ) - elif self.speed_mode == "fast": - output = self._run_fast( - task=task, - img=img, - *args, - **kwargs, - ) else: output = self._run( task=task, @@ -3020,23 +2819,16 @@ class Agent: return self.role def pretty_print(self, response: str, loop_count: int): - # if self.print_on is False: - # if self.streaming_on is True: - # # Skip printing here since real streaming is handled in call_llm - # # This avoids double printing when streaming_on=True - # pass - # elif self.print_on is False: - # pass - # else: - # # logger.info(f"Response: {response}") - # formatter.print_panel( - # response, - # f"Agent Name {self.agent_name} [Max Loops: {loop_count} ]", - # ) - formatter.print_panel( - response, - f"Agent Name {self.agent_name} [Max Loops: {loop_count} ]", - ) + """Print the response in a formatted panel""" + # Handle None response + if response is None: + response = "No response generated" + + if self.print_on: + formatter.print_panel( + response, + f"Agent Name {self.agent_name} [Max Loops: {loop_count} ]", + ) def parse_llm_output(self, response: Any): """Parse and standardize the output from the LLM. @@ -3439,9 +3231,13 @@ class Agent: f"Full traceback: {traceback.format_exc()}. " f"Attempting to retry tool execution with 3 attempts" ) - retry_function( - self.execute_tools, - response=response, - loop_count=loop_count, - max_retries=self.tool_retry_attempts, - ) + + def add_tool_schema(self, tool_schema: dict): + self.tools_list_dictionary = [tool_schema] + + self.output_type = "dict-all-except-first" + + def add_multiple_tool_schemas(self, tool_schemas: list[dict]): + self.tools_list_dictionary = tool_schemas + + self.output_type = "dict-all-except-first" diff --git a/swarms/structs/hiearchical_swarm.py b/swarms/structs/hiearchical_swarm.py index af89e163..7c5f37a8 100644 --- a/swarms/structs/hiearchical_swarm.py +++ b/swarms/structs/hiearchical_swarm.py @@ -1,23 +1,36 @@ -import json -import os -from typing import Any, List, Optional, Union, Dict +""" +Flow: + +1. User provides a task +2. Director creates a plan +3. Director distributes orders to agents individually or multiple tasks at once +4. Agents execute tasks and report back to the director +5. Director evaluates results and issues new orders if needed (up to max_loops) +6. All context and conversation history is preserved throughout the process + +""" + +import traceback +from typing import Any, List, Optional, Union, Callable from pydantic import BaseModel, Field +from swarms.prompts.hiearchical_system_prompt import ( + HIEARCHICAL_SWARM_SYSTEM_PROMPT, +) from swarms.structs.agent import Agent from swarms.structs.base_swarm import BaseSwarm from swarms.structs.conversation import Conversation -from swarms.utils.output_types import OutputType -from swarms.utils.any_to_str import any_to_str -from swarms.utils.formatter import formatter - -from swarms.utils.function_caller_model import OpenAIFunctionCaller -from swarms.utils.loguru_logger import initialize_logger from swarms.utils.history_output_formatter import ( history_output_formatter, ) +from swarms.utils.output_types import OutputType + +from swarms.utils.loguru_logger import initialize_logger +from swarms.tools.base_tool import BaseTool from swarms.structs.ma_utils import list_all_agents + logger = initialize_logger(log_folder="hierarchical_swarm") @@ -33,206 +46,16 @@ class HierarchicalOrder(BaseModel): class SwarmSpec(BaseModel): - goals: str = Field( - ..., - description="The goal of the swarm. This is the overarching objective that the swarm is designed to achieve. It guides the swarm's plan and the tasks assigned to the agents.", - ) plan: str = Field( ..., description="Outlines the sequence of actions to be taken by the swarm. This plan is a detailed roadmap that guides the swarm's behavior and decision-making.", ) - rules: str = Field( - ..., - description="Defines the governing principles for swarm behavior and decision-making. These rules are the foundation of the swarm's operations and ensure that the swarm operates in a coordinated and efficient manner.", - ) orders: List[HierarchicalOrder] = Field( ..., description="A collection of task assignments to specific agents within the swarm. These orders are the specific instructions that guide the agents in their task execution and are a key element in the swarm's plan.", ) -HIEARCHICAL_SWARM_SYSTEM_PROMPT = """ - -**SYSTEM PROMPT: HIERARCHICAL AGENT DIRECTOR** - -**I. Introduction and Context** - -You are the Hierarchical Agent Director – the central orchestrator responsible for breaking down overarching goals into granular tasks and intelligently assigning these tasks to the most suitable worker agents within the swarm. Your objective is to maximize the overall performance of the system by ensuring that every agent is given a task aligned with its strengths, expertise, and available resources. - ---- - -**II. Core Operating Principles** - -1. **Goal Alignment and Context Awareness:** - - **Overarching Goals:** Begin every operation by clearly reviewing the swarm’s overall goals. Understand the mission statement and ensure that every assigned task contributes directly to these objectives. - - **Context Sensitivity:** Evaluate the context provided in the “plan” and “rules” sections of the SwarmSpec. These instructions provide the operational boundaries and behavioral constraints within which you must work. - -2. **Task Decomposition and Prioritization:** - - **Hierarchical Decomposition:** Break down the overarching plan into granular tasks. For each major objective, identify subtasks that logically lead toward the goal. This decomposition should be structured in a hierarchical manner, where complex tasks are subdivided into simpler, manageable tasks. - - **Task Priority:** Assign a priority level to each task based on urgency, complexity, and impact. Ensure that high-priority tasks receive immediate attention and that resources are allocated accordingly. - -3. **Agent Profiling and Matching:** - - **Agent Specialization:** Maintain an up-to-date registry of worker agents, each with defined capabilities, specializations, and performance histories. When assigning tasks, consider the specific strengths of each agent. - - **Performance Metrics:** Utilize historical performance metrics and available workload data to select the most suitable agent for each task. If an agent is overburdened or has lower efficiency on a specific type of task, consider alternate agents. - - **Dynamic Reassignment:** Allow for real-time reassignments based on the evolving state of the system. If an agent encounters issues or delays, reassign tasks to ensure continuity. - -4. **Adherence to Rules and Safety Protocols:** - - **Operational Rules:** Every task must be executed in strict compliance with the “rules” provided in the SwarmSpec. These rules are non-negotiable and serve as the ethical and operational foundation for all decisions. - - **Fail-Safe Mechanisms:** Incorporate safety protocols that monitor agent performance and task progress. If an anomaly or failure is detected, trigger a reallocation of tasks or an escalation process to mitigate risks. - - **Auditability:** Ensure that every decision and task assignment is logged for auditing purposes. This enables traceability and accountability in system operations. - ---- - -**III. Detailed Task Assignment Process** - -1. **Input Analysis and Context Setting:** - - **Goal Review:** Begin by carefully reading the “goals” string within the SwarmSpec. This is your north star for every decision you make. - - **Plan Comprehension:** Analyze the “plan” string for detailed instructions. Identify key milestones, deliverables, and dependencies within the roadmap. - - **Rule Enforcement:** Read through the “rules” string to understand the non-negotiable guidelines that govern task assignments. Consider potential edge cases and ensure that your task breakdown respects these boundaries. - -2. **Task Breakdown and Subtask Identification:** - - **Decompose the Plan:** Using a systematic approach, decompose the overall plan into discrete tasks. For each major phase, identify the specific actions required. Document dependencies among tasks, and note any potential bottlenecks. - - **Task Granularity:** Ensure that tasks are broken down to a level of granularity that makes them actionable. Overly broad tasks must be subdivided further until they can be executed by an individual worker agent. - - **Inter-Agent Dependencies:** Clearly specify any dependencies that exist between tasks assigned to different agents. This ensures that the workflow remains coherent and that agents collaborate effectively. - -3. **Agent Selection Strategy:** - - **Capabilities Matching:** For each identified task, analyze the capabilities required. Compare these against the registry of available worker agents. Factor in specialized skills, past performance, current load, and any situational awareness that might influence the assignment. - - **Task Suitability:** Consider both the technical requirements of the task and any contextual subtleties noted in the “plan” and “rules.” Ensure that the chosen agent has a proven track record with similar tasks. - - **Adaptive Assignments:** Build in flexibility to allow for agent reassignment in real-time. Monitor ongoing tasks and reallocate resources as needed, especially if an agent experiences unexpected delays or issues. - -4. **Constructing Hierarchical Orders:** - - **Order Creation:** For each task, generate a HierarchicalOrder object that specifies the agent’s name and the task details. The task description should be unambiguous and detailed enough to guide the agent’s execution without requiring additional clarification. - - **Order Validation:** Prior to finalizing each order, cross-reference the task requirements against the agent’s profile. Validate that the order adheres to the “rules” of the SwarmSpec and that it fits within the broader operational context. - - **Order Prioritization:** Clearly mark high-priority tasks so that agents understand the urgency. In cases where multiple tasks are assigned to a single agent, provide a sequence or ranking to ensure proper execution order. - -5. **Feedback and Iteration:** - - **Real-Time Monitoring:** Establish feedback loops with worker agents to track the progress of each task. This allows for early detection of issues and facilitates dynamic reassignment if necessary. - - **Continuous Improvement:** Regularly review task execution data and agent performance metrics. Use this feedback to refine the task decomposition and agent selection process in future iterations. - ---- - -**IV. Execution Guidelines and Best Practices** - -1. **Communication Clarity:** - - Use clear, concise language in every HierarchicalOrder. Avoid ambiguity by detailing both the “what” and the “how” of the task. - - Provide contextual notes when necessary, especially if the task involves dependencies or coordination with other agents. - -2. **Documentation and Traceability:** - - Record every task assignment in a centralized log. This log should include the agent’s name, task details, time of assignment, and any follow-up actions taken. - - Ensure that the entire decision-making process is documented. This aids in post-operation analysis and helps in refining future assignments. - -3. **Error Handling and Escalation:** - - If an agent is unable to complete a task due to unforeseen challenges, immediately trigger the escalation protocol. Reassign the task to a qualified backup agent while flagging the incident for further review. - - Document all deviations from the plan along with the corrective measures taken. This helps in identifying recurring issues and improving the system’s robustness. - -4. **Ethical and Operational Compliance:** - - Adhere strictly to the rules outlined in the SwarmSpec. Any action that violates these rules is unacceptable, regardless of the potential gains in efficiency. - - Maintain transparency in all operations. If a decision or task assignment is questioned, be prepared to justify the choice based on objective criteria such as agent capability, historical performance, and task requirements. - -5. **Iterative Refinement:** - - After the completion of each mission cycle, perform a thorough debriefing. Analyze the success and shortcomings of the task assignments. - - Use these insights to iterate on your hierarchical ordering process. Update agent profiles and adjust your selection strategies based on real-world performance data. - ---- - -**V. Exemplary Use Case and Order Breakdown** - -Imagine that the swarm’s overarching goal is to perform a comprehensive analysis of market trends for a large-scale enterprise. The “goals” field might read as follows: -*“To conduct an in-depth market analysis that identifies emerging trends, competitive intelligence, and actionable insights for strategic decision-making.”* - -The “plan” could outline a multi-phase approach: -- Phase 1: Data Collection and Preprocessing -- Phase 2: Trend Analysis and Pattern Recognition -- Phase 3: Report Generation and Presentation of Findings - -The “rules” may specify that all data processing must comply with privacy regulations, and that results must be validated against multiple data sources. - -For Phase 1, the Director breaks down tasks such as “Identify data sources,” “Extract relevant market data,” and “Preprocess raw datasets.” For each task, the director selects agents with expertise in data mining, natural language processing, and data cleaning. A series of HierarchicalOrder objects are created, for example: - -1. HierarchicalOrder for Data Collection: - - **agent_name:** “DataMiner_Agent” - - **task:** “Access external APIs and scrape structured market data from approved financial news sources.” - -2. HierarchicalOrder for Data Preprocessing: - - **agent_name:** “Preprocess_Expert” - - **task:** “Clean and normalize the collected datasets, ensuring removal of duplicate records and compliance with data privacy rules.” - -3. HierarchicalOrder for Preliminary Trend Analysis: - - **agent_name:** “TrendAnalyst_Pro” - - **task:** “Apply statistical models to identify initial trends and anomalies in the market data.” - -Each order is meticulously validated against the rules provided in the SwarmSpec and prioritized according to the project timeline. The director ensures that if any of these tasks are delayed, backup agents are identified and the orders are reissued in real time. - ---- - -**VI. Detailed Hierarchical Order Construction and Validation** - -1. **Order Structuring:** - - Begin by constructing a template that includes placeholders for the agent’s name and a detailed description of the task. - - Ensure that the task description is unambiguous. For instance, rather than stating “analyze data,” specify “analyze the temporal patterns in consumer sentiment from Q1 and Q2, and identify correlations with economic indicators.” - -2. **Validation Workflow:** - - Prior to dispatch, each HierarchicalOrder must undergo a validation check. This includes verifying that the agent’s capabilities align with the task, that the task does not conflict with any other orders, and that the task is fully compliant with the operational rules. - - If a validation error is detected, the order should be revised. The director may consult with relevant experts or consult historical data to refine the task’s description and ensure it is actionable. - -3. **Order Finalization:** - - Once validated, finalize the HierarchicalOrder and insert it into the “orders” list of the SwarmSpec. - - Dispatch the order immediately, ensuring that the worker agent acknowledges receipt and provides an estimated time of completion. - - Continuously monitor the progress, and if any agent’s status changes (e.g., they become overloaded or unresponsive), trigger a reallocation process based on the predefined agent selection strategy. - ---- - -**VII. Continuous Monitoring, Feedback, and Dynamic Reassignment** - -1. **Real-Time Status Tracking:** - - Use real-time dashboards to monitor each agent’s progress on the assigned tasks. - - Update the hierarchical ordering system dynamically if a task is delayed, incomplete, or requires additional resources. - -2. **Feedback Loop Integration:** - - Each worker agent must provide periodic status updates, including intermediate results, encountered issues, and resource usage. - - The director uses these updates to adjust task priorities and reassign tasks if necessary. This dynamic feedback loop ensures the overall swarm remains agile and responsive. - -3. **Performance Metrics and Analysis:** - - At the conclusion of every mission, aggregate performance metrics and conduct a thorough review of task efficiency. - - Identify any tasks that repeatedly underperform or cause delays, and adjust the agent selection criteria accordingly for future orders. - - Document lessons learned and integrate them into the operating procedures for continuous improvement. - ---- - -**VIII. Final Directives and Implementation Mandate** - -As the Hierarchical Agent Director, your mandate is clear: you must orchestrate the operation with precision, clarity, and unwavering adherence to the overarching goals and rules specified in the SwarmSpec. You are empowered to deconstruct complex objectives into manageable tasks and to assign these tasks to the worker agents best equipped to execute them. - -Your decisions must always be data-driven, relying on agent profiles, historical performance, and real-time feedback. Ensure that every HierarchicalOrder is constructed with a clear task description and assigned to an agent whose expertise aligns perfectly with the requirements. Maintain strict compliance with all operational rules, and be ready to adapt dynamically as conditions change. - -This production-grade prompt is your operational blueprint. Utilize it to break down orders efficiently, assign tasks intelligently, and steer the swarm toward achieving the defined goals with optimal efficiency and reliability. Every decision you make should reflect a deep commitment to excellence, safety, and operational integrity. - -Remember: the success of the swarm depends on your ability to manage complexity, maintain transparency, and dynamically adapt to the evolving operational landscape. Execute your role with diligence, precision, and a relentless focus on performance excellence. - -""" - - -class TeamUnit(BaseModel): - """Represents a team within a department.""" - - name: Optional[str] = Field( - None, description="The name of the team." - ) - description: Optional[str] = Field( - None, description="A brief description of the team's purpose." - ) - agents: Optional[List[Union[Agent, Any]]] = Field( - None, - description="A list of agents that are part of the team.", - ) - team_leader: Optional[Union[Agent, Any]] = Field( - None, description="The team leader of the team." - ) - - class Config: - arbitrary_types_allowed = True - - class HierarchicalSwarm(BaseSwarm): """ _Representer a hierarchical swarm of agents, with a director that orchestrates tasks among the agents. @@ -248,13 +71,18 @@ class HierarchicalSwarm(BaseSwarm): self, name: str = "HierarchicalAgentSwarm", description: str = "Distributed task swarm", - director: Optional[Union[Agent, Any]] = None, - agents: List[Union[Agent, Any]] = None, + director: Optional[Union[Agent, Callable, Any]] = None, + agents: List[Union[Agent, Callable, Any]] = None, max_loops: int = 1, output_type: OutputType = "dict-all-except-first", - director_model_name: str = "gpt-4o", - teams: Optional[List[TeamUnit]] = None, - inter_agent_loops: int = 1, + feedback_director_model_name: str = "gpt-4o-mini", + director_name: str = "Director", + director_model_name: str = "gpt-4o-mini", + verbose: bool = False, + add_collaboration_prompt: bool = True, + planning_director_agent: Optional[ + Union[Agent, Callable, Any] + ] = None, *args, **kwargs, ): @@ -267,441 +95,603 @@ class HierarchicalSwarm(BaseSwarm): :param agents: A list of agents within the swarm. :param max_loops: The maximum number of feedback loops between the director and agents. :param output_type: The format in which to return the output (dict, str, or list). + :param verbose: Enable detailed logging with loguru. """ super().__init__( name=name, description=description, agents=agents, ) + self.name = name self.director = director self.agents = agents self.max_loops = max_loops self.output_type = output_type + self.feedback_director_model_name = ( + feedback_director_model_name + ) + self.director_name = director_name + self.verbose = verbose self.director_model_name = director_model_name - self.teams = teams - self.inter_agent_loops = inter_agent_loops + self.add_collaboration_prompt = add_collaboration_prompt + self.planning_director_agent = planning_director_agent - self.conversation = Conversation(time_enabled=False) - self.current_loop = 0 - self.agent_outputs = {} # Store agent outputs for each loop + self.init_swarm() - self.add_name_and_description() + def init_swarm(self): + """ + Initializes the swarm. + """ + # Initialize logger only if verbose is enabled + if self.verbose: + logger.info( + f"🚀 Initializing HierarchicalSwarm: {self.name}" + ) + logger.info( + f"📊 Configuration - Max loops: {self.max_loops}" + ) + + self.conversation = Conversation(time_enabled=False) # Reliability checks self.reliability_checks() - # Handle teams - self.handle_teams() - - # List all agents - list_all_agents(self.agents, self.conversation, self.name) - self.director = self.setup_director() - def handle_teams(self): - if not self.teams: - return + self.add_context_to_director() - # Use list comprehension for faster team processing - team_list = [team.model_dump() for team in self.teams] + if self.verbose: + logger.success( + f"✅ HierarchicalSwarm initialized successfully: Name {self.name}" + ) - # Use extend() instead of append() in a loop for better performance - self.agents.extend( - agent for team in team_list for agent in team["agents"] - ) + def add_context_to_director(self): + """Add agent context to the director's conversation.""" + try: + if self.verbose: + logger.info("📝 Adding agent context to director") + + list_all_agents( + agents=self.agents, + conversation=self.conversation, + add_to_conversation=True, + add_collaboration_prompt=self.add_collaboration_prompt, + ) - # Add conversation message - self.conversation.add( - role="System", - content=f"Teams Available: {any_to_str(team_list)}", - ) + if self.verbose: + logger.success( + "✅ Agent context added to director successfully" + ) + + except Exception as e: + error_msg = ( + f"❌ Failed to add context to director: {str(e)}" + ) + logger.error( + f"{error_msg}\n🔍 Traceback: {traceback.format_exc()}" + ) def setup_director(self): - director = OpenAIFunctionCaller( - model_name=self.director_model_name, - system_prompt=HIEARCHICAL_SWARM_SYSTEM_PROMPT, - api_key=os.getenv("OPENAI_API_KEY"), - temperature=0.5, - base_model=SwarmSpec, - max_tokens=10000, - ) + """Set up the director agent with proper configuration.""" + try: + if self.verbose: + logger.info("🎯 Setting up director agent") + + schema = BaseTool().base_model_to_dict(SwarmSpec) + + if self.verbose: + logger.debug(f"📋 Director schema: {schema}") + + # if self.director is not None: + # # if litellm_check_for_tools(self.director.model_name) is True: + # self.director.add_tool_schema([schema]) + + # if self.verbose: + # logger.success( + # "✅ Director agent setup completed successfully" + # ) + + # return self.director + # else: + return Agent( + agent_name=self.director_name, + agent_description="A director agent that can create a plan and distribute orders to agents", + model_name=self.director_model_name, + max_loops=1, + base_model=SwarmSpec, + tools_list_dictionary=[schema], + output_type="dict-all-except-first", + ) - return director + except Exception as e: + error_msg = f"❌ Failed to setup director: {str(e)}\n🔍 Traceback: {traceback.format_exc()}\n🐛 If this issue persists, please report it at: https://github.com/kyegomez/swarms/issues" + logger.error(error_msg) def reliability_checks(self): """ Checks if there are any agents and a director set for the swarm. Raises ValueError if either condition is not met. """ + try: + if self.verbose: + logger.info( + f"🔍 Running reliability checks for swarm: {self.name}" + ) - logger.info(f"🔍 CHECKING RELIABILITY OF SWARM: {self.name}") - - if len(self.agents) == 0: - raise ValueError( - "No agents found in the swarm. At least one agent must be provided to create a hierarchical swarm." - ) + if not self.agents or len(self.agents) == 0: + raise ValueError( + "No agents found in the swarm. At least one agent must be provided to create a hierarchical swarm." + ) - if self.max_loops == 0: - raise ValueError( - "Max loops must be greater than 0. Please set a valid number of loops." - ) + if self.max_loops <= 0: + raise ValueError( + "Max loops must be greater than 0. Please set a valid number of loops." + ) - if self.director is None: - self.director = self.agents[0] + if not self.director: + raise ValueError( + "Director not set for the swarm. A director agent is required to coordinate and orchestrate tasks among the agents." + ) - if not self.director: - raise ValueError( - "Director not set for the swarm. A director agent is required to coordinate and orchestrate tasks among the agents." - ) + if self.verbose: + logger.success( + f"✅ Reliability checks passed for swarm: {self.name}" + ) + logger.info( + f"📊 Swarm stats - Agents: {len(self.agents)}, Max loops: {self.max_loops}" + ) - logger.info(f"🔍 RELIABILITY CHECKS PASSED: {self.name}") + except Exception as e: + error_msg = f"❌ Failed to setup director: {str(e)}\n🔍 Traceback: {traceback.format_exc()}\n🐛 If this issue persists, please report it at: https://github.com/kyegomez/swarms/issues" + logger.error(error_msg) def run_director( - self, task: str, loop_context: str = "", img: str = None + self, + task: str, + img: str = None, ) -> SwarmSpec: """ Runs a task through the director agent with the current conversation context. :param task: The task to be executed by the director. - :param loop_context: Additional context specific to the current loop. :param img: Optional image to be used with the task. :return: The SwarmSpec containing the director's orders. """ - # Create a comprehensive context for the director - director_context = f"History: {self.conversation.get_str()}" + try: + if self.verbose: + logger.info( + f"🎯 Running director with task: {task[:100]}..." + ) - if loop_context: - director_context += f"\n\nCurrent Loop ({self.current_loop}/{self.max_loops}): {loop_context}" + if self.planning_director_agent is not None: + plan = self.planning_director_agent.run( + task=f"History: {self.conversation.get_str()} \n\n Create a detailed step by step comprehensive plan for the director to execute the task: {task}", + img=img, + ) - director_context += f"\n\nYour Task: {task}" + task += plan - # Run the director with the context - function_call = self.director.run(task=director_context) + # Run the director with the context + function_call = self.director.run( + task=f"History: {self.conversation.get_str()} \n\n Task: {task}", + img=img, + ) - formatter.print_panel( - f"Director Output (Loop {self.current_loop}/{self.max_loops}):\n{function_call}", - title="Director's Orders", - ) + self.conversation.add( + role="Director", content=function_call + ) - # Add director's output to the conversation - self.conversation.add( - role="Director", - content=f"Loop {self.current_loop}/{self.max_loops}: {function_call}", - ) + if self.verbose: + logger.success("✅ Director execution completed") + logger.debug( + f"📋 Director output type: {type(function_call)}" + ) - return function_call + return function_call - def run( - self, task: str, img: str = None, *args, **kwargs - ) -> Union[str, Dict, List]: - """ - Runs a task through the swarm, involving the director and agents through multiple loops. + except Exception as e: + error_msg = f"❌ Failed to setup director: {str(e)}\n🔍 Traceback: {traceback.format_exc()}\n🐛 If this issue persists, please report it at: https://github.com/kyegomez/swarms/issues" + logger.error(error_msg) - :param task: The task to be executed by the swarm. - :param img: Optional image to be used with the task. - :return: The output of the swarm's task execution in the specified format. + def step(self, task: str, img: str = None, *args, **kwargs): + """ + Runs a single step of the hierarchical swarm. """ - # Add the initial task to the conversation - self.conversation.add(role="User", content=f"Task: {task}") + try: + if self.verbose: + logger.info( + f"👣 Executing single step for task: {task[:100]}..." + ) - # Reset loop counter and agent outputs - self.current_loop = 0 - self.agent_outputs = {} + output = self.run_director(task=task, img=img) - # Initialize loop context - loop_context = "Initial planning phase" + # Parse the orders + plan, orders = self.parse_orders(output) - # Execute the loops - for loop_idx in range(self.max_loops): - self.current_loop = loop_idx + 1 + if self.verbose: + logger.info( + f"📋 Parsed plan and {len(orders)} orders" + ) - # Log loop start - logger.info( - f"Starting loop {self.current_loop}/{self.max_loops}" - ) + # Execute the orders + outputs = self.execute_orders(orders) - # Get director's orders - swarm_spec = self.run_director( - task=task, loop_context=loop_context, img=img - ) + if self.verbose: + logger.info(f"⚡ Executed {len(outputs)} orders") - # Add the swarm specification to the conversation - self.add_goal_and_more_in_conversation(swarm_spec) + feedback = self.feedback_director(outputs) - # Parse and execute the orders - orders_list = self.parse_swarm_spec(swarm_spec) + if self.verbose: + logger.success("✅ Step completed successfully") - # Store outputs for this loop - self.agent_outputs[self.current_loop] = {} + return feedback - # Execute each order - for order in orders_list: - agent_output = self.run_agent( - agent_name=order.agent_name, - task=order.task, - img=img, - ) + except Exception as e: + error_msg = f"❌ Failed to setup director: {str(e)}\n🔍 Traceback: {traceback.format_exc()}\n🐛 If this issue persists, please report it at: https://github.com/kyegomez/swarms/issues" + logger.error(error_msg) - # Store the agent's output for this loop - self.agent_outputs[self.current_loop][ - order.agent_name - ] = agent_output + def run(self, task: str, img: str = None, *args, **kwargs): + """ + Executes the hierarchical swarm for a specified number of feedback loops. - # Prepare context for the next loop - loop_context = self.compile_loop_context( - self.current_loop - ) + :param task: The initial task to be processed by the swarm. + :param img: Optional image input for the agents. + :param args: Additional positional arguments. + :param kwargs: Additional keyword arguments. + :return: The formatted conversation history as output. + """ + try: + current_loop = 0 + last_output = None - # If this is the last loop, break out - if self.current_loop >= self.max_loops: - break + if self.verbose: + logger.info( + f"🚀 Starting hierarchical swarm run: {self.name}" + ) + logger.info( + f"📊 Configuration - Max loops: {self.max_loops}" + ) - # Return the results in the specified format - return history_output_formatter( - self.conversation, self.output_type - ) + while current_loop < self.max_loops: + if self.verbose: + logger.info( + f"🔄 Loop {current_loop + 1}/{self.max_loops} - Processing task" + ) + + # For the first loop, use the original task. + # For subsequent loops, use the feedback from the previous loop as context. + if current_loop == 0: + loop_task = task + else: + loop_task = ( + f"Previous loop results: {last_output}\n\n" + f"Original task: {task}\n\n" + "Based on the previous results and any feedback, continue with the next iteration of the task. " + "Refine, improve, or complete any remaining aspects of the analysis." + ) + + # Execute one step of the swarm + try: + last_output = self.step( + task=loop_task, img=img, *args, **kwargs + ) + + if self.verbose: + logger.success( + f"✅ Loop {current_loop + 1} completed successfully" + ) + + except Exception as e: + error_msg = f"❌ Failed to setup director: {str(e)}\n🔍 Traceback: {traceback.format_exc()}\n🐛 If this issue persists, please report it at: https://github.com/kyegomez/swarms/issues" + logger.error(error_msg) + + current_loop += 1 + + # Add loop completion marker to conversation + self.conversation.add( + role="System", + content=f"--- Loop {current_loop}/{self.max_loops} completed ---", + ) - def compile_loop_context(self, loop_number: int) -> str: - """ - Compiles the context for a specific loop, including all agent outputs. + if self.verbose: + logger.success( + f"🎉 Hierarchical swarm run completed: {self.name}" + ) + logger.info( + f"📊 Total loops executed: {current_loop}" + ) - :param loop_number: The loop number to compile context for. - :return: A string representation of the loop context. - """ - if loop_number not in self.agent_outputs: - return "No agent outputs available for this loop." + return history_output_formatter( + conversation=self.conversation, type=self.output_type + ) - context = f"Results from loop {loop_number}:\n" + except Exception as e: + error_msg = f"❌ Failed to setup director: {str(e)}\n🔍 Traceback: {traceback.format_exc()}\n🐛 If this issue persists, please report it at: https://github.com/kyegomez/swarms/issues" + logger.error(error_msg) - for agent_name, output in self.agent_outputs[ - loop_number - ].items(): - context += f"\n--- {agent_name}'s Output ---\n{output}\n" + def feedback_director(self, outputs: list): + """Provide feedback from the director based on agent outputs.""" + try: + if self.verbose: + logger.info("📝 Generating director feedback") - return context + task = f"History: {self.conversation.get_str()} \n\n" - def add_name_and_description(self): - """ - Adds the swarm's name and description to the conversation. - """ - self.conversation.add( - role="System", - content=f"\n\nSwarm Name: {self.name}\n\nSwarm Description: {self.description}", - ) + feedback_director = Agent( + agent_name="Director", + agent_description="Director module that provides feedback to the worker agents", + model_name=self.director_model_name, + max_loops=1, + system_prompt=HIEARCHICAL_SWARM_SYSTEM_PROMPT, + ) - def find_agent(self, name: str) -> Optional[Agent]: - """ - Finds an agent by its name within the swarm. + output = feedback_director.run( + task=( + "You are the Director. Carefully review the outputs generated by all the worker agents in the previous step. " + "Provide specific, actionable feedback for each agent, highlighting strengths, weaknesses, and concrete suggestions for improvement. " + "If any outputs are unclear, incomplete, or could be enhanced, explain exactly how. " + f"Your feedback should help the agents refine their work in the next iteration. " + f"Worker Agent Responses: {task}" + ) + ) + self.conversation.add(role="Director", content=output) - :param name: The name of the agent to find. - :return: The agent if found, otherwise None. - :raises: ValueError if agent is not found - """ - try: - # Fast path: use list comprehension for quick lookup - matching_agents = [ - agent - for agent in self.agents - if agent.agent_name == name - ] - - if not matching_agents: - error_msg = f"Agent '{name}' not found in the swarm '{self.name}'" - logger.error(error_msg) - return None + if self.verbose: + logger.success( + "✅ Director feedback generated successfully" + ) - return matching_agents[0] + return output except Exception as e: - logger.error(f"Error finding agent '{name}': {str(e)}") - return None + error_msg = f"❌ Failed to setup director: {str(e)}\n🔍 Traceback: {traceback.format_exc()}\n🐛 If this issue persists, please report it at: https://github.com/kyegomez/swarms/issues" + logger.error(error_msg) - def run_agent( - self, agent_name: str, task: str, img: str = None - ) -> str: + def call_single_agent( + self, agent_name: str, task: str, *args, **kwargs + ): """ - Runs a task through a specific agent, providing it with the full conversation context. - - :param agent_name: The name of the agent to execute the task. - :param task: The task to be executed by the agent. - :param img: Optional image to be used with the task. - :return: The output of the agent's task execution. + Calls a single agent with the given task. """ try: - agent = self.find_agent(agent_name) - - # Prepare context for the agent - agent_context = ( - f"Loop: {self.current_loop}/{self.max_loops}\n" - f"History: {self.conversation.get_str()}\n" - f"Your Task: {task}" - ) + if self.verbose: + logger.info(f"📞 Calling agent: {agent_name}") + + # Find agent by name + agent = None + for a in self.agents: + if ( + hasattr(a, "agent_name") + and a.agent_name == agent_name + ): + agent = a + break + + if agent is None: + available_agents = [ + a.agent_name + for a in self.agents + if hasattr(a, "agent_name") + ] + raise ValueError( + f"Agent '{agent_name}' not found in swarm. Available agents: {available_agents}" + ) - # Run the agent with the context - formatter.print_panel( - f"Running agent '{agent_name}' with task: {task}", - title=f"Agent Task - Loop {self.current_loop}/{self.max_loops}", + output = agent.run( + task=f"History: {self.conversation.get_str()} \n\n Task: {task}", + *args, + **kwargs, ) + self.conversation.add(role=agent_name, content=output) - out = agent.run(task=agent_context) - - # Add the agent's output to the conversation - self.conversation.add( - role=agent_name, - content=f"Loop {self.current_loop}/{self.max_loops}: {out}", - ) + if self.verbose: + logger.success( + f"✅ Agent {agent_name} completed task successfully" + ) - formatter.print_panel( - out, - title=f"Output from {agent_name} - Loop {self.current_loop}/{self.max_loops}", - ) + return output - return out except Exception as e: - error_msg = ( - f"Error running agent '{agent_name}': {str(e)}" - ) + error_msg = f"❌ Failed to setup director: {str(e)}\n🔍 Traceback: {traceback.format_exc()}\n🐛 If this issue persists, please report it at: https://github.com/kyegomez/swarms/issues" logger.error(error_msg) - return error_msg - def parse_orders(self, swarm_spec: SwarmSpec) -> List[Any]: + def parse_orders(self, output): """ - Parses the orders from the SwarmSpec and executes them through the agents. - - :param swarm_spec: The SwarmSpec containing the orders to be parsed. - :return: A list of agent outputs. + Parses the orders from the director's output. """ - self.add_goal_and_more_in_conversation(swarm_spec) - orders_list = self.parse_swarm_spec(swarm_spec) - outputs = [] - try: - for order in orders_list: - output = self.run_agent( - agent_name=order.agent_name, - task=order.task, + if self.verbose: + logger.info("📋 Parsing director orders") + logger.debug(f"📊 Output type: {type(output)}") + + import json + + # Handle different output formats from the director + if isinstance(output, list): + # If output is a list, look for function call data + for item in output: + if isinstance(item, dict): + # Check if it's a conversation format with role/content + if "content" in item and isinstance( + item["content"], list + ): + for content_item in item["content"]: + if ( + isinstance(content_item, dict) + and "function" in content_item + ): + function_data = content_item[ + "function" + ] + if "arguments" in function_data: + try: + args = json.loads( + function_data[ + "arguments" + ] + ) + if ( + "plan" in args + and "orders" in args + ): + plan = args["plan"] + orders = [ + HierarchicalOrder( + **order + ) + for order in args[ + "orders" + ] + ] + + if self.verbose: + logger.success( + f"✅ Successfully parsed plan and {len(orders)} orders" + ) + + return plan, orders + except ( + json.JSONDecodeError + ) as json_err: + if self.verbose: + logger.warning( + f"⚠️ JSON decode error: {json_err}" + ) + pass + # Check if it's a direct function call format + elif "function" in item: + function_data = item["function"] + if "arguments" in function_data: + try: + args = json.loads( + function_data["arguments"] + ) + if ( + "plan" in args + and "orders" in args + ): + plan = args["plan"] + orders = [ + HierarchicalOrder(**order) + for order in args[ + "orders" + ] + ] + + if self.verbose: + logger.success( + f"✅ Successfully parsed plan and {len(orders)} orders" + ) + + return plan, orders + except ( + json.JSONDecodeError + ) as json_err: + if self.verbose: + logger.warning( + f"⚠️ JSON decode error: {json_err}" + ) + pass + # If no function call found, raise error + raise ValueError( + f"Unable to parse orders from director output: {output}" + ) + elif isinstance(output, dict): + # Handle direct dictionary format + if "plan" in output and "orders" in output: + plan = output["plan"] + orders = [ + HierarchicalOrder(**order) + for order in output["orders"] + ] + + if self.verbose: + logger.success( + f"✅ Successfully parsed plan and {len(orders)} orders" + ) + + return plan, orders + else: + raise ValueError( + f"Missing 'plan' or 'orders' in director output: {output}" + ) + else: + raise ValueError( + f"Unexpected output format from director: {type(output)}" ) - outputs.append(output) - return outputs except Exception as e: - error_msg = ( - f"Error parsing and executing orders: {str(e)}" - ) + error_msg = f"❌ Failed to setup director: {str(e)}\n🔍 Traceback: {traceback.format_exc()}\n🐛 If this issue persists, please report it at: https://github.com/kyegomez/swarms/issues" logger.error(error_msg) - return [error_msg] - def parse_swarm_spec( - self, swarm_spec: SwarmSpec - ) -> List[HierarchicalOrder]: + def execute_orders(self, orders: list): """ - Parses the SwarmSpec to extract the orders. - - :param swarm_spec: The SwarmSpec to be parsed. - :return: The list of orders extracted from the SwarmSpec. + Executes the orders from the director's output. """ try: - return swarm_spec.orders - except AttributeError: - logger.error( - "Invalid SwarmSpec format: missing 'orders' attribute" - ) - return [] - except Exception as e: - logger.error(f"Error parsing SwarmSpec: {str(e)}") - return [] - - def provide_feedback( - self, agent_outputs: Dict[str, str] - ) -> Dict[str, str]: - """ - Provides feedback to agents based on their outputs. - - :param agent_outputs: A dictionary mapping agent names to their outputs. - :return: A dictionary of feedback for each agent. - """ - feedback = {} + if self.verbose: + logger.info(f"⚡ Executing {len(orders)} orders") + + outputs = [] + for i, order in enumerate(orders): + if self.verbose: + logger.info( + f"📋 Executing order {i+1}/{len(orders)}: {order.agent_name}" + ) + + output = self.call_single_agent( + order.agent_name, order.task + ) + outputs.append(output) - # Compile all agent outputs for the director - agent_outputs_str = "\n\n".join( - f"--- {agent_name} Output ---\n{output}" - for agent_name, output in agent_outputs.items() - ) + if self.verbose: + logger.success( + f"✅ All {len(orders)} orders executed successfully" + ) - # Have the director provide feedback - feedback_task = ( - f"Review the following agent outputs and provide feedback for each agent.\n\n" - f"{agent_outputs_str}" - ) + return outputs - feedback_spec = self.run_director(task=feedback_task) - feedback_orders = self.parse_swarm_spec(feedback_spec) + except Exception as e: + error_msg = f"❌ Failed to setup director: {str(e)}\n🔍 Traceback: {traceback.format_exc()}\n🐛 If this issue persists, please report it at: https://github.com/kyegomez/swarms/issues" + logger.error(error_msg) - # Process each feedback order - for order in feedback_orders: - # The agent receiving feedback - agent_name = order.agent_name - # The feedback content - feedback_content = order.task + def batched_run( + self, tasks: List[str], img: str = None, *args, **kwargs + ): + """ + Executes the hierarchical swarm for a list of tasks. + """ + try: + if self.verbose: + logger.info( + f"🚀 Starting batched hierarchical swarm run: {self.name}" + ) + logger.info( + f"📊 Configuration - Max loops: {self.max_loops}" + ) - # Store the feedback - feedback[agent_name] = feedback_content + # Initialize a list to store the results + results = [] - # Add the feedback to the conversation - self.conversation.add( - role="Director", - content=f"Feedback for {agent_name}: {feedback_content}", - ) + # Process each task in parallel + for task in tasks: + result = self.run(task, img, *args, **kwargs) + results.append(result) - return feedback + if self.verbose: + logger.success( + f"🎉 Batched hierarchical swarm run completed: {self.name}" + ) + logger.info(f"📊 Total tasks processed: {len(tasks)}") - def add_goal_and_more_in_conversation( - self, swarm_spec: SwarmSpec - ) -> None: - """ - Adds the swarm's goals, plan, and rules to the conversation. + return results - :param swarm_spec: The SwarmSpec containing the goals, plan, and rules. - """ - try: - # Directly access and format attributes in one line - self.conversation.add( - role="Director", - content=f"Goals:\n{swarm_spec.goals}\n\nPlan:\n{swarm_spec.plan}\n\nRules:\n{swarm_spec.rules}", - ) except Exception as e: - logger.error( - f"Error adding goals and plan to conversation: {str(e)}" + error_msg = ( + f"❌ Batched hierarchical swarm run failed: {str(e)}" ) - - def batch_run( - self, tasks: List[str], img: str = None - ) -> List[Union[str, Dict, List]]: - """ - Runs multiple tasks sequentially through the swarm. - - :param tasks: The list of tasks to be executed. - :param img: Optional image to be used with the tasks. - :return: A list of outputs from each task execution. - """ - return [self.run(task, img) for task in tasks] - - def check_director_agent_output(self, output: any) -> dict: - if isinstance(output, dict): - return output - elif isinstance(output, str): - try: - # Attempt to parse the string as JSON - return json.loads(output) - except json.JSONDecodeError as e: - # Log an error if the string cannot be parsed + if self.verbose: + logger.error(error_msg) logger.error( - f"Failed to parse output string as JSON: {str(e)}" + f"🔍 Traceback: {traceback.format_exc()}" ) - return {} - else: - # Log an error if the output is neither a dict nor a string - logger.error( - "Output is neither a dictionary nor a string." - ) - return {} diff --git a/swarms/structs/interactive_groupchat.py b/swarms/structs/interactive_groupchat.py index 3174e55c..5613e9ff 100644 --- a/swarms/structs/interactive_groupchat.py +++ b/swarms/structs/interactive_groupchat.py @@ -962,7 +962,7 @@ Remember: You are part of a team. Your response should reflect that you've read, if "@" in task: mentioned_agents = self._extract_mentions(task) else: - pass + mentioned_agents = list(self.agent_map.keys()) # Add user task to conversation self.conversation.add(role="User", content=task) diff --git a/swarms/structs/ma_utils.py b/swarms/structs/ma_utils.py index ccb45617..b0d929c5 100644 --- a/swarms/structs/ma_utils.py +++ b/swarms/structs/ma_utils.py @@ -45,19 +45,36 @@ def list_all_agents( Description: Second agent description... """ - # Compile information about all agents + # Compile and describe all agents in the team total_agents = len(agents) - all_agents = f"Team Name: {name}\n" if name else "" - all_agents += ( - f"Team Description: {description}\n" if description else "" - ) + all_agents = "" + if name: + all_agents += f"Team Name: {name}\n" + if description: + all_agents += f"Team Description: {description}\n" + all_agents += "These are the agents in your team. Each agent has a specific role and expertise to contribute to the team's objectives.\n" all_agents += f"Total Agents: {total_agents}\n\n" - all_agents += "| Agent | Description |\n" - all_agents += "|-------|-------------|\n" - all_agents += "\n".join( - f"| {agent.agent_name} | {agent.description or (agent.system_prompt[:50] + '...' if len(agent.system_prompt) > 50 else agent.system_prompt)} |" - for agent in agents + all_agents += "Below is a summary of your team members and their primary responsibilities:\n" + all_agents += "| Agent Name | Description |\n" + all_agents += "|------------|-------------|\n" + for agent in agents: + agent_name = getattr( + agent, + "agent_name", + getattr(agent, "name", "Unknown Agent"), + ) + # Try to get a meaningful description or fallback to system prompt + agent_desc = getattr(agent, "description", None) + if not agent_desc: + agent_desc = getattr(agent, "system_prompt", "") + if len(agent_desc) > 50: + agent_desc = agent_desc[:50] + "..." + all_agents += f"| {agent_name} | {agent_desc} |\n" + + all_agents += ( + "\nEach agent is designed to handle tasks within their area of expertise. " + "Collaborate effectively by assigning tasks according to these roles." ) if add_to_conversation: @@ -67,13 +84,16 @@ def list_all_agents( content=all_agents, ) - if add_collaboration_prompt: - return get_multi_agent_collaboration_prompt_one( - agents_in_swarm=all_agents + return None + + elif add_collaboration_prompt: + all_agents += get_multi_agent_collaboration_prompt_one( + agents=all_agents ) - else: return all_agents + return all_agents + models = [ "anthropic/claude-3-sonnet-20240229", diff --git a/swarms/utils/formatter.py b/swarms/utils/formatter.py index 5f5faccb..0b546be5 100644 --- a/swarms/utils/formatter.py +++ b/swarms/utils/formatter.py @@ -127,12 +127,27 @@ class Formatter: title: str = "", style: str = "bold blue", ) -> None: - process_thread = threading.Thread( - target=self._print_panel, - args=(content, title, style), - daemon=True, - ) - process_thread.start() + """Print content in a panel with a title and style. + + Args: + content (str): The content to display in the panel + title (str): The title of the panel + style (str): The style to apply to the panel + """ + # Handle None content + if content is None: + content = "No content to display" + + # Convert non-string content to string + if not isinstance(content, str): + content = str(content) + + try: + self._print_panel(content, title, style) + except Exception: + # Fallback to basic printing if panel fails + print(f"\n{title}:") + print(content) def print_table( self, title: str, data: Dict[str, List[str]] diff --git a/swarms/utils/lite_utils.py b/swarms/utils/lite_utils.py new file mode 100644 index 00000000..1f8b0cf0 --- /dev/null +++ b/swarms/utils/lite_utils.py @@ -0,0 +1,5 @@ +def litellm_check_for_tools(model_name: str): + """Check if the model supports tools.""" + from litellm.utils import supports_function_calling + + return supports_function_calling(model_name)