[ENHANCEMENT][HiearchicalSwarm][Massive improvements to the hiearchical swarm, simplification, flexibility, speed improvements, and much more] [DOCS][HiearchicalSwarm] [Examples][hiearchical_examples]
parent
c9d6660879
commit
fb389903e1
@ -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).
|
@ -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
|
@ -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()
|
@ -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"
|
||||
)
|
@ -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)
|
@ -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)
|
@ -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)
|
@ -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?")
|
File diff suppressed because it is too large
Load Diff
@ -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)
|
Loading…
Reference in new issue