commit
2839b93b6c
@ -1,170 +0,0 @@
|
||||
# Bug Report: Swarms Codebase Issues
|
||||
|
||||
## Bug 1: Error Handling in Daemon Thread (Critical)
|
||||
|
||||
**Location:** `swarms/structs/agent.py` lines 1446-1453
|
||||
|
||||
**Description:** The `_handle_run_error` method creates a daemon thread to handle errors, but the exception raised in `__handle_run_error` will not propagate back to the main thread. This causes silent failures where errors are logged but not properly propagated to the caller.
|
||||
|
||||
**Type:** Concurrency/Error Handling Bug
|
||||
|
||||
**Severity:** Critical - Can lead to silent failures
|
||||
|
||||
**Current Code:**
|
||||
```python
|
||||
def _handle_run_error(self, error: any):
|
||||
process_thread = threading.Thread(
|
||||
target=self.__handle_run_error,
|
||||
args=(error,),
|
||||
daemon=True,
|
||||
)
|
||||
process_thread.start()
|
||||
```
|
||||
|
||||
**Problem:**
|
||||
- The daemon thread will exit when the main thread exits
|
||||
- The `raise error` at the end of `__handle_run_error` occurs in the daemon thread, not the main thread
|
||||
- This means exceptions are lost and not properly handled by the calling code
|
||||
|
||||
**Fix:** Remove the threading wrapper and call the error handler directly, or use proper exception propagation.
|
||||
|
||||
---
|
||||
|
||||
## Bug 2: Method Name Typo (Logic Error)
|
||||
|
||||
**Location:** `swarms/structs/agent.py` lines 2128 and 2122
|
||||
|
||||
**Description:** There are two related typos in the response filtering functionality:
|
||||
1. The method `apply_reponse_filters` has a typo in the name - it should be `apply_response_filters`
|
||||
2. The `add_response_filter` method accesses `self.reponse_filters` instead of `self.response_filters`
|
||||
|
||||
**Type:** Naming/Logic Error
|
||||
|
||||
**Severity:** Medium - Can cause AttributeError when called
|
||||
|
||||
**Current Code:**
|
||||
```python
|
||||
def add_response_filter(self, filter_word: str) -> None:
|
||||
logger.info(f"Adding response filter: {filter_word}")
|
||||
self.reponse_filters.append(filter_word) # TYPO: reponse_filters
|
||||
|
||||
def apply_reponse_filters(self, response: str) -> str: # TYPO: apply_reponse_filters
|
||||
"""
|
||||
Apply the response filters to the response
|
||||
"""
|
||||
logger.info(
|
||||
f"Applying response filters to response: {response}"
|
||||
)
|
||||
for word in self.response_filters:
|
||||
response = response.replace(word, "[FILTERED]")
|
||||
return response
|
||||
```
|
||||
|
||||
**Problem:**
|
||||
- Method name is misspelled: `apply_reponse_filters` instead of `apply_response_filters`
|
||||
- Attribute access is misspelled: `self.reponse_filters` instead of `self.response_filters`
|
||||
- The method is called correctly in `filtered_run` method, suggesting these are typos
|
||||
|
||||
**Fix:** Fix both typos to use correct spelling.
|
||||
|
||||
---
|
||||
|
||||
## Bug 3: Document Ingestion Logic Error (Data Loss)
|
||||
|
||||
**Location:** `swarms/structs/agent.py` lines 2193-2212
|
||||
|
||||
**Description:** The `ingest_docs` method has a logic error where it processes all documents in a loop but only retains the data from the last document. All previous documents are processed but their data is overwritten and lost.
|
||||
|
||||
**Type:** Logic Error
|
||||
|
||||
**Severity:** High - Causes data loss
|
||||
|
||||
**Current Code:**
|
||||
```python
|
||||
def ingest_docs(self, docs: List[str], *args, **kwargs):
|
||||
"""Ingest the docs into the memory
|
||||
|
||||
Args:
|
||||
docs (List[str]): Documents of pdfs, text, csvs
|
||||
|
||||
Returns:
|
||||
None
|
||||
"""
|
||||
try:
|
||||
for doc in docs:
|
||||
data = data_to_text(doc)
|
||||
|
||||
return self.short_memory.add(
|
||||
role=self.user_name, content=data
|
||||
)
|
||||
except Exception as error:
|
||||
logger.info(f"Error ingesting docs: {error}", "red")
|
||||
```
|
||||
|
||||
**Problem:**
|
||||
- The `data` variable is overwritten on each iteration
|
||||
- Only the last document's data is actually added to memory
|
||||
- All previous documents are processed but their data is lost
|
||||
- The method should either process documents individually or combine all data
|
||||
|
||||
**Fix:** Accumulate all document data or process each document individually.
|
||||
|
||||
---
|
||||
|
||||
## Impact Assessment
|
||||
|
||||
1. **Bug 1 (Critical):** Can cause silent failures in production, making debugging difficult
|
||||
2. **Bug 2 (Medium):** Will cause AttributeError when the method is called correctly
|
||||
3. **Bug 3 (High):** Causes data loss when ingesting multiple documents
|
||||
|
||||
## Fixes Applied
|
||||
|
||||
### Bug 1 Fix - Error Handling
|
||||
**Status:** ✅ FIXED
|
||||
|
||||
Changed the `_handle_run_error` method to call `__handle_run_error` directly instead of using a daemon thread:
|
||||
```python
|
||||
def _handle_run_error(self, error: any):
|
||||
# Handle error directly instead of using daemon thread
|
||||
# to ensure proper exception propagation
|
||||
self.__handle_run_error(error)
|
||||
```
|
||||
|
||||
### Bug 2 Fix - Method Name Typos
|
||||
**Status:** ✅ FIXED
|
||||
|
||||
Fixed both typos in the response filtering functionality:
|
||||
1. Renamed `apply_reponse_filters` to `apply_response_filters`
|
||||
2. Fixed `self.reponse_filters` to `self.response_filters`
|
||||
|
||||
### Bug 3 Fix - Document Ingestion Logic
|
||||
**Status:** ✅ FIXED
|
||||
|
||||
Modified the `ingest_docs` method to process all documents and combine their content:
|
||||
```python
|
||||
def ingest_docs(self, docs: List[str], *args, **kwargs):
|
||||
try:
|
||||
# Process all documents and combine their content
|
||||
all_data = []
|
||||
for doc in docs:
|
||||
data = data_to_text(doc)
|
||||
all_data.append(f"Document: {doc}\n{data}")
|
||||
|
||||
# Combine all document content
|
||||
combined_data = "\n\n".join(all_data)
|
||||
|
||||
return self.short_memory.add(
|
||||
role=self.user_name, content=combined_data
|
||||
)
|
||||
except Exception as error:
|
||||
logger.info(f"Error ingesting docs: {error}", "red")
|
||||
```
|
||||
|
||||
## Recommendations
|
||||
|
||||
1. ✅ Fixed the error handling to properly propagate exceptions
|
||||
2. ✅ Corrected the method name typos
|
||||
3. ✅ Fixed the document ingestion logic to process all documents
|
||||
4. Add unit tests to prevent similar issues in the future
|
||||
5. Consider adding linting rules to catch method name typos
|
||||
6. Consider code review processes to catch similar issues
|
After Width: | Height: | Size: 175 KiB |
@ -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
|
@ -1,349 +1,305 @@
|
||||
# Enterprise-Grade and Production Ready Agents
|
||||
# Introduction to Multi-Agent Collaboration
|
||||
|
||||
Swarms is an enterprise grade and production ready multi-agent collaboration framework that enables you to orchestrate many agents to work collaboratively at scale to automate real-world activities.
|
||||
---
|
||||
|
||||
| **Feature** | **Description** | **Performance Impact** | **Documentation Link** |
|
||||
|------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------|-------------------------------|
|
||||
| Models | Pre-trained models that can be utilized for various tasks within the swarm framework. | ⭐⭐⭐ | [Documentation](https://docs.swarms.world/en/latest/swarms/models/) |
|
||||
| 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]() |
|
||||
## 🚀 Benefits of Multi-Agent Collaboration
|
||||
|
||||
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.
|
||||
<div align="center">
|
||||
<img src="/assets/img/benefits.png" alt="Benefits of Multi-Agent Collaboration" width="700"/>
|
||||
<br/>
|
||||
<em>Fig. 1: Key benefits and structure of multi-agent collaboration</em>
|
||||
</div>
|
||||
|
||||
----
|
||||
### Why Multi-Agent Architectures?
|
||||
|
||||
## Install 💻
|
||||
`$ pip3 install -U swarms`
|
||||
Multi-agent systems unlock new levels of intelligence, reliability, and efficiency by enabling agents to work together. Here are the core benefits:
|
||||
|
||||
---
|
||||
1. **Reduction of Hallucination**: Cross-verification between agents ensures more accurate, reliable outputs by reducing hallucination.
|
||||
2. **Extended Memory**: Agents share knowledge and task history, achieving collective long-term memory for smarter, more adaptive responses.
|
||||
3. **Specialization & Task Distribution**: Delegating tasks to specialized agents boosts efficiency and quality.
|
||||
4. **Parallel Processing**: Multiple agents work simultaneously, greatly increasing speed and throughput.
|
||||
5. **Scalability & Adaptability**: Systems can dynamically scale and adapt, maintaining efficiency as demands change.
|
||||
|
||||
# Usage Examples 🤖
|
||||
---
|
||||
|
||||
### Google Collab Example
|
||||
Run example in Collab: <a target="_blank" href="https://colab.research.google.com/github/kyegomez/swarms/blob/master/examples/collab/swarms_example.ipynb">
|
||||
<img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/>
|
||||
</a>
|
||||
## 🏗️ Multi-Agent Architectures For Production Deployments
|
||||
|
||||
---
|
||||
`swarms` provides a variety of powerful, pre-built multi-agent architectures enabling you to orchestrate agents in various ways. Choose the right structure for your specific problem to build efficient and reliable production systems.
|
||||
|
||||
## `Agents`
|
||||
A fully plug-and-play autonomous agent powered by an LLM extended by a long-term memory database, and equipped with function calling for tool usage! By passing in an LLM, you can create a fully autonomous agent with extreme customization and reliability, ready for real-world task automation!
|
||||
| **Architecture** | **Description** | **Best For** |
|
||||
|---|---|---|
|
||||
| **[SequentialWorkflow](https://docs.swarms.world/en/latest/swarms/structs/sequential_workflow/)** | Agents execute tasks in a linear chain; one agent's output is the next one's input. | Step-by-step processes like data transformation pipelines, report generation. |
|
||||
| **[ConcurrentWorkflow](https://docs.swarms.world/en/latest/swarms/structs/concurrent_workflow/)** | Agents run tasks simultaneously for maximum efficiency. | High-throughput tasks like batch processing, parallel data analysis. |
|
||||
| **[AgentRearrange](https://docs.swarms.world/en/latest/swarms/structs/agent_rearrange/)** | Dynamically maps complex relationships (e.g., `a -> b, c`) between agents. | Flexible and adaptive workflows, task distribution, dynamic routing. |
|
||||
| **[GraphWorkflow](https://docs.swarms.world/en/latest/swarms/structs/graph_workflow/)** | Orchestrates agents as nodes in a Directed Acyclic Graph (DAG). | Complex projects with intricate dependencies, like software builds. |
|
||||
| **[MixtureOfAgents (MoA)](https://docs.swarms.world/en/latest/swarms/structs/moa/)** | Utilizes multiple expert agents in parallel and synthesizes their outputs. | Complex problem-solving, achieving state-of-the-art performance through collaboration. |
|
||||
| **[GroupChat](https://docs.swarms.world/en/latest/swarms/structs/group_chat/)** | Agents collaborate and make decisions through a conversational interface. | Real-time collaborative decision-making, negotiations, brainstorming. |
|
||||
| **[ForestSwarm](https://docs.swarms.world/en/latest/swarms/structs/forest_swarm/)** | Dynamically selects the most suitable agent or tree of agents for a given task. | Task routing, optimizing for expertise, complex decision-making trees. |
|
||||
| **[SpreadSheetSwarm](https://docs.swarms.world/en/latest/swarms/structs/spreadsheet_swarm/)** | Manages thousands of agents concurrently, tracking tasks and outputs in a structured format. | Massive-scale parallel operations, large-scale data generation and analysis. |
|
||||
| **[SwarmRouter](https://docs.swarms.world/en/latest/swarms/structs/swarm_router/)** | Universal orchestrator that provides a single interface to run any type of swarm with dynamic selection. | Simplifying complex workflows, switching between swarm strategies, unified multi-agent management. |
|
||||
| **[HierarchicalSwarm](https://docs.swarms.world/en/latest/swarms/structs/hierarchical_swarm/)** | Director agent coordinates specialized worker agents in a hierarchy. | Complex, multi-stage tasks, iterative refinement, enterprise workflows. |
|
||||
| **[Hybrid Hierarchical-Cluster Swarm (HHCS)](https://docs.swarms.world/en/latest/swarms/structs/hhcs/)** | Router agent distributes tasks to specialized swarms for parallel, hierarchical processing. | Enterprise-scale, multi-domain, and highly complex workflows. |
|
||||
|
||||
Features:
|
||||
---
|
||||
|
||||
✅ Any LLM / Any framework
|
||||
### 🏢 HierarchicalSwarm Example
|
||||
|
||||
✅ Extremely customize-able with max loops, autosaving, import docs (PDFS, TXT, CSVs, etc), tool usage, etc etc
|
||||
Hierarchical architectures enable structured, iterative, and scalable problem-solving by combining a director (or router) agent with specialized worker agents or swarms. Below are two key patterns:
|
||||
|
||||
✅ Long term memory database with RAG (ChromaDB, Pinecone, Qdrant)
|
||||
|
||||
```python
|
||||
from swarms import Agent
|
||||
from swarms.structs.hiearchical_swarm import HierarchicalSwarm
|
||||
|
||||
## Initialize the workflow
|
||||
agent = Agent(temperature=0.5, model_name="gpt-4o-mini", max_tokens=4000, max_loops=1, autosave=True, dashboard=True)
|
||||
# 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",
|
||||
)
|
||||
|
||||
# Run the workflow on a task
|
||||
agent.run("Generate a 10,000 word blog on health and wellness.")
|
||||
```
|
||||
# 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
|
||||
result = swarm.run(task="Analyze the market potential for Tesla (TSLA) stock")
|
||||
print(result)
|
||||
```
|
||||
|
||||
### `Agent` + Long Term Memory
|
||||
`Agent` equipped with quasi-infinite long term memory. Great for long document understanding, analysis, and retrieval.
|
||||
[Full HierarchicalSwarm Documentation →](https://docs.swarms.world/en/latest/swarms/structs/hierarchical_swarm/)
|
||||
|
||||
```python
|
||||
from swarms import Agent
|
||||
from swarm_models import OpenAIChat
|
||||
from swarms_memory import ChromaDB # Copy and paste the code and put it in your own local directory.
|
||||
|
||||
# Making an instance of the ChromaDB class
|
||||
memory = ChromaDB(
|
||||
metric="cosine",
|
||||
n_results=3,
|
||||
output_dir="results",
|
||||
docs_folder="docs",
|
||||
)
|
||||
|
||||
# Initializing the agent with the Gemini instance and other parameters
|
||||
agent = Agent(
|
||||
agent_name="Covid-19-Chat",
|
||||
agent_description=(
|
||||
"This agent provides information about COVID-19 symptoms."
|
||||
),
|
||||
llm=OpenAIChat(),
|
||||
max_loops="auto",
|
||||
autosave=True,
|
||||
verbose=True,
|
||||
long_term_memory=memory,
|
||||
stopping_condition="finish",
|
||||
)
|
||||
|
||||
# Defining the task and image path
|
||||
task = ("What are the symptoms of COVID-19?",)
|
||||
### SequentialWorkflow
|
||||
|
||||
# Running the agent with the specified task and image
|
||||
out = agent.run(task)
|
||||
print(out)
|
||||
A `SequentialWorkflow` executes tasks in a strict order, forming a pipeline where each agent builds upon the work of the previous one. `SequentialWorkflow` is Ideal for processes that have clear, ordered steps. This ensures that tasks with dependencies are handled correctly.
|
||||
|
||||
```python
|
||||
from swarms import Agent, SequentialWorkflow
|
||||
|
||||
# Initialize agents for a 3-step process
|
||||
# 1. Generate an idea
|
||||
idea_generator = Agent(agent_name="IdeaGenerator", system_prompt="Generate a unique startup idea.", model_name="gpt-4o-mini")
|
||||
# 2. Validate the idea
|
||||
validator = Agent(agent_name="Validator", system_prompt="Take this startup idea and analyze its market viability.", model_name="gpt-4o-mini")
|
||||
# 3. Create a pitch
|
||||
pitch_creator = Agent(agent_name="PitchCreator", system_prompt="Write a 3-sentence elevator pitch for this validated startup idea.", model_name="gpt-4o-mini")
|
||||
|
||||
# Create the sequential workflow
|
||||
workflow = SequentialWorkflow(agents=[idea_generator, validator, pitch_creator])
|
||||
|
||||
# Run the workflow
|
||||
elevator_pitch = workflow.run()
|
||||
print(elevator_pitch)
|
||||
```
|
||||
|
||||
### ConcurrentWorkflow (with `SpreadSheetSwarm`)
|
||||
|
||||
### `Agent` ++ Long Term Memory ++ Tools!
|
||||
An LLM equipped with long term memory and tools, a full stack agent capable of automating all and any digital tasks given a good prompt.
|
||||
A concurrent workflow runs multiple agents simultaneously. `SpreadSheetSwarm` is a powerful implementation that can manage thousands of concurrent agents and log their outputs to a CSV file. Use this architecture for high-throughput tasks that can be performed in parallel, drastically reducing execution time.
|
||||
|
||||
```python
|
||||
from swarms import Agent, ChromaDB, OpenAIChat
|
||||
|
||||
# Making an instance of the ChromaDB class
|
||||
memory = ChromaDB(
|
||||
metric="cosine",
|
||||
n_results=3,
|
||||
output_dir="results",
|
||||
docs_folder="docs",
|
||||
)
|
||||
from swarms import Agent, SpreadSheetSwarm
|
||||
|
||||
# Initialize a tool
|
||||
def search_api(query: str):
|
||||
# Add your logic here
|
||||
return query
|
||||
|
||||
# Initializing the agent with the Gemini instance and other parameters
|
||||
agent = Agent(
|
||||
agent_name="Covid-19-Chat",
|
||||
agent_description=(
|
||||
"This agent provides information about COVID-19 symptoms."
|
||||
),
|
||||
llm=OpenAIChat(),
|
||||
max_loops="auto",
|
||||
autosave=True,
|
||||
verbose=True,
|
||||
long_term_memory=memory,
|
||||
stopping_condition="finish",
|
||||
tools=[search_api],
|
||||
)
|
||||
# Define a list of tasks (e.g., social media posts to generate)
|
||||
platforms = ["Twitter", "LinkedIn", "Instagram"]
|
||||
|
||||
# Defining the task and image path
|
||||
task = ("What are the symptoms of COVID-19?",)
|
||||
|
||||
# Running the agent with the specified task and image
|
||||
out = agent.run(task)
|
||||
print(out)
|
||||
# Create an agent for each task
|
||||
agents = [
|
||||
Agent(
|
||||
agent_name=f"{platform}-Marketer",
|
||||
system_prompt=f"Generate a real estate marketing post for {platform}.",
|
||||
model_name="gpt-4o-mini",
|
||||
)
|
||||
for platform in platforms
|
||||
]
|
||||
|
||||
# Initialize the swarm to run these agents concurrently
|
||||
swarm = SpreadSheetSwarm(
|
||||
agents=agents,
|
||||
autosave_on=True,
|
||||
save_file_path="marketing_posts.csv",
|
||||
)
|
||||
|
||||
# Run the swarm with a single, shared task description
|
||||
property_description = "A beautiful 3-bedroom house in sunny California."
|
||||
swarm.run(task=f"Generate a post about: {property_description}")
|
||||
# Check marketing_posts.csv for the results!
|
||||
```
|
||||
|
||||
### AgentRearrange
|
||||
|
||||
### Devin
|
||||
Implementation of Devin in less than 90 lines of code with several tools:
|
||||
terminal, browser, and edit files.
|
||||
Inspired by `einsum`, `AgentRearrange` lets you define complex, non-linear relationships between agents using a simple string-based syntax. [Learn more](https://docs.swarms.world/en/latest/swarms/structs/agent_rearrange/). This architecture is Perfect for orchestrating dynamic workflows where agents might work in parallel, sequence, or a combination of both.
|
||||
|
||||
```python
|
||||
from swarms import Agent
|
||||
from swarm_models import Anthropic
|
||||
import subprocess
|
||||
from swarms import Agent, AgentRearrange
|
||||
|
||||
# Model
|
||||
llm = Anthropic(
|
||||
temperature=0.1,
|
||||
)
|
||||
# Define agents
|
||||
researcher = Agent(agent_name="researcher", model_name="gpt-4o-mini")
|
||||
writer = Agent(agent_name="writer", model_name="gpt-4o-mini")
|
||||
editor = Agent(agent_name="editor", model_name="gpt-4o-mini")
|
||||
|
||||
# Tools
|
||||
def terminal(
|
||||
code: str,
|
||||
):
|
||||
"""
|
||||
Run code in the terminal.
|
||||
|
||||
Args:
|
||||
code (str): The code to run in the terminal.
|
||||
|
||||
Returns:
|
||||
str: The output of the code.
|
||||
"""
|
||||
out = subprocess.run(
|
||||
code, shell=True, capture_output=True, text=True
|
||||
).stdout
|
||||
return str(out)
|
||||
|
||||
def browser(query: str):
|
||||
"""
|
||||
Search the query in the browser with the `browser` tool.
|
||||
|
||||
Args:
|
||||
query (str): The query to search in the browser.
|
||||
|
||||
Returns:
|
||||
str: The search results.
|
||||
"""
|
||||
import webbrowser
|
||||
|
||||
url = f"https://www.google.com/search?q={query}"
|
||||
webbrowser.open(url)
|
||||
return f"Searching for {query} in the browser."
|
||||
|
||||
def create_file(file_path: str, content: str):
|
||||
"""
|
||||
Create a file using the file editor tool.
|
||||
|
||||
Args:
|
||||
file_path (str): The path to the file.
|
||||
content (str): The content to write to the file.
|
||||
|
||||
Returns:
|
||||
str: The result of the file creation operation.
|
||||
"""
|
||||
with open(file_path, "w") as file:
|
||||
file.write(content)
|
||||
return f"File {file_path} created successfully."
|
||||
|
||||
def file_editor(file_path: str, mode: str, content: str):
|
||||
"""
|
||||
Edit a file using the file editor tool.
|
||||
|
||||
Args:
|
||||
file_path (str): The path to the file.
|
||||
mode (str): The mode to open the file in.
|
||||
content (str): The content to write to the file.
|
||||
|
||||
Returns:
|
||||
str: The result of the file editing operation.
|
||||
"""
|
||||
with open(file_path, mode) as file:
|
||||
file.write(content)
|
||||
return f"File {file_path} edited successfully."
|
||||
|
||||
|
||||
# Agent
|
||||
agent = Agent(
|
||||
agent_name="Devin",
|
||||
system_prompt=(
|
||||
"Autonomous agent that can interact with humans and other"
|
||||
" agents. Be Helpful and Kind. Use the tools provided to"
|
||||
" assist the user. Return all code in markdown format."
|
||||
),
|
||||
llm=llm,
|
||||
max_loops="auto",
|
||||
autosave=True,
|
||||
dashboard=False,
|
||||
streaming_on=True,
|
||||
verbose=True,
|
||||
stopping_token="<DONE>",
|
||||
interactive=True,
|
||||
tools=[terminal, browser, file_editor, create_file],
|
||||
code_interpreter=True,
|
||||
# streaming=True,
|
||||
# Define a flow: researcher sends work to both writer and editor simultaneously
|
||||
# This is a one-to-many relationship
|
||||
flow = "researcher -> writer, editor"
|
||||
|
||||
# Create the rearrangement system
|
||||
rearrange_system = AgentRearrange(
|
||||
agents=[researcher, writer, editor],
|
||||
flow=flow,
|
||||
)
|
||||
|
||||
# Run the agent
|
||||
out = agent("Create a new file for a plan to take over the world.")
|
||||
print(out)
|
||||
# Run the system
|
||||
# The researcher will generate content, and then both the writer and editor
|
||||
# will process that content in parallel.
|
||||
outputs = rearrange_system.run("Analyze the impact of AI on modern cinema.")
|
||||
print(outputs)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### SwarmRouter: The Universal Swarm Orchestrator
|
||||
|
||||
The `SwarmRouter` simplifies building complex workflows by providing a single interface to run any type of swarm. Instead of importing and managing different swarm classes, you can dynamically select the one you need just by changing the `swarm_type` parameter. [Read the full documentation](https://docs.swarms.world/en/latest/swarms/structs/swarm_router/)
|
||||
|
||||
### `Agent`with Pydantic BaseModel as Output Type
|
||||
The following is an example of an agent that intakes a pydantic basemodel and outputs it at the same time:
|
||||
This makes your code cleaner and more flexible, allowing you to switch between different multi-agent strategies with ease. Here's a complete example that shows how to define agents and then use `SwarmRouter` to execute the same task using different collaborative strategies.
|
||||
|
||||
```python
|
||||
from pydantic import BaseModel, Field
|
||||
from swarms import Agent
|
||||
from swarm_models import Anthropic
|
||||
from swarms.structs.swarm_router import SwarmRouter, SwarmType
|
||||
|
||||
# Define a few generic agents
|
||||
writer = Agent(agent_name="Writer", system_prompt="You are a creative writer.", model_name="gpt-4o-mini")
|
||||
editor = Agent(agent_name="Editor", system_prompt="You are an expert editor for stories.", model_name="gpt-4o-mini")
|
||||
reviewer = Agent(agent_name="Reviewer", system_prompt="You are a final reviewer who gives a score.", model_name="gpt-4o-mini")
|
||||
|
||||
# The agents and task will be the same for all examples
|
||||
agents = [writer, editor, reviewer]
|
||||
task = "Write a short story about a robot who discovers music."
|
||||
|
||||
# --- Example 1: SequentialWorkflow ---
|
||||
# Agents run one after another in a chain: Writer -> Editor -> Reviewer.
|
||||
print("Running a Sequential Workflow...")
|
||||
sequential_router = SwarmRouter(swarm_type=SwarmType.SequentialWorkflow, agents=agents)
|
||||
sequential_output = sequential_router.run(task)
|
||||
print(f"Final Sequential Output:\n{sequential_output}\n")
|
||||
|
||||
# --- Example 2: ConcurrentWorkflow ---
|
||||
# All agents receive the same initial task and run at the same time.
|
||||
print("Running a Concurrent Workflow...")
|
||||
concurrent_router = SwarmRouter(swarm_type=SwarmType.ConcurrentWorkflow, agents=agents)
|
||||
concurrent_outputs = concurrent_router.run(task)
|
||||
# This returns a dictionary of each agent's output
|
||||
for agent_name, output in concurrent_outputs.items():
|
||||
print(f"Output from {agent_name}:\n{output}\n")
|
||||
|
||||
# --- Example 3: MixtureOfAgents ---
|
||||
# All agents run in parallel, and a special 'aggregator' agent synthesizes their outputs.
|
||||
print("Running a Mixture of Agents Workflow...")
|
||||
aggregator = Agent(
|
||||
agent_name="Aggregator",
|
||||
system_prompt="Combine the story, edits, and review into a final document.",
|
||||
model_name="gpt-4o-mini"
|
||||
)
|
||||
moa_router = SwarmRouter(
|
||||
swarm_type=SwarmType.MixtureOfAgents,
|
||||
agents=agents,
|
||||
aggregator_agent=aggregator, # MoA requires an aggregator
|
||||
)
|
||||
aggregated_output = moa_router.run(task)
|
||||
print(f"Final Aggregated Output:\n{aggregated_output}\n")
|
||||
```
|
||||
|
||||
|
||||
# Initialize the schema for the person's information
|
||||
class Schema(BaseModel):
|
||||
name: str = Field(..., title="Name of the person")
|
||||
agent: int = Field(..., title="Age of the person")
|
||||
is_student: bool = Field(..., title="Whether the person is a student")
|
||||
courses: list[str] = Field(
|
||||
..., title="List of courses the person is taking"
|
||||
)
|
||||
The `SwarmRouter` is a powerful tool for simplifying multi-agent orchestration. It provides a consistent and flexible way to deploy different collaborative strategies, allowing you to build more sophisticated applications with less code.
|
||||
|
||||
---
|
||||
|
||||
# Convert the schema to a JSON string
|
||||
tool_schema = Schema(
|
||||
name="Tool Name",
|
||||
agent=1,
|
||||
is_student=True,
|
||||
courses=["Course1", "Course2"],
|
||||
)
|
||||
### MixtureOfAgents (MoA)
|
||||
|
||||
# Define the task to generate a person's information
|
||||
task = "Generate a person's information based on the following schema:"
|
||||
|
||||
# Initialize the agent
|
||||
agent = Agent(
|
||||
agent_name="Person Information Generator",
|
||||
system_prompt=(
|
||||
"Generate a person's information based on the following schema:"
|
||||
),
|
||||
# Set the tool schema to the JSON string -- this is the key difference
|
||||
tool_schema=tool_schema,
|
||||
llm=Anthropic(),
|
||||
max_loops=3,
|
||||
autosave=True,
|
||||
dashboard=False,
|
||||
streaming_on=True,
|
||||
verbose=True,
|
||||
interactive=True,
|
||||
# Set the output type to the tool schema which is a BaseModel
|
||||
output_type=tool_schema, # or dict, or str
|
||||
metadata_output_type="json",
|
||||
# List of schemas that the agent can handle
|
||||
list_base_models=[tool_schema],
|
||||
function_calling_format_type="OpenAI",
|
||||
function_calling_type="json", # or soon yaml
|
||||
The `MixtureOfAgents` architecture processes tasks by feeding them to multiple "expert" agents in parallel. Their diverse outputs are then synthesized by an aggregator agent to produce a final, high-quality result. [Learn more here](https://docs.swarms.world/en/latest/swarms/examples/moa_example/)
|
||||
|
||||
```python
|
||||
from swarms import Agent, MixtureOfAgents
|
||||
|
||||
# Define expert agents
|
||||
financial_analyst = Agent(agent_name="FinancialAnalyst", system_prompt="Analyze financial data.", model_name="gpt-4o-mini")
|
||||
market_analyst = Agent(agent_name="MarketAnalyst", system_prompt="Analyze market trends.", model_name="gpt-4o-mini")
|
||||
risk_analyst = Agent(agent_name="RiskAnalyst", system_prompt="Analyze investment risks.", model_name="gpt-4o-mini")
|
||||
|
||||
# Define the aggregator agent
|
||||
aggregator = Agent(
|
||||
agent_name="InvestmentAdvisor",
|
||||
system_prompt="Synthesize the financial, market, and risk analyses to provide a final investment recommendation.",
|
||||
model_name="gpt-4o-mini"
|
||||
)
|
||||
|
||||
# Run the agent to generate the person's information
|
||||
generated_data = agent.run(task)
|
||||
# Create the MoA swarm
|
||||
moa_swarm = MixtureOfAgents(
|
||||
agents=[financial_analyst, market_analyst, risk_analyst],
|
||||
aggregator_agent=aggregator,
|
||||
)
|
||||
|
||||
# Print the generated data
|
||||
print(f"Generated data: {generated_data}")
|
||||
# Run the swarm
|
||||
recommendation = moa_swarm.run("Should we invest in NVIDIA stock right now?")
|
||||
print(recommendation)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
```
|
||||
### GroupChat
|
||||
|
||||
### Multi Modal Autonomous Agent
|
||||
Run the agent with multiple modalities useful for various real-world tasks in manufacturing, logistics, and health.
|
||||
`GroupChat` creates a conversational environment where multiple agents can interact, discuss, and collaboratively solve a problem. You can define the speaking order or let it be determined dynamically. This architecture is ideal for tasks that benefit from debate and multi-perspective reasoning, such as contract negotiation, brainstorming, or complex decision-making.
|
||||
|
||||
```python
|
||||
# Description: This is an example of how to use the Agent class to run a multi-modal workflow
|
||||
import os
|
||||
from swarms import Agent, GroupChat
|
||||
|
||||
from dotenv import load_dotenv
|
||||
# Define agents for a debate
|
||||
tech_optimist = Agent(agent_name="TechOptimist", system_prompt="Argue for the benefits of AI in society.", model_name="gpt-4o-mini")
|
||||
tech_critic = Agent(agent_name="TechCritic", system_prompt="Argue against the unchecked advancement of AI.", model_name="gpt-4o-mini")
|
||||
|
||||
from swarm_models.gpt4_vision_api import GPT4VisionAPI
|
||||
from swarms.structs import Agent
|
||||
# Create the group chat
|
||||
chat = GroupChat(
|
||||
agents=[tech_optimist, tech_critic],
|
||||
max_loops=4, # Limit the number of turns in the conversation
|
||||
)
|
||||
|
||||
# Load the environment variables
|
||||
load_dotenv()
|
||||
# Run the chat with an initial topic
|
||||
conversation_history = chat.run(
|
||||
"Let's discuss the societal impact of artificial intelligence."
|
||||
)
|
||||
|
||||
# Get the API key from the environment
|
||||
api_key = os.environ.get("OPENAI_API_KEY")
|
||||
# Print the full conversation
|
||||
for message in conversation_history:
|
||||
print(f"[{message['agent_name']}]: {message['content']}")
|
||||
```
|
||||
|
||||
# Initialize the language model
|
||||
llm = GPT4VisionAPI(
|
||||
openai_api_key=api_key,
|
||||
max_tokens=500,
|
||||
)
|
||||
--
|
||||
|
||||
# Initialize the task
|
||||
task = (
|
||||
"Analyze this image of an assembly line and identify any issues such as"
|
||||
" misaligned parts, defects, or deviations from the standard assembly"
|
||||
" process. IF there is anything unsafe in the image, explain why it is"
|
||||
" unsafe and how it could be improved."
|
||||
)
|
||||
img = "assembly_line.jpg"
|
||||
## Connect With Us
|
||||
|
||||
## Initialize the workflow
|
||||
agent = Agent(
|
||||
llm=llm, max_loops="auto", autosave=True, dashboard=True, multi_modal=True
|
||||
)
|
||||
Join our community of agent engineers and researchers for technical support, cutting-edge updates, and exclusive access to world-class agent engineering insights!
|
||||
|
||||
# Run the workflow on a task
|
||||
agent.run(task=task, img=img)
|
||||
```
|
||||
----
|
||||
| Platform | Description | Link |
|
||||
|----------|-------------|------|
|
||||
| 📚 Documentation | Official documentation and guides | [docs.swarms.world](https://docs.swarms.world) |
|
||||
| 📝 Blog | Latest updates and technical articles | [Medium](https://medium.com/@kyeg) |
|
||||
| 💬 Discord | Live chat and community support | [Join Discord](https://discord.gg/jM3Z6M9uMq) |
|
||||
| 🐦 Twitter | Latest news and announcements | [@kyegomez](https://twitter.com/kyegomez) |
|
||||
| 👥 LinkedIn | Professional network and updates | [The Swarm Corporation](https://www.linkedin.com/company/the-swarm-corporation) |
|
||||
| 📺 YouTube | Tutorials and demos | [Swarms Channel](https://www.youtube.com/channel/UC9yXyitkbU_WSy7bd_41SqQ) |
|
||||
| 🎫 Events | Join our community events | [Sign up here](https://lu.ma/5p2jnc2v) |
|
||||
| 🚀 Onboarding Session | Get onboarded with Kye Gomez, creator and lead maintainer of Swarms | [Book Session](https://cal.com/swarms/swarms-onboarding-session) |
|
||||
|
||||
---
|
||||
|
||||
|
@ -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