Merge branch 'kyegomez:master' into master2

pull/1097/head
Aksh Parekh 1 day ago committed by GitHub
commit 2b4fd96899
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -18,12 +18,12 @@ If you're adding a new integration, please include:
Maintainer responsibilities:
- General / Misc / if you don't know who to tag: kye@apac.ai
- DataLoaders / VectorStores / Retrievers: kye@apac.ai
- swarms.models: kye@apac.ai
- swarms.memory: kye@apac.ai
- swarms.structures: kye@apac.ai
- General / Misc / if you don't know who to tag: kye@swarms.world
- DataLoaders / VectorStores / Retrievers: kye@swarms.world
- swarms.models: kye@swarms.world
- swarms.memory: kye@swarms.world
- swarms.structures: kye@swarms.world
If no one reviews your PR within a few days, feel free to email Kye at kye@apac.ai
If no one reviews your PR within a few days, feel free to email Kye at kye@swarms.world
See contribution guidelines for more information on how to write/run tests, lint, etc: https://github.com/kyegomez/swarms

@ -11,7 +11,7 @@ jobs:
permissions: write-all
runs-on: ubuntu-latest
steps:
- uses: actions/first-interaction@v3.0.0
- uses: actions/first-interaction@v3.1.0
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
issue-message:

@ -60,7 +60,7 @@ representative at an online or offline event.
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
kye@apac.ai.
kye@swarms.world.
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the

@ -27,7 +27,7 @@
* * * * *
If you discover a security vulnerability in any of the above versions, please report it immediately to our security team by sending an email to kye@apac.ai. We take security vulnerabilities seriously and appreciate your efforts in disclosing them responsibly.
If you discover a security vulnerability in any of the above versions, please report it immediately to our security team by sending an email to kye@swarms.world. We take security vulnerabilities seriously and appreciate your efforts in disclosing them responsibly.
Please provide detailed information on the vulnerability, including steps to reproduce, potential impact, and any known mitigations. Our security team will acknowledge receipt of your report within 24 hours and will provide regular updates on the progress of the investigation.

@ -1,20 +1,18 @@
import orjson
from dotenv import load_dotenv
import json
from swarms.structs.auto_swarm_builder import AutoSwarmBuilder
load_dotenv()
from swarms import AutoSwarmBuilder
swarm = AutoSwarmBuilder(
name="My Swarm",
description="My Swarm Description",
verbose=True,
max_loops=1,
return_agents=True,
execution_type="return-agents",
model_name="gpt-4.1",
)
result = swarm.run(
task="Build a swarm to write a research paper on the topic of AI"
)
print(orjson.dumps(result, option=orjson.OPT_INDENT_2).decode())
print(json.dumps(result, indent=2))

@ -0,0 +1,171 @@
# Medical AOP Example
A real-world demonstration of the Agent Orchestration Protocol (AOP) using medical agents deployed as MCP tools.
## Overview
This example showcases how to:
- Deploy multiple medical agents as MCP tools via AOP
- Use discovery tools for dynamic agent collaboration
- Execute real tool calls with structured schemas
- Integrate with keyless APIs for enhanced context
## Architecture
```mermaid
graph LR
A[Medical Agents] --> B[AOP MCP Server<br/>Port 8000]
B --> C[Client<br/>Cursor/Python]
B --> D[Discovery Tools]
B --> E[Tool Execution]
subgraph "Medical Agents"
F[Chief Medical Officer]
G[Virologist]
H[Internist]
I[Medical Coder]
J[Diagnostic Synthesizer]
end
A --> F
A --> G
A --> H
A --> I
A --> J
```
### Medical Agents
- **Chief Medical Officer**: Coordination, diagnosis, triage
- **Virologist**: Viral disease analysis and ICD-10 coding
- **Internist**: Internal medicine evaluation and HCC tagging
- **Medical Coder**: ICD-10 code assignment and compliance
- **Diagnostic Synthesizer**: Final report synthesis with confidence levels
## Files
| File | Description |
|------|-------------|
| `medical_aop/server.py` | AOP server exposing medical agents as MCP tools |
| `medical_aop/client.py` | Discovery client with real tool execution |
| `README.md` | This documentation |
## Usage
### 1. Start the AOP Server
```bash
python -m examples.aop_examples.medical_aop.server
```
### 2. Configure Cursor MCP Integration
Add to `~/.cursor/mcp.json`:
```json
{
"mcpServers": {
"Medical AOP": {
"type": "http",
"url": "http://localhost:8000/mcp"
}
}
}
```
### 3. Use in Cursor
Enable "Medical AOP" in Cursor's MCP settings, then:
#### Discover agents:
```
Call tool discover_agents with: {}
```
#### Execute medical coding:
```
Call tool Medical Coder with: {"task":"Patient: 45M, egfr 59 ml/min/1.73; non-African American. Provide ICD-10 suggestions and coding notes.","priority":"normal","include_images":false}
```
#### Review infection control:
```
Call tool Chief Medical Officer with: {"task":"Review current hospital infection control protocols in light of recent MRSA outbreak in ICU. Provide executive summary, policy adjustment recommendations, and estimated implementation costs.","priority":"high"}
```
### 4. Run Python Client
```bash
python -m examples.aop_examples.medical_aop.client
```
## Features
### Structured Schemas
- Custom input/output schemas with validation
- Priority levels (low/normal/high)
- Image processing support
- Confidence scoring
### Discovery Tools
| Tool | Description |
|------|-------------|
| `discover_agents` | List all available agents |
| `get_agent_details` | Detailed agent information |
| `search_agents` | Keyword-based agent search |
| `list_agents` | Simple agent name list |
### Real-world Integration
- Keyless API integration (disease.sh for epidemiology data)
- Structured medical coding workflows
- Executive-level policy recommendations
- Cost estimation and implementation timelines
## Response Format
All tools return consistent JSON:
```json
{
"result": "Agent response text",
"success": true,
"error": null,
"confidence": 0.95,
"codes": ["N18.3", "Z51.11"]
}
```
## Configuration
### Server Settings
| Setting | Value |
|---------|-------|
| Port | 8000 |
| Transport | streamable-http |
| Timeouts | 40-50 seconds per agent |
| Logging | INFO level with traceback enabled |
### Agent Metadata
Each agent includes:
- Tags for categorization
- Capabilities for matching
- Role classification
- Model configuration
## Best Practices
1. **Use structured inputs**: Leverage the custom schemas for better results
2. **Chain agents**: Pass results between agents for comprehensive analysis
3. **Monitor timeouts**: Adjust based on task complexity
4. **Validate responses**: Check the `success` field in all responses
5. **Use discovery**: Query available agents before hardcoding tool names
## Troubleshooting
| Issue | Solution |
|-------|----------|
| Connection refused | Ensure server is running on port 8000 |
| Tool not found | Use `discover_agents` to verify available tools |
| Timeout errors | Increase timeout values for complex tasks |
| Schema validation | Ensure input matches the defined JSON schema |
## References
- [AOP Reference](https://docs.swarms.world/en/latest/swarms/structs/aop/)
- [MCP Integration](https://docs.swarms.ai/examples/mcp-integration)
- [Protocol Overview](https://docs.swarms.world/en/latest/protocol/overview/)

File diff suppressed because it is too large Load Diff

@ -110,7 +110,7 @@ for doc in documents:
agent = Agent(
agent_name="RAG-Agent",
agent_description="Agent with Qdrant-powered RAG for enhanced knowledge retrieval",
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
dynamic_temperature_enabled=True,
long_term_memory=rag_db
@ -186,7 +186,7 @@ for i, result in enumerate(results_with_metadata):
agent = Agent(
agent_name="Advanced-RAG-Agent",
agent_description="Advanced agent with metadata-enhanced RAG capabilities",
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
dynamic_temperature_enabled=True,
long_term_memory=rag_db
@ -330,7 +330,7 @@ for doc in company_documents:
agent = Agent(
agent_name="Company-DocQA-Agent",
agent_description="Intelligent document Q&A system for company information",
model_name="gpt-4o",
model_name="gpt-4.1",
long_term_memory=rag_db
)
@ -355,7 +355,7 @@ class KnowledgeBaseAgent:
self.agent = Agent(
agent_name="KB-Management-Agent",
agent_description="Knowledge base management and retrieval system",
model_name="gpt-4o",
model_name="gpt-4.1",
long_term_memory=self.rag_db
)

@ -27,7 +27,7 @@ from swarms import OpenAIAssistant
assistant = OpenAIAssistant(
name="Math Tutor",
instructions="You are a helpful math tutor.",
model="gpt-4o",
model="gpt-4.1",
tools=[{"type": "code_interpreter"}]
)
@ -79,7 +79,7 @@ assistant.add_function(
OpenAIAssistant(
name: str,
instructions: Optional[str] = None,
model: str = "gpt-4o",
model: str = "gpt-4.1",
tools: Optional[List[Dict[str, Any]]] = None,
file_ids: Optional[List[str]] = None,
metadata: Optional[Dict[str, Any]] = None,

@ -377,7 +377,7 @@ consistency_agent = SelfConsistencyAgent(
# Reasoning Duo for collaborative analysis workflows
duo_agent = ReasoningDuo(
model_names=["gpt-4o-mini", "gpt-4o"]
model_names=["gpt-4o-mini", "gpt-4.1"]
)
# Reflexion Agent for adaptive learning scenarios

@ -11,7 +11,7 @@ The ReasoningDuo class implements a dual-agent reasoning system that combines a
|-----------|------|---------|-------------|
| model_name | str | "reasoning-agent-01" | Name identifier for the reasoning agent |
| description | str | "A highly intelligent..." | Description of the reasoning agent's capabilities |
| model_names | list[str] | ["gpt-4o-mini", "gpt-4o"] | Model names for reasoning and main agents |
| model_names | list[str] | ["gpt-4o-mini", "gpt-4.1"] | Model names for reasoning and main agents |
| system_prompt | str | "You are a helpful..." | System prompt for the main agent |
### Methods
@ -31,7 +31,7 @@ from swarms.agents.reasoning_duo import ReasoningDuo
# Initialize the ReasoningDuo
duo = ReasoningDuo(
model_name="reasoning-agent-01",
model_names=["gpt-4o-mini", "gpt-4o"]
model_names=["gpt-4o-mini", "gpt-4.1"]
)
# Run a single task
@ -97,7 +97,7 @@ You can customize both agents by modifying their initialization parameters:
duo = ReasoningDuo(
model_name="custom-reasoning-agent",
description="Specialized financial analysis agent",
model_names=["gpt-4o-mini", "gpt-4o"],
model_names=["gpt-4o-mini", "gpt-4.1"],
system_prompt="You are a financial expert AI assistant..."
)
```

@ -0,0 +1,336 @@
# AOP Cluster Example
This example demonstrates how to use AOPCluster to connect to and manage multiple MCP servers running AOP agents.
## Basic Cluster Setup
```python
import json
from swarms.structs.aop import AOPCluster
# Connect to multiple MCP servers
cluster = AOPCluster(
urls=[
"http://localhost:8000/mcp", # Research and Analysis server
"http://localhost:8001/mcp", # Writing and Code server
"http://localhost:8002/mcp" # Financial server
],
transport="streamable-http"
)
# Get all available tools from all servers
all_tools = cluster.get_tools(output_type="dict")
print(f"Found {len(all_tools)} tools across all servers")
# Pretty print all tools
print(json.dumps(all_tools, indent=2))
```
## Finding Specific Tools
```python
# Find a specific tool by name
research_tool = cluster.find_tool_by_server_name("Research-Agent")
if research_tool:
print("Found Research-Agent tool:")
print(json.dumps(research_tool, indent=2))
else:
print("Research-Agent tool not found")
# Find multiple tools
tool_names = ["Research-Agent", "Analysis-Agent", "Writing-Agent", "Code-Agent"]
found_tools = {}
for tool_name in tool_names:
tool = cluster.find_tool_by_server_name(tool_name)
if tool:
found_tools[tool_name] = tool
print(f"✓ Found {tool_name}")
else:
print(f"✗ {tool_name} not found")
print(f"Found {len(found_tools)} out of {len(tool_names)} tools")
```
## Tool Discovery and Management
```python
# Get tools in different formats
json_tools = cluster.get_tools(output_type="json")
dict_tools = cluster.get_tools(output_type="dict")
str_tools = cluster.get_tools(output_type="str")
print(f"JSON format: {len(json_tools)} tools")
print(f"Dict format: {len(dict_tools)} tools")
print(f"String format: {len(str_tools)} tools")
# Analyze tool distribution across servers
server_tools = {}
for tool in dict_tools:
server_name = tool.get("server", "unknown")
if server_name not in server_tools:
server_tools[server_name] = []
server_tools[server_name].append(tool.get("function", {}).get("name", "unknown"))
print("\nTools by server:")
for server, tools in server_tools.items():
print(f" {server}: {len(tools)} tools - {tools}")
```
## Advanced Cluster Management
```python
class AOPClusterManager:
def __init__(self, urls, transport="streamable-http"):
self.cluster = AOPCluster(urls, transport)
self.tools_cache = {}
self.last_update = None
def refresh_tools(self):
"""Refresh the tools cache"""
self.tools_cache = {}
tools = self.cluster.get_tools(output_type="dict")
for tool in tools:
tool_name = tool.get("function", {}).get("name")
if tool_name:
self.tools_cache[tool_name] = tool
self.last_update = time.time()
return len(self.tools_cache)
def get_tool(self, tool_name):
"""Get a specific tool by name"""
if not self.tools_cache or time.time() - self.last_update > 300: # 5 min cache
self.refresh_tools()
return self.tools_cache.get(tool_name)
def list_tools_by_category(self):
"""Categorize tools by their names"""
categories = {
"research": [],
"analysis": [],
"writing": [],
"code": [],
"financial": [],
"other": []
}
for tool_name in self.tools_cache.keys():
tool_name_lower = tool_name.lower()
if "research" in tool_name_lower:
categories["research"].append(tool_name)
elif "analysis" in tool_name_lower:
categories["analysis"].append(tool_name)
elif "writing" in tool_name_lower:
categories["writing"].append(tool_name)
elif "code" in tool_name_lower:
categories["code"].append(tool_name)
elif "financial" in tool_name_lower:
categories["financial"].append(tool_name)
else:
categories["other"].append(tool_name)
return categories
def get_available_servers(self):
"""Get list of available servers"""
servers = set()
for tool in self.tools_cache.values():
server = tool.get("server", "unknown")
servers.add(server)
return list(servers)
# Usage example
import time
manager = AOPClusterManager([
"http://localhost:8000/mcp",
"http://localhost:8001/mcp",
"http://localhost:8002/mcp"
])
# Refresh and display tools
tool_count = manager.refresh_tools()
print(f"Loaded {tool_count} tools")
# Categorize tools
categories = manager.list_tools_by_category()
for category, tools in categories.items():
if tools:
print(f"{category.title()}: {tools}")
# Get available servers
servers = manager.get_available_servers()
print(f"Available servers: {servers}")
```
## Error Handling and Resilience
```python
class ResilientAOPCluster:
def __init__(self, urls, transport="streamable-http"):
self.urls = urls
self.transport = transport
self.cluster = AOPCluster(urls, transport)
self.failed_servers = set()
def get_tools_with_fallback(self, output_type="dict"):
"""Get tools with fallback for failed servers"""
try:
return self.cluster.get_tools(output_type=output_type)
except Exception as e:
print(f"Error getting tools: {e}")
# Try individual servers
all_tools = []
for url in self.urls:
if url in self.failed_servers:
continue
try:
single_cluster = AOPCluster([url], self.transport)
tools = single_cluster.get_tools(output_type=output_type)
all_tools.extend(tools)
except Exception as server_error:
print(f"Server {url} failed: {server_error}")
self.failed_servers.add(url)
return all_tools
def find_tool_with_retry(self, tool_name, max_retries=3):
"""Find tool with retry logic"""
for attempt in range(max_retries):
try:
return self.cluster.find_tool_by_server_name(tool_name)
except Exception as e:
print(f"Attempt {attempt + 1} failed: {e}")
if attempt < max_retries - 1:
time.sleep(2 ** attempt) # Exponential backoff
return None
# Usage
resilient_cluster = ResilientAOPCluster([
"http://localhost:8000/mcp",
"http://localhost:8001/mcp",
"http://localhost:8002/mcp"
])
# Get tools with error handling
tools = resilient_cluster.get_tools_with_fallback()
print(f"Retrieved {len(tools)} tools")
# Find tool with retry
research_tool = resilient_cluster.find_tool_with_retry("Research-Agent")
if research_tool:
print("Found Research-Agent tool")
else:
print("Research-Agent tool not found after retries")
```
## Monitoring and Health Checks
```python
class AOPClusterMonitor:
def __init__(self, cluster_manager):
self.manager = cluster_manager
self.health_status = {}
def check_server_health(self, url):
"""Check if a server is healthy"""
try:
single_cluster = AOPCluster([url], self.manager.cluster.transport)
tools = single_cluster.get_tools(output_type="dict")
return {
"status": "healthy",
"tool_count": len(tools),
"timestamp": time.time()
}
except Exception as e:
return {
"status": "unhealthy",
"error": str(e),
"timestamp": time.time()
}
def check_all_servers(self):
"""Check health of all servers"""
for url in self.manager.cluster.urls:
health = self.check_server_health(url)
self.health_status[url] = health
status_icon = "✓" if health["status"] == "healthy" else "✗"
print(f"{status_icon} {url}: {health['status']}")
if health["status"] == "healthy":
print(f" Tools available: {health['tool_count']}")
else:
print(f" Error: {health['error']}")
def get_health_summary(self):
"""Get summary of server health"""
healthy_count = sum(1 for status in self.health_status.values()
if status["status"] == "healthy")
total_count = len(self.health_status)
return {
"healthy_servers": healthy_count,
"total_servers": total_count,
"health_percentage": (healthy_count / total_count) * 100 if total_count > 0 else 0
}
# Usage
monitor = AOPClusterMonitor(manager)
monitor.check_all_servers()
summary = monitor.get_health_summary()
print(f"Health Summary: {summary['healthy_servers']}/{summary['total_servers']} servers healthy ({summary['health_percentage']:.1f}%)")
```
## Complete Example
```python
import json
import time
from swarms.structs.aop import AOPCluster
def main():
# Initialize cluster
cluster = AOPCluster(
urls=[
"http://localhost:8000/mcp",
"http://localhost:8001/mcp",
"http://localhost:8002/mcp"
],
transport="streamable-http"
)
print("AOP Cluster Management System")
print("=" * 40)
# Get all tools
print("\n1. Discovering tools...")
tools = cluster.get_tools(output_type="dict")
print(f"Found {len(tools)} tools across all servers")
# List all tool names
tool_names = [tool.get("function", {}).get("name") for tool in tools]
print(f"Available tools: {tool_names}")
# Find specific tools
print("\n2. Finding specific tools...")
target_tools = ["Research-Agent", "Analysis-Agent", "Writing-Agent", "Code-Agent", "Financial-Agent"]
for tool_name in target_tools:
tool = cluster.find_tool_by_server_name(tool_name)
if tool:
print(f"✓ {tool_name}: Available")
else:
print(f"✗ {tool_name}: Not found")
# Display tool details
print("\n3. Tool details:")
for tool in tools[:3]: # Show first 3 tools
print(f"\nTool: {tool.get('function', {}).get('name')}")
print(f"Description: {tool.get('function', {}).get('description')}")
print(f"Parameters: {list(tool.get('function', {}).get('parameters', {}).get('properties', {}).keys())}")
print("\nAOP Cluster setup complete!")
if __name__ == "__main__":
main()
```
This example demonstrates comprehensive AOP cluster management including tool discovery, error handling, health monitoring, and advanced cluster operations.

@ -0,0 +1,164 @@
# AOP Server Setup Example
This example demonstrates how to set up an Agent Orchestration Protocol (AOP) server with multiple specialized agents.
## Overview
The AOP server allows you to deploy multiple agents that can be discovered and called by other agents or clients in the network. This example shows how to create a server with specialized agents for different tasks.
## Code Example
```python
from swarms import Agent
from swarms.structs.aop import (
AOP,
)
# Create specialized agents
research_agent = Agent(
agent_name="Research-Agent",
agent_description="Expert in research, data collection, and information gathering",
model_name="anthropic/claude-sonnet-4-5",
max_loops=1,
top_p=None,
dynamic_temperature_enabled=True,
system_prompt="""You are a research specialist. Your role is to:
1. Gather comprehensive information on any given topic
2. Analyze data from multiple sources
3. Provide well-structured research findings
4. Cite sources and maintain accuracy
5. Present findings in a clear, organized manner
Always provide detailed, factual information with proper context.""",
)
analysis_agent = Agent(
agent_name="Analysis-Agent",
agent_description="Expert in data analysis, pattern recognition, and generating insights",
model_name="anthropic/claude-sonnet-4-5",
max_loops=1,
top_p=None,
dynamic_temperature_enabled=True,
system_prompt="""You are an analysis specialist. Your role is to:
1. Analyze data and identify patterns
2. Generate actionable insights
3. Create visualizations and summaries
4. Provide statistical analysis
5. Make data-driven recommendations
Focus on extracting meaningful insights from information.""",
)
writing_agent = Agent(
agent_name="Writing-Agent",
agent_description="Expert in content creation, editing, and communication",
model_name="anthropic/claude-sonnet-4-5",
max_loops=1,
top_p=None,
dynamic_temperature_enabled=True,
system_prompt="""You are a writing specialist. Your role is to:
1. Create engaging, well-structured content
2. Edit and improve existing text
3. Adapt tone and style for different audiences
4. Ensure clarity and coherence
5. Follow best practices in writing
Always produce high-quality, professional content.""",
)
code_agent = Agent(
agent_name="Code-Agent",
agent_description="Expert in programming, code review, and software development",
model_name="anthropic/claude-sonnet-4-5",
max_loops=1,
top_p=None,
dynamic_temperature_enabled=True,
system_prompt="""You are a coding specialist. Your role is to:
1. Write clean, efficient code
2. Debug and fix issues
3. Review and optimize code
4. Explain programming concepts
5. Follow best practices and standards
Always provide working, well-documented code.""",
)
financial_agent = Agent(
agent_name="Financial-Agent",
agent_description="Expert in financial analysis, market research, and investment insights",
model_name="anthropic/claude-sonnet-4-5",
max_loops=1,
top_p=None,
dynamic_temperature_enabled=True,
system_prompt="""You are a financial specialist. Your role is to:
1. Analyze financial data and markets
2. Provide investment insights
3. Assess risk and opportunities
4. Create financial reports
5. Explain complex financial concepts
Always provide accurate, well-reasoned financial analysis.""",
)
# Basic usage - individual agent addition
deployer = AOP("MyAgentServer", verbose=True, port=5932)
agents = [
research_agent,
analysis_agent,
writing_agent,
code_agent,
financial_agent,
]
deployer.add_agents_batch(agents)
deployer.run()
```
## Key Components
### 1. Agent Creation
Each agent is created with:
- **agent_name**: Unique identifier for the agent
- **agent_description**: Brief description of the agent's capabilities
- **model_name**: The language model to use
- **system_prompt**: Detailed instructions defining the agent's role and behavior
### 2. AOP Server Setup
- **Server Name**: "MyAgentServer" - identifies your server
- **Port**: 5932 - the port where the server will run
- **Verbose**: True - enables detailed logging
### 3. Agent Registration
- **add_agents_batch()**: Registers multiple agents at once
- Agents become available for discovery and remote calls
## Usage
1. **Start the Server**: Run the script to start the AOP server
2. **Agent Discovery**: Other agents or clients can discover available agents
3. **Remote Calls**: Agents can be called remotely by their names
## Server Features
- **Agent Discovery**: Automatically registers agents for network discovery
- **Remote Execution**: Agents can be called from other network nodes
- **Load Balancing**: Distributes requests across available agents
- **Health Monitoring**: Tracks agent status and availability
## Configuration Options
- **Port**: Change the port number as needed
- **Verbose**: Set to False for reduced logging
- **Server Name**: Use a descriptive name for your server
## Next Steps
- See [AOP Cluster Example](aop_cluster_example.md) for multi-server setups
- Check [AOP Reference](../structs/aop.md) for advanced configuration options
- Explore agent communication patterns in the examples directory

@ -19,7 +19,7 @@ market_research_agent = Agent(
- Industry report generation
- Market opportunity identification
- Risk assessment and mitigation strategies""",
model_name="gpt-4o",
model_name="gpt-4.1",
)
financial_analyst_agent = Agent(
@ -32,7 +32,7 @@ financial_analyst_agent = Agent(
- Financial modeling and forecasting
- Risk assessment and portfolio analysis
- ESG (Environmental, Social, Governance) analysis""",
model_name="gpt-4o",
model_name="gpt-4.1",
)
# Initialize the hierarchical swarm
@ -67,7 +67,7 @@ frontend_developer_agent = Agent(
- State management (Redux, Zustand, Context API)
- Web performance optimization
- Accessibility (WCAG) and SEO best practices""",
model_name="gpt-4o",
model_name="gpt-4.1",
)
backend_developer_agent = Agent(
@ -80,7 +80,7 @@ backend_developer_agent = Agent(
- API design and REST/GraphQL implementation
- Authentication and authorization systems
- Microservices architecture and containerization""",
model_name="gpt-4o",
model_name="gpt-4.1",
)
# Initialize the development swarm
@ -108,13 +108,13 @@ from swarms.structs.hiearchical_swarm import HierarchicalSwarm
market_agent = Agent(
agent_name="Market-Analyst",
agent_description="Expert in market analysis and trends",
model_name="gpt-4o",
model_name="gpt-4.1",
)
technical_agent = Agent(
agent_name="Technical-Analyst",
agent_description="Specialist in technical analysis and patterns",
model_name="gpt-4o",
model_name="gpt-4.1",
)
# Initialize the swarm
@ -142,13 +142,13 @@ from swarms.structs.hiearchical_swarm import HierarchicalSwarm
market_agent = Agent(
agent_name="Market-Analyst",
agent_description="Expert in market analysis and trends",
model_name="gpt-4o",
model_name="gpt-4.1",
)
technical_agent = Agent(
agent_name="Technical-Analyst",
agent_description="Specialist in technical analysis and patterns",
model_name="gpt-4o",
model_name="gpt-4.1",
)
# Initialize the swarm
@ -183,21 +183,21 @@ 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",
model_name="gpt-4.1",
)
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",
model_name="gpt-4.1",
)
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",
model_name="gpt-4.1",
)
# Initialize the research swarm

@ -39,7 +39,7 @@ legal_expert = Agent(
3. Ensuring regulatory compliance
4. Providing legal recommendations
5. Drafting and reviewing legal documents""",
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
)
@ -51,7 +51,7 @@ financial_expert = Agent(
3. Assessing financial risks
4. Providing financial projections
5. Recommending financial strategies""",
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
)
@ -63,7 +63,7 @@ business_expert = Agent(
3. Assessing competitive advantages
4. Providing strategic recommendations
5. Planning business development""",
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
)
@ -76,7 +76,7 @@ aggregator = Agent(
3. Prioritizing recommendations
4. Providing coherent final decisions
5. Ensuring comprehensive coverage of all aspects""",
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
)
```
@ -184,7 +184,7 @@ market_analyst = Agent(
3. Customer segments
4. Market trends
5. Entry barriers""",
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
)
@ -196,7 +196,7 @@ financial_analyst = Agent(
3. Cash flow analysis
4. Investment requirements
5. ROI projections""",
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
)
@ -208,7 +208,7 @@ risk_analyst = Agent(
3. Financial risks
4. Regulatory risks
5. Strategic risks""",
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
)
@ -221,7 +221,7 @@ aggregator = Agent(
3. Evaluating trade-offs
4. Making recommendations
5. Providing action plans""",
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
)

@ -127,7 +127,7 @@ research_agent = Agent(
# Creative agent using GPT-4o for content generation
creative_agent = Agent(
agent_name="Creative-Agent",
model_name="gpt-4o",
model_name="gpt-4.1",
system_prompt="You are a creative content expert."
)
@ -149,7 +149,7 @@ from swarms import Agent, ModelRouter
model_router = ModelRouter(
models={
"analysis": "claude-3-sonnet-20240229",
"creative": "gpt-4o",
"creative": "gpt-4.1",
"fast": "gpt-4o-mini",
"local": "ollama/llama2"
}

@ -100,7 +100,7 @@ agent = Agent(
agent_description="Expert cryptocurrency financial analyst and market researcher",
system_prompt=CRYPTO_ANALYST_SYSTEM_PROMPT,
max_loops="auto",
model_name="gpt-4o",
model_name="gpt-4.1",
dynamic_temperature_enabled=True,
user_name="crypto_analyst",
output_type="str",

@ -35,21 +35,21 @@ from swarms.structs.swarm_router import SwarmRouter, SwarmType
data_extractor_agent = Agent(
agent_name="Data-Extractor",
system_prompt="You are a data extraction specialist...",
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
)
summarizer_agent = Agent(
agent_name="Document-Summarizer",
system_prompt="You are a document summarization expert...",
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
)
financial_analyst_agent = Agent(
agent_name="Financial-Analyst",
system_prompt="You are a financial analysis specialist...",
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
)
```
@ -193,21 +193,21 @@ from swarms.structs.swarm_router import SwarmRouter, SwarmType
research_agent = Agent(
agent_name="ResearchAgent",
system_prompt="You are a research specialist...",
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1
)
analysis_agent = Agent(
agent_name="AnalysisAgent",
system_prompt="You are an analysis expert...",
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1
)
summary_agent = Agent(
agent_name="SummaryAgent",
system_prompt="You are a summarization specialist...",
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1
)

@ -36,7 +36,7 @@ class BrowserAgent:
async def browser_agent_test(self, task: str):
agent = Agent(
task=task,
llm=ChatOpenAI(model="gpt-4o"),
llm=ChatOpenAI(model="gpt-4.1"),
)
result = await agent.run()
return result

@ -20,7 +20,7 @@ agent = Agent(
agent_description="Personal finance advisor agent",
system_prompt=FINANCIAL_AGENT_SYS_PROMPT,
max_loops=1,
model_name="gpt-4o",
model_name="gpt-4.1",
dynamic_temperature_enabled=True,
user_name="swarms_corp",
return_step_meta=False,

@ -25,7 +25,7 @@ agent = Agent(
agent_description="Personal finance advisor agent",
system_prompt=FINANCIAL_AGENT_SYS_PROMPT,
max_loops=1,
model_name="gpt-4o",
model_name="gpt-4.1",
dynamic_temperature_enabled=True,
user_name="swarms_corp",
retry_attempts=3,

@ -42,7 +42,7 @@ agent = Agent(
agent_description="Personal finance advisor agent",
system_prompt=FINANCIAL_AGENT_SYS_PROMPT,
max_loops=1,
model_name="gpt-4o",
model_name="gpt-4.1",
tools=[yahoo_finance_api],
)

@ -1043,7 +1043,7 @@ A Pydantic model representing a delta update for messages in chat applications.
A Pydantic model representing a request for chat completion.
**Attributes**:
- `model` (`str`): The model to use for completing the chat (default is "gpt-4o").
- `model` (`str`): The model to use for completing the chat (default is "gpt-4.1").
- `messages` (`List[ChatMessageInput]`): A list of input messages for the chat.

@ -179,13 +179,13 @@ board_members = [
research_agent = Agent(
agent_name="Research-Specialist",
agent_description="Expert in market research and analysis",
model_name="gpt-4o",
model_name="gpt-4.1",
)
financial_agent = Agent(
agent_name="Financial-Analyst",
agent_description="Specialist in financial analysis and valuation",
model_name="gpt-4o",
model_name="gpt-4.1",
)
# Initialize the Board of Directors swarm
@ -215,7 +215,7 @@ print(result)
market_research_agent = Agent(
agent_name="Market-Research-Specialist",
agent_description="Expert in market research, competitive analysis, and industry trends",
model_name="gpt-4o",
model_name="gpt-4.1",
system_prompt="""You are a Market Research Specialist. Your responsibilities include:
1. Conducting comprehensive market research and analysis
2. Identifying market trends, opportunities, and risks
@ -229,7 +229,7 @@ You should be thorough, analytical, and objective in your research."""
financial_analyst_agent = Agent(
agent_name="Financial-Analyst",
agent_description="Specialist in financial analysis, valuation, and investment assessment",
model_name="gpt-4o",
model_name="gpt-4.1",
system_prompt="""You are a Financial Analyst. Your responsibilities include:
1. Conducting financial analysis and valuation
2. Assessing investment opportunities and risks
@ -243,7 +243,7 @@ You should be financially astute, analytical, and focused on value creation."""
technical_assessor_agent = Agent(
agent_name="Technical-Assessor",
agent_description="Expert in technical feasibility and implementation assessment",
model_name="gpt-4o",
model_name="gpt-4.1",
system_prompt="""You are a Technical Assessor. Your responsibilities include:
1. Evaluating technical feasibility and requirements
2. Assessing implementation challenges and risks
@ -327,7 +327,7 @@ print(json.dumps(result, indent=2))
tech_strategy_agent = Agent(
agent_name="Tech-Strategy-Specialist",
agent_description="Expert in technology strategy and digital transformation",
model_name="gpt-4o",
model_name="gpt-4.1",
system_prompt="""You are a Technology Strategy Specialist. Your responsibilities include:
1. Developing technology roadmaps and strategies
2. Assessing digital transformation opportunities
@ -341,7 +341,7 @@ You should be strategic, forward-thinking, and technology-savvy."""
implementation_planner_agent = Agent(
agent_name="Implementation-Planner",
agent_description="Expert in implementation planning and project management",
model_name="gpt-4o",
model_name="gpt-4.1",
system_prompt="""You are an Implementation Planner. Your responsibilities include:
1. Creating detailed implementation plans
2. Assessing resource requirements and timelines
@ -391,7 +391,7 @@ print(json.dumps(result, indent=2))
crisis_coordinator_agent = Agent(
agent_name="Crisis-Coordinator",
agent_description="Expert in crisis management and emergency response",
model_name="gpt-4o",
model_name="gpt-4.1",
system_prompt="""You are a Crisis Coordinator. Your responsibilities include:
1. Coordinating crisis response efforts
2. Assessing crisis severity and impact
@ -405,7 +405,7 @@ You should be calm, decisive, and action-oriented."""
communications_specialist_agent = Agent(
agent_name="Communications-Specialist",
agent_description="Expert in crisis communications and stakeholder management",
model_name="gpt-4o",
model_name="gpt-4.1",
system_prompt="""You are a Communications Specialist. Your responsibilities include:
1. Developing crisis communication strategies
2. Managing stakeholder communications

@ -894,7 +894,7 @@ agent = Agent(
output_type="json",
# LLM Configuration
model_name="gpt-4o",
model_name="gpt-4.1",
temperature=0.3,
max_tokens=8000,
top_p=0.95,

@ -0,0 +1,817 @@
# AOP (Agent Orchestration Protocol)
The Agent Orchestration Protocol (AOP) is a powerful framework for deploying multiple Swarms agents as tools in an MCP (Model Context Protocol) server. This enables you to create a distributed system where agents can be accessed as individual tools, making them available for use by other systems, applications, or clients.
AOP provides two main classes:
- **AOP**: Deploy agents as tools in a single MCP server
- **AOPCluster**: Connect to and manage multiple MCP servers
## Core Classes
### AgentToolConfig
Configuration dataclass for converting an agent to an MCP tool.
| Attribute | Type | Default | Description |
|-----------|------|---------|-------------|
| `tool_name` | `str` | Required | The name of the tool in the MCP server |
| `tool_description` | `str` | Required | Description of what the tool does |
| `input_schema` | `Dict[str, Any]` | Required | JSON schema for the tool's input parameters |
| `output_schema` | `Dict[str, Any]` | Required | JSON schema for the tool's output |
| `timeout` | `int` | `30` | Maximum time to wait for agent execution (seconds) |
| `max_retries` | `int` | `3` | Number of retries if agent execution fails |
| `verbose` | `bool` | `False` | Enable verbose logging for this tool |
| `traceback_enabled` | `bool` | `True` | Enable traceback logging for errors |
### AOP Class
Main class for deploying agents as tools in an MCP server.
#### Constructor Parameters
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `server_name` | `str` | `"AOP Cluster"` | Name for the MCP server |
| `description` | `str` | `"A cluster that enables you to deploy multiple agents as tools in an MCP server."` | Server description |
| `agents` | `any` | `None` | Optional list of agents to add initially |
| `port` | `int` | `8000` | Port for the MCP server |
| `transport` | `str` | `"streamable-http"` | Transport type for the MCP server |
| `verbose` | `bool` | `False` | Enable verbose logging |
| `traceback_enabled` | `bool` | `True` | Enable traceback logging for errors |
| `host` | `str` | `"localhost"` | Host to bind the server to |
| `log_level` | `str` | `"INFO"` | Logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL) |
| `*args` | `Any` | - | Additional positional arguments passed to FastMCP |
| `**kwargs` | `Any` | - | Additional keyword arguments passed to FastMCP |
#### Methods
##### add_agent()
Add an agent to the MCP server as a tool.
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `agent` | `AgentType` | Required | The swarms Agent instance to deploy |
| `tool_name` | `str` | `None` | Name for the tool (defaults to agent.agent_name) |
| `tool_description` | `str` | `None` | Description of the tool (defaults to agent.agent_description) |
| `input_schema` | `Dict[str, Any]` | `None` | JSON schema for input parameters |
| `output_schema` | `Dict[str, Any]` | `None` | JSON schema for output |
| `timeout` | `int` | `30` | Maximum execution time in seconds |
| `max_retries` | `int` | `3` | Number of retries on failure |
| `verbose` | `bool` | `None` | Enable verbose logging for this tool |
| `traceback_enabled` | `bool` | `None` | Enable traceback logging for this tool |
**Returns:** `str` - The tool name that was registered
##### add_agents_batch()
Add multiple agents to the MCP server as tools in batch.
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `agents` | `List[Agent]` | Required | List of swarms Agent instances |
| `tool_names` | `List[str]` | `None` | Optional list of tool names |
| `tool_descriptions` | `List[str]` | `None` | Optional list of tool descriptions |
| `input_schemas` | `List[Dict[str, Any]]` | `None` | Optional list of input schemas |
| `output_schemas` | `List[Dict[str, Any]]` | `None` | Optional list of output schemas |
| `timeouts` | `List[int]` | `None` | Optional list of timeout values |
| `max_retries_list` | `List[int]` | `None` | Optional list of max retry values |
| `verbose_list` | `List[bool]` | `None` | Optional list of verbose settings |
| `traceback_enabled_list` | `List[bool]` | `None` | Optional list of traceback settings |
**Returns:** `List[str]` - List of tool names that were registered
##### remove_agent()
Remove an agent from the MCP server.
| Parameter | Type | Description |
|-----------|------|-------------|
| `tool_name` | `str` | Name of the tool to remove |
**Returns:** `bool` - True if agent was removed, False if not found
##### list_agents()
Get a list of all registered agent tool names.
**Returns:** `List[str]` - List of tool names
##### get_agent_info()
Get information about a specific agent tool.
| Parameter | Type | Description |
|-----------|------|-------------|
| `tool_name` | `str` | Name of the tool |
**Returns:** `Dict[str, Any]` - Agent information, or None if not found
##### start_server()
Start the MCP server.
##### run()
Run the MCP server (alias for start_server).
##### get_server_info()
Get information about the MCP server and registered tools.
**Returns:** `Dict[str, Any]` - Server information
##### _register_tool()
Register a single agent as an MCP tool (internal method).
| Parameter | Type | Description |
|-----------|------|-------------|
| `tool_name` | `str` | Name of the tool to register |
| `agent` | `AgentType` | The agent instance to register |
##### _execute_agent_with_timeout()
Execute an agent with a timeout and all run method parameters (internal method).
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `agent` | `AgentType` | Required | The agent to execute |
| `task` | `str` | Required | The task to execute |
| `timeout` | `int` | Required | Maximum execution time in seconds |
| `img` | `str` | `None` | Optional image to be processed by the agent |
| `imgs` | `List[str]` | `None` | Optional list of images to be processed by the agent |
| `correct_answer` | `str` | `None` | Optional correct answer for validation or comparison |
**Returns:** `str` - The agent's response
**Raises:** `TimeoutError` if execution exceeds timeout, `Exception` if agent execution fails
##### _get_agent_discovery_info()
Get discovery information for a specific agent (internal method).
| Parameter | Type | Description |
|-----------|------|-------------|
| `tool_name` | `str` | Name of the agent tool |
**Returns:** `Optional[Dict[str, Any]]` - Agent discovery information, or None if not found
## Discovery Tools
AOP automatically registers several discovery tools that allow agents to learn about each other and enable dynamic agent discovery within the cluster.
### discover_agents
Discover information about agents in the cluster including their name, description, system prompt (truncated to 200 chars), and tags.
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `agent_name` | `str` | `None` | Optional specific agent name to get info for. If None, returns info for all agents. |
**Returns:** `Dict[str, Any]` - Agent information for discovery
**Response Format:**
```json
{
"success": true,
"agents": [
{
"tool_name": "agent_name",
"agent_name": "Agent Name",
"description": "Agent description",
"short_system_prompt": "Truncated system prompt...",
"tags": ["tag1", "tag2"],
"capabilities": ["capability1", "capability2"],
"role": "worker",
"model_name": "model_name",
"max_loops": 1,
"temperature": 0.5,
"max_tokens": 4096
}
]
}
```
### get_agent_details
Get detailed information about a single agent by name including configuration, capabilities, and metadata.
| Parameter | Type | Description |
|-----------|------|-------------|
| `agent_name` | `str` | Name of the agent to get information for. |
**Returns:** `Dict[str, Any]` - Detailed agent information
**Response Format:**
```json
{
"success": true,
"agent_info": {
"tool_name": "agent_name",
"agent_name": "Agent Name",
"agent_description": "Agent description",
"model_name": "model_name",
"max_loops": 1,
"tool_description": "Tool description",
"timeout": 30,
"max_retries": 3,
"verbose": false,
"traceback_enabled": true
},
"discovery_info": {
"tool_name": "agent_name",
"agent_name": "Agent Name",
"description": "Agent description",
"short_system_prompt": "Truncated system prompt...",
"tags": ["tag1", "tag2"],
"capabilities": ["capability1", "capability2"],
"role": "worker",
"model_name": "model_name",
"max_loops": 1,
"temperature": 0.5,
"max_tokens": 4096
}
}
```
### get_agents_info
Get detailed information about multiple agents by providing a list of agent names.
| Parameter | Type | Description |
|-----------|------|-------------|
| `agent_names` | `List[str]` | List of agent names to get information for. |
**Returns:** `Dict[str, Any]` - Detailed information for all requested agents
**Response Format:**
```json
{
"success": true,
"agents_info": [
{
"agent_name": "agent_name",
"agent_info": { /* detailed agent info */ },
"discovery_info": { /* discovery info */ }
}
],
"not_found": ["missing_agent"],
"total_found": 1,
"total_requested": 2
}
```
### list_agents
Get a simple list of all available agent names in the cluster.
**Returns:** `Dict[str, Any]` - List of agent names
**Response Format:**
```json
{
"success": true,
"agent_names": ["agent1", "agent2", "agent3"],
"total_count": 3
}
```
### search_agents
Search for agents by name, description, tags, or capabilities using keyword matching.
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `query` | `str` | Required | Search query string |
| `search_fields` | `List[str]` | `["name", "description", "tags", "capabilities"]` | Optional list of fields to search in. If None, searches all fields. |
**Returns:** `Dict[str, Any]` - Matching agents
**Response Format:**
```json
{
"success": true,
"matching_agents": [
{
"tool_name": "agent_name",
"agent_name": "Agent Name",
"description": "Agent description",
"short_system_prompt": "Truncated system prompt...",
"tags": ["tag1", "tag2"],
"capabilities": ["capability1", "capability2"],
"role": "worker",
"model_name": "model_name",
"max_loops": 1,
"temperature": 0.5,
"max_tokens": 4096
}
],
"total_matches": 1,
"query": "search_term",
"search_fields": ["name", "description", "tags", "capabilities"]
}
```
### AOPCluster Class
Class for connecting to and managing multiple MCP servers.
#### AOPCluster Constructor Parameters
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `urls` | `List[str]` | Required | List of MCP server URLs to connect to |
| `transport` | `str` | `"streamable-http"` | Transport type for connections |
#### AOPCluster Methods
##### get_tools()
Get tools from all connected MCP servers.
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `output_type` | `Literal["json", "dict", "str"]` | `"dict"` | Format of the output |
**Returns:** `List[Dict[str, Any]]` - List of available tools
##### find_tool_by_server_name()
Find a tool by its server name (function name).
| Parameter | Type | Description |
|-----------|------|-------------|
| `server_name` | `str` | The name of the tool/function to find |
**Returns:** `Dict[str, Any]` - Tool information, or None if not found
## Tool Parameters
All agent tools accept the following parameters:
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `task` | `str` | Yes | The main task or prompt to execute |
| `img` | `str` | No | Single image to be processed by the agent |
| `imgs` | `List[str]` | No | Multiple images to be processed by the agent |
| `correct_answer` | `str` | No | Correct answer for validation or comparison |
## Output Format
All agent tools return a standardized response format:
```json
{
"result": "string", // The agent's response to the task
"success": "boolean", // Whether the task was executed successfully
"error": "string" // Error message if execution failed (null if successful)
}
```
## Complete Examples
### Basic Server Setup
```python
from swarms import Agent
from swarms.structs.aop import AOP
# Create specialized agents
research_agent = Agent(
agent_name="Research-Agent",
agent_description="Expert in research, data collection, and information gathering",
model_name="anthropic/claude-sonnet-4-5",
max_loops=1,
top_p=None,
dynamic_temperature_enabled=True,
system_prompt="""You are a research specialist. Your role is to:
1. Gather comprehensive information on any given topic
2. Analyze data from multiple sources
3. Provide well-structured research findings
4. Cite sources and maintain accuracy
5. Present findings in a clear, organized manner
Always provide detailed, factual information with proper context.""",
)
analysis_agent = Agent(
agent_name="Analysis-Agent",
agent_description="Expert in data analysis, pattern recognition, and generating insights",
model_name="anthropic/claude-sonnet-4-5",
max_loops=1,
top_p=None,
dynamic_temperature_enabled=True,
system_prompt="""You are an analysis specialist. Your role is to:
1. Analyze data and identify patterns
2. Generate actionable insights
3. Create visualizations and summaries
4. Provide statistical analysis
5. Make data-driven recommendations
Focus on extracting meaningful insights from information.""",
)
# Create AOP instance
deployer = AOP(
server_name="MyAgentServer",
port=8000,
verbose=True,
log_level="INFO"
)
# Add agents individually
deployer.add_agent(research_agent)
deployer.add_agent(analysis_agent)
# Start the server
deployer.run()
```
### Batch Agent Addition
```python
from swarms import Agent
from swarms.structs.aop import AOP
# Create multiple agents
agents = [
Agent(
agent_name="Research-Agent",
agent_description="Expert in research and data collection",
model_name="anthropic/claude-sonnet-4-5",
max_loops=1,
),
Agent(
agent_name="Writing-Agent",
agent_description="Expert in content creation and editing",
model_name="anthropic/claude-sonnet-4-5",
max_loops=1,
),
Agent(
agent_name="Code-Agent",
agent_description="Expert in programming and code review",
model_name="anthropic/claude-sonnet-4-5",
max_loops=1,
),
]
# Create AOP instance
deployer = AOP("MyAgentServer", verbose=True)
# Add all agents at once
tool_names = deployer.add_agents_batch(agents)
print(f"Added {len(tool_names)} agents: {tool_names}")
# Start the server
deployer.run()
```
### Advanced Configuration with Tags and Capabilities
```python
from swarms import Agent
from swarms.structs.aop import AOP
# Create agent with custom configuration, tags, and capabilities
research_agent = Agent(
agent_name="Research-Agent",
agent_description="Expert in research and data collection",
model_name="anthropic/claude-sonnet-4-5",
max_loops=1,
# Add tags and capabilities for better discovery
tags=["research", "data-collection", "analysis"],
capabilities=["web-search", "data-gathering", "report-generation"],
role="researcher"
)
# Create AOP with custom settings
deployer = AOP(
server_name="AdvancedAgentServer",
port=8001,
host="0.0.0.0", # Allow external connections
verbose=True,
traceback_enabled=True,
log_level="DEBUG"
)
# Add agent with custom tool configuration
deployer.add_agent(
agent=research_agent,
tool_name="custom_research_tool",
tool_description="Custom research tool with extended capabilities",
timeout=60, # 60 second timeout
max_retries=5, # 5 retries
verbose=True,
traceback_enabled=True
)
# Add custom input/output schemas
custom_input_schema = {
"type": "object",
"properties": {
"task": {
"type": "string",
"description": "The research task to execute"
},
"sources": {
"type": "array",
"items": {"type": "string"},
"description": "Specific sources to research"
},
"depth": {
"type": "string",
"enum": ["shallow", "medium", "deep"],
"description": "Research depth level"
}
},
"required": ["task"]
}
custom_output_schema = {
"type": "object",
"properties": {
"result": {"type": "string"},
"sources": {"type": "array", "items": {"type": "string"}},
"confidence": {"type": "number", "minimum": 0, "maximum": 1},
"success": {"type": "boolean"},
"error": {"type": "string"}
},
"required": ["result", "success"]
}
# Add another agent with custom schemas
analysis_agent = Agent(
agent_name="Analysis-Agent",
agent_description="Expert in data analysis",
model_name="anthropic/claude-sonnet-4-5",
max_loops=1,
)
deployer.add_agent(
agent=analysis_agent,
tool_name="custom_analysis_tool",
tool_description="Custom analysis tool",
input_schema=custom_input_schema,
output_schema=custom_output_schema,
timeout=45,
max_retries=3
)
# List all registered agents
print("Registered agents:", deployer.list_agents())
# Get server information
server_info = deployer.get_server_info()
print("Server info:", server_info)
# Start the server
deployer.run()
```
### AOPCluster Usage
```python
import json
from swarms.structs.aop import AOPCluster
# Connect to multiple MCP servers
cluster = AOPCluster(
urls=[
"http://localhost:8000/mcp",
"http://localhost:8001/mcp",
"http://localhost:8002/mcp"
],
transport="streamable-http"
)
# Get all available tools from all servers
all_tools = cluster.get_tools(output_type="dict")
print(f"Found {len(all_tools)} tools across all servers")
# Pretty print all tools
print(json.dumps(all_tools, indent=2))
# Find a specific tool by name
research_tool = cluster.find_tool_by_server_name("Research-Agent")
if research_tool:
print("Found Research-Agent tool:")
print(json.dumps(research_tool, indent=2))
else:
print("Research-Agent tool not found")
```
### Discovery Tools Examples
The AOP server automatically provides discovery tools that allow agents to learn about each other. Here are examples of how to use these tools:
```python
# Example discovery tool calls (these would be made by MCP clients)
# Discover all agents in the cluster
all_agents = discover_agents()
print(f"Found {len(all_agents['agents'])} agents in the cluster")
# Discover a specific agent
research_agent_info = discover_agents(agent_name="Research-Agent")
if research_agent_info['success']:
agent = research_agent_info['agents'][0]
print(f"Agent: {agent['agent_name']}")
print(f"Description: {agent['description']}")
print(f"Tags: {agent['tags']}")
print(f"Capabilities: {agent['capabilities']}")
# Get detailed information about a specific agent
agent_details = get_agent_details(agent_name="Research-Agent")
if agent_details['success']:
print("Agent Info:", agent_details['agent_info'])
print("Discovery Info:", agent_details['discovery_info'])
# Get information about multiple agents
multiple_agents = get_agents_info(agent_names=["Research-Agent", "Analysis-Agent"])
print(f"Found {multiple_agents['total_found']} out of {multiple_agents['total_requested']} agents")
print("Not found:", multiple_agents['not_found'])
# List all available agents
agent_list = list_agents()
print(f"Available agents: {agent_list['agent_names']}")
# Search for agents by keyword
search_results = search_agents(query="research")
print(f"Found {search_results['total_matches']} agents matching 'research'")
# Search in specific fields only
tag_search = search_agents(
query="data",
search_fields=["tags", "capabilities"]
)
print(f"Found {tag_search['total_matches']} agents with 'data' in tags or capabilities")
```
### Dynamic Agent Discovery Example
Here's a practical example of how agents can use discovery tools to find and collaborate with other agents:
```python
from swarms import Agent
from swarms.structs.aop import AOP
# Create a coordinator agent that can discover and use other agents
coordinator = Agent(
agent_name="Coordinator-Agent",
agent_description="Coordinates tasks between different specialized agents",
model_name="anthropic/claude-sonnet-4-5",
max_loops=1,
tags=["coordination", "orchestration", "management"],
capabilities=["agent-discovery", "task-distribution", "workflow-management"],
role="coordinator"
)
# Create specialized agents
research_agent = Agent(
agent_name="Research-Agent",
agent_description="Expert in research and data collection",
model_name="anthropic/claude-sonnet-4-5",
max_loops=1,
tags=["research", "data-collection", "analysis"],
capabilities=["web-search", "data-gathering", "report-generation"],
role="researcher"
)
analysis_agent = Agent(
agent_name="Analysis-Agent",
agent_description="Expert in data analysis and insights",
model_name="anthropic/claude-sonnet-4-5",
max_loops=1,
tags=["analysis", "data-processing", "insights"],
capabilities=["statistical-analysis", "pattern-recognition", "visualization"],
role="analyst"
)
# Create AOP server
deployer = AOP(
server_name="DynamicAgentCluster",
port=8000,
verbose=True
)
# Add all agents
deployer.add_agent(coordinator)
deployer.add_agent(research_agent)
deployer.add_agent(analysis_agent)
# The coordinator can now discover other agents and use them
# This would be done through MCP tool calls in practice
def coordinate_research_task(task_description):
"""
Example of how the coordinator might use discovery tools
"""
# 1. Discover available research agents
research_agents = discover_agents()
research_agents = [a for a in research_agents['agents'] if 'research' in a['tags']]
# 2. Get detailed info about the best research agent
if research_agents:
best_agent = research_agents[0]
agent_details = get_agent_details(agent_name=best_agent['agent_name'])
# 3. Use the research agent for the task
research_result = research_agent.run(task=task_description)
# 4. Find analysis agents for processing the research
analysis_agents = search_agents(query="analysis", search_fields=["tags"])
if analysis_agents['matching_agents']:
analysis_agent_name = analysis_agents['matching_agents'][0]['agent_name']
analysis_result = analysis_agent.run(task=f"Analyze this research: {research_result}")
return {
"research_result": research_result,
"analysis_result": analysis_result,
"agents_used": [best_agent['agent_name'], analysis_agent_name]
}
return {"error": "No suitable agents found"}
# Start the server
deployer.run()
```
### Tool Execution Examples
Once your AOP server is running, you can call the tools using MCP clients. Here are examples of how the tools would be called:
```python
# Example tool calls (these would be made by MCP clients)
# Basic task execution
result = research_tool(task="Research the latest AI trends in 2024")
# Task with single image
result = analysis_tool(
task="Analyze this chart and provide insights",
img="path/to/chart.png"
)
# Task with multiple images
result = writing_tool(
task="Write a comprehensive report based on these images",
imgs=["image1.jpg", "image2.jpg", "image3.jpg"]
)
# Task with validation
result = code_tool(
task="Debug this Python function",
correct_answer="Expected output: Hello World"
)
# The response format for all calls:
# {
# "result": "The agent's response...",
# "success": true,
# "error": null
# }
```
## Error Handling
AOP provides comprehensive error handling:
- **Timeout Protection**: Each agent has configurable timeout limits
- **Retry Logic**: Automatic retries on failure with configurable retry counts
- **Detailed Logging**: Verbose logging with traceback information
- **Graceful Degradation**: Failed agents don't crash the entire server
## Best Practices
| Best Practice | Description |
|------------------------------|--------------------------------------------------------------------|
| **Use Descriptive Names** | Choose clear, descriptive tool names |
| **Set Appropriate Timeouts** | Configure timeouts based on expected task complexity |
| **Enable Logging** | Use verbose logging for debugging and monitoring |
| **Handle Errors** | Always check the `success` field in tool responses |
| **Resource Management** | Monitor server resources when running multiple agents |
| **Security** | Use appropriate host/port settings for your deployment environment |
| **Use Tags and Capabilities** | Add meaningful tags and capabilities to agents for better discovery |
| **Define Agent Roles** | Use the `role` attribute to categorize agents (coordinator, worker, etc.) |
| **Leverage Discovery Tools** | Use built-in discovery tools for dynamic agent collaboration |
| **Design for Scalability** | Plan for adding/removing agents dynamically using discovery tools |
## Integration with Other Systems
AOP servers can be integrated with:
| Integration Target | Description |
|------------------------|--------------------------------------------------|
| **MCP Clients** | Any MCP-compatible client |
| **Web Applications** | Via HTTP transport |
| **Other Swarms** | As part of larger multi-agent systems |
| **External APIs** | Through MCP protocol |
This makes AOP a powerful tool for creating distributed, scalable agent systems that can be easily integrated into existing workflows and applications.

@ -1,200 +0,0 @@
# Agent Builder
The Agent Builder is a powerful class that automatically builds and manages swarms of AI agents. It provides a flexible and extensible framework for creating, coordinating, and executing multiple AI agents working together to accomplish complex tasks.
## Overview
The Agent Builder uses a boss agent to delegate work and create new specialized agents as needed. It's designed to be production-ready with robust error handling, logging, and configuration options.
## Architecture
```mermaid
graph TD
A[Agent Builder] --> B[Configuration]
A --> C[Agent Creation]
A --> D[Task Execution]
B --> B1[Name]
B --> B2[Description]
B --> B3[Model Settings]
C --> C1[Agent Pool]
C --> C2[Agent Registry]
C --> C3[Agent Configuration]
D --> D1[Task Distribution]
D --> D2[Result Collection]
D --> D3[Error Handling]
C1 --> E[Specialized Agents]
C2 --> E
C3 --> E
E --> F[Task Execution]
F --> G[Results]
```
## Class Structure
### AgentsBuilder Class
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| name | str | "swarm-creator-01" | The name of the swarm |
| description | str | "This is a swarm that creates swarms" | A description of the swarm's purpose |
| verbose | bool | True | Whether to output detailed logs |
| max_loops | int | 1 | Maximum number of execution loops |
| model_name | str | "gpt-4o" | The model to use for agent creation |
| return_dictionary | bool | True | Whether to return results as a dictionary |
| system_prompt | str | BOSS_SYSTEM_PROMPT | The system prompt for the boss agent |
### Methods
| Method | Description | Parameters | Returns |
|--------|-------------|------------|---------|
| run | Run the swarm on a given task | task: str, image_url: str = None, *args, **kwargs | Tuple[List[Agent], int] |
| _create_agents | Create necessary agents for a task | task: str, *args, **kwargs | List[Agent] |
| build_agent | Build a single agent with specifications | agent_name: str, agent_description: str, agent_system_prompt: str, max_loops: int = 1, model_name: str = "gpt-4o", dynamic_temperature_enabled: bool = True, auto_generate_prompt: bool = False, role: str = "worker", max_tokens: int = 8192, temperature: float = 0.5 | Agent |
## Enterprise Use Cases
### 1. Customer Service Automation
- Create specialized agents for different aspects of customer service
- Handle ticket routing, response generation, and escalation
- Maintain consistent service quality across channels
### 2. Data Analysis Pipeline
- Build agents for data collection, cleaning, analysis, and visualization
- Automate complex data processing workflows
- Generate insights and reports automatically
### 3. Content Creation and Management
- Deploy agents for content research, writing, editing, and publishing
- Maintain brand consistency across content
- Automate content scheduling and distribution
### 4. Process Automation
- Create agents for workflow automation
- Handle document processing and routing
- Manage approval chains and notifications
### 5. Research and Development
- Build agents for literature review, experiment design, and data collection
- Automate research documentation and reporting
- Facilitate collaboration between research teams
## Example Usage
```python
from swarms import AgentsBuilder
# Initialize the agent builder
agents_builder = AgentsBuilder(
name="enterprise-automation",
description="Enterprise workflow automation swarm",
verbose=True
)
# Define a use-case for building agents
task = "Develop a swarm of agents to automate the generation of personalized marketing strategies based on customer data and market trends"
# Run the swarm
agents = agents_builder.run(task)
# Access results
print(agents)
```
## Best Practices
1. **Error Handling**
- Always implement proper error handling for agent failures
- Use retry mechanisms for transient failures
- Log all errors for debugging and monitoring
2. **Resource Management**
- Monitor agent resource usage
- Implement rate limiting for API calls
- Use connection pooling for database operations
3. **Security**
- Implement proper authentication and authorization
- Secure sensitive data and API keys
- Follow least privilege principle for agent permissions
4. **Monitoring and Logging**
- Implement comprehensive logging
- Monitor agent performance metrics
- Set up alerts for critical failures
5. **Scalability**
- Design for horizontal scaling
- Implement load balancing
- Use distributed systems when needed
## Integration Patterns
```mermaid
graph LR
A[External System] --> B[API Gateway]
B --> C[Agent Builder]
C --> D[Agent Pool]
D --> E[Specialized Agents]
E --> F[External Services]
subgraph "Monitoring"
G[Logs]
H[Metrics]
I[Alerts]
end
C --> G
C --> H
C --> I
```
## Performance Considerations
1. **Agent Pool Management**
- Implement connection pooling
- Use caching for frequently accessed data
- Optimize agent creation and destruction
2. **Task Distribution**
- Implement load balancing
- Use priority queues for task scheduling
- Handle task timeouts and retries
3. **Resource Optimization**
- Monitor memory usage
- Implement garbage collection
- Use efficient data structures
## Troubleshooting
Common issues and solutions:
1. **Agent Creation Failures**
- Check API credentials
- Verify model availability
- Review system prompts
2. **Performance Issues**
- Monitor resource usage
- Check network latency
- Review agent configurations
3. **Integration Problems**
- Verify API endpoints
- Check authentication
- Review data formats

@ -1,33 +1,37 @@
# AutoSwarmBuilder Documentation
The `AutoSwarmBuilder` is a powerful class that automatically builds and manages swarms of AI agents to accomplish complex tasks. It uses a sophisticated boss agent system to delegate work and create specialized agents as needed.
## Overview
The `AutoSwarmBuilder` is a powerful class that automatically builds and manages swarms of AI agents to accomplish complex tasks. It uses a sophisticated boss agent system with comprehensive design principles to delegate work and create specialized agents as needed.
The AutoSwarmBuilder is designed to:
| Feature | Description |
|---------|-------------|
| Automatic Agent Creation | Automatically create and coordinate multiple AI agents |
| Task Delegation | Delegate tasks to specialized agents based on task requirements |
| Agent Communication Management | Manage communication between agents through a swarm router |
| Complex Workflow Handling | Handle complex workflows with various execution types |
| Architecture Pattern Support | Support different multi-agent architecture patterns |
| Error Handling & Logging | Provide comprehensive error handling and logging |
| **Automatic Agent Creation** | Automatically create and coordinate multiple AI agents with distinct personalities and capabilities |
| **Intelligent Task Delegation** | Delegate tasks to specialized agents based on comprehensive task analysis and requirements |
| **Advanced Agent Communication** | Manage sophisticated communication protocols between agents through a swarm router |
| **Multiple Execution Types** | Support 6 different execution types for various use cases and workflows |
| **Comprehensive Architecture Support** | Support 13+ different multi-agent architecture patterns and coordination strategies |
| **Robust Error Handling** | Provide comprehensive error handling, logging, and recovery procedures |
| **Dynamic Agent Specification** | Create agents with detailed specifications including roles, personalities, and capabilities |
| **Flexible Configuration** | Support extensive configuration options for models, tokens, temperature, and behavior |
| **Batch Processing** | Handle multiple tasks efficiently with batch processing capabilities |
| **Interactive Mode** | Support real-time interactive collaboration and decision-making |
## Parameters
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| name | str | "auto-swarm-builder" | The name of the swarm |
| description | str | "Auto Swarm Builder" | A description of the swarm's purpose |
| verbose | bool | True | Whether to output detailed logs |
| max_loops | int | 1 | Maximum number of execution loops |
| model_name | str | "gpt-4.1" | The LLM model to use for the boss agent |
| generate_router_config | bool | False | Whether to generate router configuration |
| interactive | bool | False | Whether to enable interactive mode |
| max_tokens | int | 8000 | Maximum tokens for the LLM responses |
| execution_type | str | "return-agents" | Type of execution to perform |
| `name` | str | "auto-swarm-builder" | The name of the swarm |
| `description` | str | "Auto Swarm Builder" | A description of the swarm's purpose |
| `verbose` | bool | True | Whether to output detailed logs |
| `max_loops` | int | 1 | Maximum number of execution loops |
| `model_name` | str | "gpt-4.1" | The LLM model to use for the boss agent |
| `generate_router_config` | bool | False | Whether to generate router configuration |
| `interactive` | bool | False | Whether to enable interactive mode |
| `max_tokens` | int | 8000 | Maximum tokens for the LLM responses |
| `execution_type` | str | "return-agents" | Type of execution to perform (see Execution Types) |
| `system_prompt` | str | BOSS_SYSTEM_PROMPT | System prompt for the boss agent |
| `additional_llm_args` | dict | {} | Additional arguments to pass to the LLM |
## Execution Types
@ -35,10 +39,10 @@ The `execution_type` parameter controls how the AutoSwarmBuilder operates:
| Execution Type | Description |
|----------------------------------|-----------------------------------------------------------|
| **"return-agents"** | Creates and returns a list of Agent objects (default) |
| **"return-agents"** | Creates and returns agent specifications as a dictionary (default) |
| **"execute-swarm-router"** | Executes the swarm router with the created agents |
| **"return-swarm-router-config"** | Returns the swarm router configuration as a dictionary |
| **"return-agent-configurations"**| Returns agent configurations as a dictionary |
| **"return-agents-objects"** | Returns agent objects created from specifications |
## Core Methods
@ -78,26 +82,6 @@ Creates specialized agents for a given task using the boss agent system.
- `Exception`: If there's an error during agent creation
### build_agent(agent_name: str, agent_description: str, agent_system_prompt: str)
Builds a single agent with specified parameters and enhanced error handling.
**Parameters:**
| Parameter | Type | Description |
|-----------------------|-------|--------------------------------|
| `agent_name` | str | Name of the agent |
| `agent_description` | str | Description of the agent |
| `agent_system_prompt` | str | System prompt for the agent |
**Returns:**
- `Agent`: The constructed agent
**Raises:**
- `Exception`: If there's an error during agent construction
### create_router_config(task: str)
Creates a swarm router configuration for a given task.
@ -156,6 +140,18 @@ Returns the available execution types.
- `List[str]`: List of available execution types
### create_agents_from_specs(agents_dictionary: Any)
Create agents from agent specifications.
**Parameters:**
- `agents_dictionary`: Dictionary containing agent specifications
**Returns:**
- `List[Agent]`: List of created agents
### dict_to_agent(output: dict)
Converts a dictionary output to a list of Agent objects.
@ -168,6 +164,18 @@ Converts a dictionary output to a list of Agent objects.
- `List[Agent]`: List of constructed agents
### _execute_task(task: str)
Execute a task by creating agents and initializing the swarm router.
**Parameters:**
- `task` (str): The task to execute
**Returns:**
- `Any`: The result of the swarm router execution
### build_llm_agent(config: BaseModel)
Builds an LLM agent for configuration generation.
@ -190,6 +198,33 @@ Performs reliability checks on the AutoSwarmBuilder configuration.
## Configuration Classes
### AgentSpec
Configuration for an individual agent specification with comprehensive options.
**Fields:**
| Field | Type | Description |
|----------------------|---------|-----------------------------------------------------------------------------------------------|
| `agent_name` | str | Unique name assigned to the agent, identifying its role and functionality |
| `description` | str | Detailed explanation of the agent's purpose, capabilities, and specific tasks |
| `system_prompt` | str | Initial instruction or context provided to guide agent behavior and responses |
| `model_name` | str | AI model name for processing tasks (e.g., 'gpt-4o', 'gpt-4o-mini', 'openai/o3-mini') |
| `auto_generate_prompt`| bool | Flag indicating whether the agent should automatically create prompts |
| `max_tokens` | int | Maximum number of tokens allowed in agent responses |
| `temperature` | float | Parameter controlling randomness of agent output (lower = more deterministic) |
| `role` | str | Designated role within the swarm influencing behavior and interactions |
| `max_loops` | int | Maximum number of times the agent can repeat its task for iterative processing |
| `goal` | str | The primary objective or desired outcome the agent is tasked with achieving |
### Agents
Configuration for a collection of agents that work together as a swarm.
**Fields:**
- `agents` (List[AgentSpec]): List containing specifications of each agent participating in the swarm
### AgentConfig
Configuration model for individual agents in a swarm.
@ -198,7 +233,7 @@ Configuration model for individual agents in a swarm.
| Field | Type | Description |
|-----------------|---------|-----------------------------------------------------------------------------------------------|
| `name` | str | Unique identifier for the agent |
| `agent_name` | str | Unique identifier for the agent |
| `description` | str | Comprehensive description of the agent's purpose and capabilities |
| `system_prompt` | str | Detailed system prompt defining agent behavior |
| `goal` | str | Primary objective the agent is tasked with achieving |
@ -249,6 +284,67 @@ The AutoSwarmBuilder supports various multi-agent architecture patterns:
| **InteractiveGroupChat** | Dynamic group interactions |
| **HeavySwarm** | High-capacity processing with multiple agents |
## Boss System Prompt
The AutoSwarmBuilder uses a comprehensive `BOSS_SYSTEM_PROMPT` that embodies sophisticated multi-agent architecture design principles. This system prompt guides the boss agent in creating highly effective agent teams.
### Core Design Principles
The boss system prompt includes six fundamental design principles:
1. **Comprehensive Task Analysis**
- Thoroughly deconstruct tasks into fundamental components and sub-tasks
- Identify specific skills, knowledge domains, and personality traits required
- Analyze challenges, dependencies, and coordination requirements
- Map optimal workflows, information flow patterns, and decision-making hierarchies
2. **Agent Design Excellence**
- Create agents with crystal-clear, specific purposes and domain expertise
- Design distinct, complementary personalities that enhance team dynamics
- Ensure agents are self-aware of limitations and know when to seek assistance
- Create agents that effectively communicate progress, challenges, and insights
3. **Comprehensive Agent Framework**
- **Role & Purpose**: Precise description of responsibilities and authority
- **Personality Profile**: Distinct characteristics influencing thinking patterns
- **Expertise Matrix**: Specific knowledge domains, skill sets, and capabilities
- **Communication Protocol**: How agents present information and interact
- **Decision-Making Framework**: Systematic approach to problem-solving
- **Limitations & Boundaries**: Clear constraints and operational boundaries
- **Collaboration Strategy**: How agents work together and share knowledge
4. **Advanced System Prompt Engineering**
- Detailed role and purpose explanations with context and scope
- Rich personality descriptions with behavioral guidelines
- Comprehensive capabilities, tools, and resource specifications
- Detailed communication protocols and reporting requirements
- Systematic problem-solving approaches with decision-making frameworks
- Collaboration guidelines and conflict resolution procedures
- Quality standards, success criteria, and performance metrics
- Error handling, recovery procedures, and escalation protocols
5. **Multi-Agent Coordination Architecture**
- Design robust communication channels and protocols between agents
- Establish clear task handoff procedures and information sharing mechanisms
- Create feedback loops for continuous improvement and adaptation
- Implement comprehensive error handling and recovery procedures
- Define escalation paths for complex issues and decision-making hierarchies
6. **Quality Assurance & Governance**
- Set measurable success criteria for each agent and the overall system
- Implement verification steps, validation procedures, and quality checks
- Create mechanisms for self-assessment, peer review, and continuous improvement
- Establish protocols for handling edge cases and unexpected situations
- Design governance structures for oversight, accountability, and performance management
### Output Requirements
The boss system prompt ensures that when creating multi-agent systems, the following are provided:
1. **Agent Specifications**: Comprehensive role statements, personality profiles, capabilities, limitations, communication styles, and collaboration strategies
2. **System Prompts**: Complete, detailed prompts embodying each agent's identity and capabilities
3. **Architecture Design**: Team structure, communication flow patterns, task distribution strategies, quality control measures, and error handling procedures
## Examples
### Example 1: Basic Content Creation Swarm
@ -278,7 +374,7 @@ from swarms.structs.auto_swarm_builder import AutoSwarmBuilder
swarm = AutoSwarmBuilder(
name="Data Analysis Swarm",
description="A swarm specialized in data analysis and visualization",
model_name="gpt-4o",
model_name="gpt-4.1",
max_tokens=12000,
verbose=True,
execution_type="return-agents"
@ -300,7 +396,7 @@ from swarms.structs.auto_swarm_builder import AutoSwarmBuilder
swarm = AutoSwarmBuilder(
name="Marketing Swarm",
description="A swarm for marketing strategy development",
execution_type="return-agent-configurations"
execution_type="return-agents"
)
# Get agent configurations without executing
@ -310,7 +406,7 @@ agent_configs = swarm.run(
print("Generated agents:")
for agent in agent_configs["agents"]:
print(f"- {agent['name']}: {agent['description']}")
print(f"- {agent['agent_name']}: {agent['description']}")
```
### Example 4: Getting Swarm Router Configuration
@ -384,41 +480,201 @@ result = swarm.run(
)
```
### Example 7: Getting Agent Objects
```python
from swarms.structs.auto_swarm_builder import AutoSwarmBuilder
# Initialize to return agent objects
swarm = AutoSwarmBuilder(
name="Specification Swarm",
description="A swarm for generating agent specifications",
execution_type="return-agents-objects"
)
# Get agent objects
agents = swarm.run(
"Create a team of agents for analyzing customer feedback and generating actionable insights"
)
print(f"Created {len(agents)} agents:")
for agent in agents:
print(f"- {agent.agent_name}: {agent.description}")
```
### Example 8: Getting Agent Dictionary
```python
from swarms.structs.auto_swarm_builder import AutoSwarmBuilder
# Initialize to return agent dictionary
swarm = AutoSwarmBuilder(
name="Dictionary Swarm",
description="A swarm for generating agent dictionaries",
execution_type="return-agents"
)
# Get agent configurations as dictionary
agent_dict = swarm.run(
"Create a marketing team to develop a comprehensive social media strategy"
)
print("Agent Dictionary:")
for agent in agent_dict["agents"]:
print(f"- {agent['agent_name']}: {agent['description']}")
print(f" Model: {agent['model_name']}")
print(f" Role: {agent['role']}")
print(f" Temperature: {agent['temperature']}")
```
### Example 9: Custom System Prompt
```python
from swarms.structs.auto_swarm_builder import AutoSwarmBuilder
# Custom system prompt for specialized domain
custom_prompt = """
You are an expert in financial analysis and risk assessment.
Create specialized agents for financial modeling, risk analysis,
and investment strategy development. Focus on quantitative analysis,
regulatory compliance, and market research capabilities.
"""
# Initialize with custom system prompt
swarm = AutoSwarmBuilder(
name="Financial Analysis Swarm",
description="A specialized swarm for financial analysis",
system_prompt=custom_prompt,
model_name="gpt-4.1",
max_tokens=12000
)
# Run with custom prompt
result = swarm.run(
"Analyze the financial health of a tech startup and provide investment recommendations"
)
```
### Example 10: Advanced Agent Configuration
```python
from swarms.structs.auto_swarm_builder import AutoSwarmBuilder
# Initialize with advanced configuration
swarm = AutoSwarmBuilder(
name="Advanced Swarm",
description="A highly configured swarm with advanced settings",
model_name="gpt-4.1",
max_tokens=16000,
additional_llm_args={"temperature": 0.3},
verbose=True,
interactive=False
)
# Create agents with detailed specifications
agent_specs = swarm.run(
"Develop a comprehensive cybersecurity strategy for a mid-size company"
)
# Build agents from specifications
agents = swarm.create_agents_from_specs(agent_specs)
# Use the agents directly
for agent in agents:
print(f"Agent: {agent.agent_name}")
print(f"Description: {agent.description}")
print(f"Model: {agent.model_name}")
print(f"Max Loops: {agent.max_loops}")
print("---")
```
## Best Practices
!!! tip "Task Definition"
- Provide clear, specific task descriptions
- Include any relevant context or constraints
- Specify expected output format if needed
- Provide clear, specific task descriptions with context and constraints
- Include expected output format and success criteria
- Break complex tasks into smaller, manageable components
- Consider task dependencies and coordination requirements
- Use domain-specific terminology for better agent specialization
!!! note "Configuration"
- Set appropriate `max_loops` based on task complexity
- Set appropriate `max_loops` based on task complexity (typically 1)
- Use `verbose=True` during development for debugging
- Choose the right `execution_type` for your use case:
- Use `"return-agents"` for direct agent interaction
- Use `"return-agent-configurations"` for inspection
- Use `"return-swarm-router-config"` for configuration analysis
- Use `"return-agents"` for getting agent specifications as dictionary (default)
- Use `"execute-swarm-router"` for executing the swarm router with created agents
- Use `"return-swarm-router-config"` for analyzing swarm architecture
- Use `"return-agents-objects"` for getting agent objects created from specifications
- Set `max_tokens` appropriately based on expected response length
- Use `interactive=True` for real-time collaboration scenarios
- Use `additional_llm_args` for passing custom parameters to the LLM
!!! note "Model Selection"
- Choose appropriate `model_name` based on task requirements
- Consider model capabilities and token limits
- Use more powerful models for complex reasoning tasks
- Consider model capabilities, token limits, and cost
- Use more powerful models (GPT-4.1, Claude-3) for complex reasoning
- Use efficient models (GPT-4o-mini) for simple tasks
- Balance performance with cost considerations
- Test different models for optimal results
!!! note "Agent Design"
- Leverage the comprehensive BOSS_SYSTEM_PROMPT for optimal agent creation
- Use custom system prompts for domain-specific applications
- Consider agent personality and role diversity for better collaboration
- Set appropriate temperature values (0.1-0.7) for task requirements
- Use `auto_generate_prompt=True` for dynamic prompt generation
- Configure `max_tokens` based on expected response complexity
!!! note "Swarm Architecture"
- Choose appropriate swarm types based on task requirements
- Use `AgentRearrange` for dynamic task allocation
- Use `MixtureOfAgents` for parallel processing
- Use `GroupChat` for collaborative decision-making
- Use `SequentialWorkflow` for linear task progression
- Consider `HeavySwarm` for high-capacity processing
!!! warning "Error Handling"
- The class includes comprehensive error handling
- All methods include try-catch blocks with detailed logging
- Errors are propagated with full stack traces for debugging
- Always handle exceptions in your calling code
- Always wrap AutoSwarmBuilder calls in try-catch blocks
- Implement appropriate fallback strategies for failures
- Monitor error patterns and adjust configurations
- Use comprehensive logging for debugging
- Handle API rate limits and token limits gracefully
!!! info "Performance Optimization"
- Use `batch_run()` for processing multiple similar tasks
- Consider using `generate_router_config=True` for complex workflows
- Monitor token usage with `max_tokens` parameter
- Use appropriate `swarm_type` for your specific use case
- Implement caching for repeated operations
- Use parallel processing where appropriate
!!! info "Production Deployment"
- Implement proper logging and monitoring
- Use environment variables for sensitive configuration
- Set up health checks and circuit breakers
- Monitor resource usage and performance metrics
- Implement graceful shutdown procedures
- Use proper error reporting and alerting systems
### Best Practices for Error Handling
!!! warning "Always Handle Exceptions"
- Wrap AutoSwarmBuilder calls in try-catch blocks
- Log errors with appropriate detail levels
- Implement appropriate fallback strategies
- Monitor error patterns and adjust configurations
!!! tip "Debugging Configuration Issues"
- Use `verbose=True` during development
- Test with simple tasks first
- Validate model names and API keys
- Check token limits and rate limits
!!! note "Production Considerations"
- Implement circuit breakers for external API calls
- Use health checks to monitor system status
- Set up proper logging and monitoring
- Implement graceful shutdown procedures
## Notes

@ -112,8 +112,8 @@ swarm = HeavySwarm(
description="Comprehensive multi-agent analysis system",
timeout=600,
loops_per_agent=2,
question_agent_model_name="gpt-4o",
worker_model_name="gpt-4o",
question_agent_model_name="gpt-4.1",
worker_model_name="gpt-4.1",
verbose=True,
max_workers=8,
show_dashboard=True,
@ -335,8 +335,8 @@ from swarms.structs.heavy_swarm import HeavySwarm
swarm = HeavySwarm(
name="AdvancedMarketAnalysis",
description="Deep market analysis with multiple iterations",
worker_model_name="gpt-4o",
question_agent_model_name="gpt-4o",
worker_model_name="gpt-4.1",
question_agent_model_name="gpt-4.1",
show_dashboard=True,
loops_per_agent=3, # Multiple iterations for depth
timeout=600,
@ -366,7 +366,7 @@ from swarms.structs.heavy_swarm import HeavySwarm
# Configure for question generation
swarm = HeavySwarm(
name="QuestionGenerator",
question_agent_model_name="gpt-4o",
question_agent_model_name="gpt-4.1",
worker_model_name="gpt-4o-mini",
show_dashboard=False
)
@ -463,7 +463,7 @@ from swarms_tools import exa_search, calculator
swarm = HeavySwarm(
name="CustomToolsSwarm",
description="HeavySwarm with enhanced tool capabilities",
worker_model_name="gpt-4o",
worker_model_name="gpt-4.1",
worker_tools=[exa_search, calculator],
show_dashboard=True,
timeout=600
@ -491,8 +491,8 @@ from swarms.structs.heavy_swarm import HeavySwarm
swarm = HeavySwarm(
name="EnterpriseAnalysis",
description="High-performance enterprise analysis",
worker_model_name="gpt-4o", # Highest quality
question_agent_model_name="gpt-4o",
worker_model_name="gpt-4.1", # Highest quality
question_agent_model_name="gpt-4.1",
show_dashboard=True,
loops_per_agent=5, # Maximum depth
timeout=1800, # 30 minutes
@ -523,7 +523,7 @@ from swarms.structs.heavy_swarm import HeavySwarm
swarm = HeavySwarm(
name="DiverseAnalysis",
description="Analysis with random iteration depth",
worker_model_name="gpt-4o",
worker_model_name="gpt-4.1",
question_agent_model_name="gpt-4o-mini",
show_dashboard=True,
loops_per_agent=1, # Base loops

@ -94,13 +94,13 @@ from swarms.structs.hiearchical_swarm import HierarchicalSwarm
research_agent = Agent(
agent_name="Research-Specialist",
agent_description="Expert in market research and analysis",
model_name="gpt-4o",
model_name="gpt-4.1",
)
financial_agent = Agent(
agent_name="Financial-Analyst",
agent_description="Specialist in financial analysis and valuation",
model_name="gpt-4o",
model_name="gpt-4.1",
)
# Initialize the hierarchical swarm
@ -196,13 +196,13 @@ from swarms.structs.hiearchical_swarm import HierarchicalSwarm
frontend_agent = Agent(
agent_name="Frontend-Developer",
agent_description="Expert in React and modern web development",
model_name="gpt-4o",
model_name="gpt-4.1",
)
backend_agent = Agent(
agent_name="Backend-Developer",
agent_description="Specialist in Node.js and API development",
model_name="gpt-4o",
model_name="gpt-4.1",
)
# Initialize the swarm
@ -246,13 +246,13 @@ from swarms.structs.hiearchical_swarm import HierarchicalSwarm
market_agent = Agent(
agent_name="Market-Analyst",
agent_description="Expert in market analysis and trends",
model_name="gpt-4o",
model_name="gpt-4.1",
)
technical_agent = Agent(
agent_name="Technical-Analyst",
agent_description="Specialist in technical analysis and patterns",
model_name="gpt-4o",
model_name="gpt-4.1",
)
# Initialize the swarm

@ -51,12 +51,12 @@ from swarms.structs.hiearchical_swarm import HierarchicalSwarm
research_agent = Agent(
agent_name="Research-Specialist",
agent_description="Expert in market research and analysis",
model_name="gpt-4o",
model_name="gpt-4.1",
)
financial_agent = Agent(
agent_name="Financial-Analyst",
agent_description="Specialist in financial analysis and valuation",
model_name="gpt-4o",
model_name="gpt-4.1",
)
# Initialize the hierarchical swarm

@ -57,7 +57,7 @@ class MajorityVoting:
consensus_agent_prompt: str = CONSENSUS_AGENT_PROMPT,
consensus_agent_name: str = "Consensus-Agent",
consensus_agent_description: str = "An agent that uses consensus to generate a final answer.",
consensus_agent_model_name: str = "gpt-4o",
consensus_agent_model_name: str = "gpt-4.1",
additional_consensus_agent_kwargs: dict = {},
*args,
**kwargs,
@ -79,7 +79,7 @@ class MajorityVoting:
| `consensus_agent_prompt` | `str` | `CONSENSUS_AGENT_PROMPT` | System prompt for the consensus agent. |
| `consensus_agent_name` | `str` | `"Consensus-Agent"` | Name for the automatically created consensus agent. |
| `consensus_agent_description` | `str` | `"An agent that uses consensus to generate a final answer."` | Description for the consensus agent. |
| `consensus_agent_model_name` | `str` | `"gpt-4o"` | Model name for the consensus agent. |
| `consensus_agent_model_name` | `str` | `"gpt-4.1"` | Model name for the consensus agent. |
| `additional_consensus_agent_kwargs` | `dict` | `{}` | Additional keyword arguments passed to the consensus agent. |
| `*args` | `Any` | - | Variable length argument list passed to Conversation. |
| `**kwargs` | `Any` | - | Arbitrary keyword arguments passed to Conversation. |
@ -619,7 +619,7 @@ technical_agent = Agent(
agent_description="Specialized in technical analysis, chart patterns, and trading signals",
system_prompt=TECHNICAL_ANALYSIS_PROMPT,
max_loops=1,
model_name="gpt-4o",
model_name="gpt-4.1",
)
fundamental_agent = Agent(
@ -627,7 +627,7 @@ fundamental_agent = Agent(
agent_description="Specialized in financial statement analysis and company valuation",
system_prompt=FUNDAMENTAL_ANALYSIS_PROMPT,
max_loops=1,
model_name="gpt-4o",
model_name="gpt-4.1",
)
risk_agent = Agent(
@ -635,7 +635,7 @@ risk_agent = Agent(
agent_description="Specialized in portfolio optimization and risk management strategies",
system_prompt=RISK_MANAGEMENT_PROMPT,
max_loops=1,
model_name="gpt-4o",
model_name="gpt-4.1",
)
# Create the majority voting swarm with the three specialized quant agents
@ -671,21 +671,21 @@ agents = [
agent_description="Market trend analyst",
system_prompt="You are a market analyst specializing in identifying growth opportunities and market trends.",
max_loops=1,
model_name="gpt-4o"
model_name="gpt-4.1"
),
Agent(
agent_name="Risk-Assessment-Agent",
agent_description="Risk analysis expert",
system_prompt="You are a risk assessment expert focused on evaluating investment risks and volatility.",
max_loops=1,
model_name="gpt-4o"
model_name="gpt-4.1"
),
Agent(
agent_name="Portfolio-Strategy-Agent",
agent_description="Portfolio optimization specialist",
system_prompt="You are a portfolio strategist focused on diversification and long-term growth strategies.",
max_loops=1,
model_name="gpt-4o"
model_name="gpt-4.1"
)
]
@ -726,28 +726,28 @@ content_agents = [
agent_description="Creative content specialist",
system_prompt="You are a creative writer who produces engaging, story-driven content with vivid descriptions.",
max_loops=1,
model_name="gpt-4o"
model_name="gpt-4.1"
),
Agent(
agent_name="Technical-Writer",
agent_description="Technical content specialist",
system_prompt="You are a technical writer who focuses on clarity, accuracy, and structured information.",
max_loops=1,
model_name="gpt-4o"
model_name="gpt-4.1"
),
Agent(
agent_name="SEO-Optimized-Writer",
agent_description="SEO content specialist",
system_prompt="You are an SEO specialist who creates content optimized for search engines while maintaining quality.",
max_loops=1,
model_name="gpt-4o"
model_name="gpt-4.1"
),
Agent(
agent_name="Conversational-Writer",
agent_description="Conversational content specialist",
system_prompt="You are a conversational writer who creates relatable, engaging content that connects with readers.",
max_loops=1,
model_name="gpt-4o"
model_name="gpt-4.1"
)
]
@ -791,35 +791,35 @@ research_agents = [
agent_description="Quantitative research specialist",
system_prompt="You are a quantitative researcher who analyzes data, statistics, and numerical evidence.",
max_loops=1,
model_name="gpt-4o"
model_name="gpt-4.1"
),
Agent(
agent_name="Qualitative-Researcher",
agent_description="Qualitative research specialist",
system_prompt="You are a qualitative researcher who focuses on patterns, themes, and contextual understanding.",
max_loops=1,
model_name="gpt-4o"
model_name="gpt-4.1"
),
Agent(
agent_name="Literature-Review-Specialist",
agent_description="Literature review expert",
system_prompt="You are a literature review specialist who synthesizes existing research and identifies knowledge gaps.",
max_loops=1,
model_name="gpt-4o"
model_name="gpt-4.1"
),
Agent(
agent_name="Methodology-Expert",
agent_description="Research methodology specialist",
system_prompt="You are a methodology expert who evaluates research design, validity, and reliability.",
max_loops=1,
model_name="gpt-4o"
model_name="gpt-4.1"
),
Agent(
agent_name="Ethics-Reviewer",
agent_description="Research ethics specialist",
system_prompt="You are an ethics reviewer who ensures research practices are responsible and unbiased.",
max_loops=1,
model_name="gpt-4o"
model_name="gpt-4.1"
)
]

@ -84,7 +84,7 @@ healthcare_router = MultiAgentRouter(
name="Healthcare-Router",
description="Routes medical and healthcare-related tasks to specialized agents",
agents=agents,
model="gpt-4o",
model="gpt-4.1",
temperature=0.1
)

@ -154,11 +154,6 @@ flowchart TD
- Covers detailed implementation, constructor arguments, and full examples
### Auto Agent Builder Documentation:
- [Agent Builder Documentation](https://docs.swarms.world/en/latest/swarms/structs/auto_agent_builder/)
- Includes enterprise use cases, best practices, and integration patterns
3. SwarmRouter Documentation:

@ -36,7 +36,6 @@ This page provides a comprehensive overview of all available multi-agent archite
| Architecture | Use Case | Key Functionality | Documentation |
|-------------|----------|-------------------|---------------|
| HierarchicalSwarm | Hierarchical task orchestration | Director agent coordinates specialized worker agents | [Docs](hierarchical_swarm.md) |
| Auto Agent Builder | Automated agent creation | Automatically creates and configures agents | [Docs](auto_agent_builder.md) |
| Hybrid Hierarchical-Cluster Swarm | Complex organization | Combines hierarchical and cluster-based organization | [Docs](hhcs.md) |
| Auto Swarm Builder | Automated swarm creation | Automatically creates and configures swarms | [Docs](auto_swarm_builder.md) |

@ -107,19 +107,19 @@ from swarms import Agent, SequentialWorkflow
agent1 = Agent(
agent_name="ICD-10 Code Analyzer",
system_prompt="Analyze medical data and provide relevant ICD-10 codes.",
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
)
agent2 = Agent(
agent_name="ICD-10 Code Summarizer",
system_prompt="Summarize the findings and suggest ICD-10 codes.",
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
)
agent3 = Agent(
agent_name="ICD-10 Code Validator",
system_prompt="Validate and finalize the ICD-10 code recommendations.",
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
)

@ -78,12 +78,12 @@ from swarms.structs.transforms import TransformConfig
agent = Agent(
agent_name="Trading-Agent",
agent_description="Financial analysis agent",
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
transforms=TransformConfig(
enabled=True,
method="middle-out",
model_name="gpt-4o",
model_name="gpt-4.1",
preserve_system_messages=True,
preserve_recent_messages=3,
),
@ -160,7 +160,7 @@ Built-in knowledge of popular models:
# Supported models include:
"gpt-4": 8192 tokens
"gpt-4-turbo": 128000 tokens
"gpt-4o": 128000 tokens
"gpt-4.1": 128000 tokens
"claude-3-opus": 200000 tokens
"claude-3-sonnet": 200000 tokens
# ... and many more
@ -213,7 +213,7 @@ from swarms.structs.transforms import apply_transforms_to_messages
# Apply transforms to messages directly
result = apply_transforms_to_messages(
messages=my_messages,
model_name="gpt-4o"
model_name="gpt-4.1"
)
```
@ -226,7 +226,7 @@ Transforms work seamlessly with conversation memory systems:
def handle_transforms(
transforms: MessageTransforms,
short_memory: Conversation,
model_name: str = "gpt-4o"
model_name: str = "gpt-4.1"
) -> str:
"""Apply transforms to conversation memory."""
messages = short_memory.return_messages_as_dictionary()
@ -333,7 +333,7 @@ research_agent = Agent(
# Support bot maintaining conversation history
support_agent = Agent(
agent_name="Support-Agent",
model_name="gpt-4o",
model_name="gpt-4.1",
transforms=TransformConfig(
enabled=True,
preserve_system_messages=True,

@ -334,7 +334,7 @@ agent = Agent(
"clear, accurate financial insights and recommendations. Always format "
"responses in markdown for better readability."
),
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=3,
autosave=True,
dashboard=False,
@ -519,7 +519,7 @@ agent = Agent(
"data and provide comprehensive financial insights. Always present data "
"in a clear, professional format with actionable recommendations."
),
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=3,
autosave=True,
dashboard=False,

@ -20,7 +20,7 @@ from swarms import Agent
# Configure a single fallback model
agent = Agent(
model_name="gpt-4o", # Primary model
model_name="gpt-4.1", # Primary model
fallback_model_name="gpt-4o-mini", # Fallback model
max_loops=1
)
@ -33,7 +33,7 @@ from swarms import Agent
# Configure multiple fallback models using unified list
agent = Agent(
fallback_models=["gpt-4o", "gpt-4o-mini", "gpt-3.5-turbo", "claude-3-haiku"], # First is primary, rest are fallbacks
fallback_models=["gpt-4.1", "gpt-4o-mini", "gpt-3.5-turbo", "claude-3-haiku"], # First is primary, rest are fallbacks
max_loops=1
)
```
@ -45,7 +45,7 @@ from swarms import Agent
# You can use both single fallback and fallback list
agent = Agent(
model_name="gpt-4o", # Primary model
model_name="gpt-4.1", # Primary model
fallback_model_name="gpt-4o-mini", # Single fallback
fallback_models=["gpt-3.5-turbo", "claude-3-haiku"], # Additional fallbacks
max_loops=1
@ -53,7 +53,7 @@ agent = Agent(
# Or use the unified list approach (recommended)
agent = Agent(
fallback_models=["gpt-4o", "gpt-4o-mini", "gpt-3.5-turbo", "claude-3-haiku"],
fallback_models=["gpt-4.1", "gpt-4o-mini", "gpt-3.5-turbo", "claude-3-haiku"],
max_loops=1
)
# Final order: gpt-4o -> gpt-4o-mini -> gpt-3.5-turbo -> claude-3-haiku
@ -128,7 +128,7 @@ from swarms import Agent
# Create agent with fallback models
agent = Agent(
model_name="gpt-4o",
model_name="gpt-4.1",
fallback_models=["gpt-4o-mini", "gpt-3.5-turbo"],
max_loops=1
)
@ -144,7 +144,7 @@ print(response)
from swarms import Agent
agent = Agent(
model_name="gpt-4o",
model_name="gpt-4.1",
fallback_models=["gpt-4o-mini", "gpt-3.5-turbo"],
max_loops=1
)
@ -156,7 +156,7 @@ print(f"Current model: {agent.get_current_model()}")
response = agent.run("Analyze this data")
# Check if fallback was used
if agent.get_current_model() != "gpt-4o":
if agent.get_current_model() != "gpt-4.1":
print(f"Used fallback model: {agent.get_current_model()}")
```
@ -166,7 +166,7 @@ if agent.get_current_model() != "gpt-4o":
from swarms import Agent
agent = Agent(
model_name="gpt-4o",
model_name="gpt-4.1",
fallback_models=["gpt-4o-mini", "gpt-3.5-turbo"],
max_loops=1
)
@ -247,7 +247,7 @@ Enable verbose logging to see detailed fallback information:
```python
agent = Agent(
model_name="gpt-4o",
model_name="gpt-4.1",
fallback_models=["gpt-4o-mini"],
verbose=True # Enable detailed logging
)
@ -261,11 +261,11 @@ If you're upgrading from an agent without fallback support:
```python
# Before
agent = Agent(model_name="gpt-4o")
agent = Agent(model_name="gpt-4.1")
# After
agent = Agent(
model_name="gpt-4o",
model_name="gpt-4.1",
fallback_models=["gpt-4o-mini", "gpt-3.5-turbo"]
)
```

@ -0,0 +1,66 @@
# AOP Examples
This directory contains runnable examples that demonstrate AOP (Agents over Protocol) patterns in Swarms: spinning up a simple MCP server, discovering available agents/tools, and invoking agent tools from client scripts.
## Whats inside
- **Top-level demos**
- [`example_new_agent_tools.py`](./example_new_agent_tools.py): Endtoend demo of agent discovery utilities (list/search agents, get details for one or many). Targets an MCP server at `http://localhost:5932/mcp`.
- [`list_agents_and_call_them.py`](./list_agents_and_call_them.py): Utility helpers to fetch tools from an MCP server and call an agentstyle tool with a task prompt. Defaults to `http://localhost:8000/mcp`.
- [`get_all_agents.py`](./get_all_agents.py): Minimal snippet to print all tools exposed by an MCP server as JSON. Defaults to `http://0.0.0.0:8000/mcp`.
- **Server**
- [`server/server.py`](./server/server.py): Simple MCP server entrypoint you can run locally to expose tools/agents for the client examples.
- **Client**
- [`client/aop_cluster_example.py`](./client/aop_cluster_example.py): Connect to an AOP cluster and interact with agents.
- [`client/aop_queue_example.py`](./client/aop_queue_example.py): Example of queuestyle task submission to agents.
- [`client/aop_raw_task_example.py`](./client/aop_raw_task_example.py): Shows how to send a raw task payload without additional wrappers.
- [`client/aop_raw_client_code.py`](./client/aop_raw_client_code.py): Minimal, lowlevel client calls against the MCP endpoint.
- **Discovery**
- [`discovery/example_agent_communication.py`](./discovery/example_agent_communication.py): Illustrates simple agenttoagent or agenttoservice communication patterns.
- [`discovery/example_aop_discovery.py`](./discovery/example_aop_discovery.py): Demonstrates discovering available agents/tools via AOP.
- [`discovery/simple_discovery_example.py`](./discovery/simple_discovery_example.py): A pareddown discovery walkthrough.
- [`discovery/test_aop_discovery.py`](./discovery/test_aop_discovery.py): Teststyle script validating discovery functionality.
## Prerequisites
- Python environment with project dependencies installed.
- An MCP server running locally (you can use the provided server example).
## Quick start
1. Start a local MCP server (in a separate terminal):
```bash
python examples/aop_examples/server/server.py
```
1. Try discovery utilities (adjust the URL if your server uses a different port):
```bash
# List exposed tools (defaults to http://0.0.0.0:8000/mcp)
python examples/aop_examples/get_all_agents.py
# Fetch tools and call the first agent-like tool (defaults to http://localhost:8000/mcp)
python examples/aop_examples/list_agents_and_call_them.py
# Rich demo of agent info utilities (expects http://localhost:5932/mcp by default)
python examples/aop_examples/example_new_agent_tools.py
```
1. Explore client variants:
```bash
python examples/aop_examples/client/aop_cluster_example.py
python examples/aop_examples/client/aop_queue_example.py
python examples/aop_examples/client/aop_raw_task_example.py
python examples/aop_examples/client/aop_raw_client_code.py
```
## Tips
- **Server URL/port**: Several examples assume `http://localhost:8000/mcp` or `http://localhost:5932/mcp`. If your server runs elsewhere, update the `server_path`/URL variables at the top of the scripts.
- **Troubleshooting**: If a script reports “No tools available”, ensure the MCP server is running and that the endpoint path (`/mcp`) and port match the script.
- **Next steps**: Use these scripts as templates—swap in your own tools/agents, change the search queries, or extend the client calls to fit your workflow.

@ -0,0 +1,47 @@
import json
import asyncio
from swarms.structs.aop import AOPCluster
from swarms.tools.mcp_client_tools import execute_tool_call_simple
async def discover_agents_example():
"""
Discover all agents using the AOPCluster and print the result.
"""
aop_cluster = AOPCluster(
urls=["http://localhost:5932/mcp"],
transport="streamable-http",
)
tool = aop_cluster.find_tool_by_server_name("discover_agents")
if not tool:
print("discover_agents tool not found.")
return None
tool_call_request = {
"type": "function",
"function": {
"name": "discover_agents",
"arguments": "{}",
},
}
result = await execute_tool_call_simple(
response=tool_call_request,
server_path="http://localhost:5932/mcp",
output_type="dict",
verbose=False,
)
print(json.dumps(result, indent=2))
return result
def main():
"""
Run the discover_agents_example coroutine.
"""
asyncio.run(discover_agents_example())
if __name__ == "__main__":
main()

@ -0,0 +1,149 @@
#!/usr/bin/env python3
"""
Example demonstrating the AOP queue system for agent execution.
This example shows how to use the new queue-based execution system
in the AOP framework for improved performance and reliability.
"""
import time
from swarms import Agent
from swarms.structs.aop import AOP
def main():
"""Demonstrate AOP queue functionality."""
# Create some sample agents
agent1 = Agent(
agent_name="Research Agent",
agent_description="Specialized in research tasks",
model_name="gpt-4",
max_loops=1,
)
agent2 = Agent(
agent_name="Writing Agent",
agent_description="Specialized in writing tasks",
model_name="gpt-4",
max_loops=1,
)
# Create AOP with queue enabled
aop = AOP(
server_name="Queue Demo Cluster",
description="A demonstration of queue-based agent execution",
queue_enabled=True,
max_workers_per_agent=2, # 2 workers per agent
max_queue_size_per_agent=100, # Max 100 tasks per queue
processing_timeout=60, # 60 second timeout
retry_delay=2.0, # 2 second delay between retries
verbose=True,
)
# Add agents to the cluster
print("Adding agents to cluster...")
aop.add_agent(agent1, tool_name="researcher")
aop.add_agent(agent2, tool_name="writer")
# Get initial queue stats
print("\nInitial queue stats:")
stats = aop.get_queue_stats()
print(f"Stats: {stats}")
# Add some tasks to the queues
print("\nAdding tasks to queues...")
# Add high priority research task
research_task_id = aop.task_queues["researcher"].add_task(
task="Research the latest developments in quantum computing",
priority=10, # High priority
max_retries=2,
)
print(f"Added research task: {research_task_id}")
# Add medium priority writing task
writing_task_id = aop.task_queues["writer"].add_task(
task="Write a summary of AI trends in 2024",
priority=5, # Medium priority
max_retries=3,
)
print(f"Added writing task: {writing_task_id}")
# Add multiple low priority tasks
for i in range(3):
task_id = aop.task_queues["researcher"].add_task(
task=f"Research task {i+1}: Analyze market trends",
priority=1, # Low priority
max_retries=1,
)
print(f"Added research task {i+1}: {task_id}")
# Get updated queue stats
print("\nUpdated queue stats:")
stats = aop.get_queue_stats()
print(f"Stats: {stats}")
# Monitor task progress
print("\nMonitoring task progress...")
for _ in range(10): # Monitor for 10 iterations
time.sleep(1)
# Check research task status
research_status = aop.get_task_status(
"researcher", research_task_id
)
print(
f"Research task status: {research_status['task']['status'] if research_status['success'] else 'Error'}"
)
# Check writing task status
writing_status = aop.get_task_status(
"writer", writing_task_id
)
print(
f"Writing task status: {writing_status['task']['status'] if writing_status['success'] else 'Error'}"
)
# Get current queue stats
current_stats = aop.get_queue_stats()
if current_stats["success"]:
for agent_name, agent_stats in current_stats[
"stats"
].items():
print(
f"{agent_name}: {agent_stats['pending_tasks']} pending, {agent_stats['processing_tasks']} processing, {agent_stats['completed_tasks']} completed"
)
print("---")
# Demonstrate queue management
print("\nDemonstrating queue management...")
# Pause the research agent queue
print("Pausing research agent queue...")
aop.pause_agent_queue("researcher")
# Get queue status
research_queue_status = aop.task_queues["researcher"].get_status()
print(f"Research queue status: {research_queue_status.value}")
# Resume the research agent queue
print("Resuming research agent queue...")
aop.resume_agent_queue("researcher")
# Clear all queues
print("Clearing all queues...")
cleared = aop.clear_all_queues()
print(f"Cleared tasks: {cleared}")
# Final stats
print("\nFinal queue stats:")
final_stats = aop.get_queue_stats()
print(f"Final stats: {final_stats}")
print("\nQueue demonstration completed!")
if __name__ == "__main__":
main()

@ -0,0 +1,88 @@
import json
import asyncio
from swarms.structs.aop import AOPCluster
from swarms.tools.mcp_client_tools import execute_tool_call_simple
from mcp import ClientSession
from mcp.client.streamable_http import streamablehttp_client
async def discover_agents_example():
"""
Discover all agents using the AOPCluster and print the result.
"""
aop_cluster = AOPCluster(
urls=["http://localhost:5932/mcp"],
transport="streamable-http",
)
tool = aop_cluster.find_tool_by_server_name("discover_agents")
if not tool:
print("discover_agents tool not found.")
return None
tool_call_request = {
"type": "function",
"function": {
"name": "discover_agents",
"arguments": "{}",
},
}
result = await execute_tool_call_simple(
response=tool_call_request,
server_path="http://localhost:5932/mcp",
output_type="dict",
verbose=False,
)
print(json.dumps(result, indent=2))
return result
async def raw_mcp_discover_agents_example():
"""
Call the MCP server directly using the raw MCP client to execute the
built-in "discover_agents" tool and print the JSON result.
This demonstrates how to:
- Initialize an MCP client over streamable HTTP
- List available tools (optional)
- Call a specific tool by name with arguments
"""
url = "http://localhost:5932/mcp"
# Open a raw MCP client connection
async with streamablehttp_client(url, timeout=10) as ctx:
if len(ctx) == 2:
read, write = ctx
else:
read, write, *_ = ctx
async with ClientSession(read, write) as session:
# Initialize the MCP session and optionally inspect tools
await session.initialize()
# Optional: list tools (uncomment to print)
# tools = await session.list_tools()
# print(json.dumps(tools.model_dump(), indent=2))
# Call the built-in discovery tool with empty arguments
result = await session.call_tool(
name="discover_agents",
arguments={},
)
# Convert to dict for pretty printing
print(json.dumps(result.model_dump(), indent=2))
return result.model_dump()
def main():
"""
Run the helper-based and raw MCP client discovery examples.
"""
asyncio.run(discover_agents_example())
asyncio.run(raw_mcp_discover_agents_example())
if __name__ == "__main__":
main()

@ -0,0 +1,107 @@
import json
import asyncio
from mcp import ClientSession
from mcp.client.streamable_http import streamablehttp_client
async def call_agent_tool_raw(
url: str,
tool_name: str,
task: str,
img: str | None = None,
imgs: list[str] | None = None,
correct_answer: str | None = None,
) -> dict:
"""
Call a specific agent tool on an MCP server using the raw MCP client.
Args:
url: MCP server URL (e.g., "http://localhost:5932/mcp").
tool_name: Name of the tool/agent to invoke.
task: Task prompt to execute.
img: Optional single image path/URL.
imgs: Optional list of image paths/URLs.
correct_answer: Optional expected answer for validation.
Returns:
A dict containing the tool's JSON response.
"""
# Open a raw MCP client connection over streamable HTTP
async with streamablehttp_client(url, timeout=30) as ctx:
if len(ctx) == 2:
read, write = ctx
else:
read, write, *_ = ctx
async with ClientSession(read, write) as session:
# Initialize the MCP session
await session.initialize()
# Prepare arguments in the canonical AOP tool format
arguments: dict = {"task": task}
if img is not None:
arguments["img"] = img
if imgs is not None:
arguments["imgs"] = imgs
if correct_answer is not None:
arguments["correct_answer"] = correct_answer
# Invoke the tool by name
result = await session.call_tool(
name=tool_name, arguments=arguments
)
# Convert to dict for return/printing
return result.model_dump()
async def list_available_tools(url: str) -> dict:
"""
List tools from an MCP server using the raw client.
Args:
url: MCP server URL (e.g., "http://localhost:5932/mcp").
Returns:
A dict representation of the tools listing.
"""
async with streamablehttp_client(url, timeout=30) as ctx:
if len(ctx) == 2:
read, write = ctx
else:
read, write, *_ = ctx
async with ClientSession(read, write) as session:
await session.initialize()
tools = await session.list_tools()
return tools.model_dump()
def main() -> None:
"""
Demonstration entrypoint: list tools, then call a specified tool with a task.
"""
url = "http://localhost:5932/mcp"
tool_name = "Research-Agent" # Change to your agent tool name
task = "Summarize the latest advances in agent orchestration protocols."
# List tools
tools_info = asyncio.run(list_available_tools(url))
print("Available tools:")
print(json.dumps(tools_info, indent=2))
# Call the tool
print(f"\nCalling tool '{tool_name}' with task...\n")
result = asyncio.run(
call_agent_tool_raw(
url=url,
tool_name=tool_name,
task=task,
)
)
print(json.dumps(result, indent=2))
if __name__ == "__main__":
main()

@ -0,0 +1,149 @@
#!/usr/bin/env python3
"""
Example showing how agents can use the discovery tool to learn about each other
and collaborate more effectively.
"""
from swarms import Agent
from swarms.structs.aop import AOP
def simulate_agent_discovery():
"""Simulate how an agent would use the discovery tool."""
# Create a sample agent that will use the discovery tool
Agent(
agent_name="ProjectCoordinator",
agent_description="Coordinates projects and assigns tasks to other agents",
system_prompt="You are a project coordinator who helps organize work and delegate tasks to the most appropriate team members. You can discover information about other agents to make better decisions.",
model_name="gpt-4o-mini",
temperature=0.4,
)
# Create the AOP cluster
aop = AOP(
server_name="Project Team",
description="A team of specialized agents for project coordination",
verbose=True,
)
# Add some specialized agents
data_agent = Agent(
agent_name="DataSpecialist",
agent_description="Handles all data-related tasks and analysis",
system_prompt="You are a data specialist with expertise in data processing, analysis, and visualization. You work with large datasets and create insights.",
tags=["data", "analysis", "python", "sql", "statistics"],
capabilities=[
"data_processing",
"statistical_analysis",
"visualization",
],
role="specialist",
)
code_agent = Agent(
agent_name="CodeSpecialist",
agent_description="Handles all coding and development tasks",
system_prompt="You are a software development specialist who writes clean, efficient code and follows best practices. You handle both frontend and backend development.",
tags=[
"coding",
"development",
"python",
"javascript",
"react",
],
capabilities=[
"software_development",
"code_review",
"debugging",
],
role="developer",
)
writing_agent = Agent(
agent_name="ContentSpecialist",
agent_description="Creates and manages all written content",
system_prompt="You are a content specialist who creates engaging written content, documentation, and marketing materials. You ensure all content is clear and compelling.",
tags=["writing", "content", "documentation", "marketing"],
capabilities=[
"content_creation",
"technical_writing",
"editing",
],
role="writer",
)
# Add agents to the cluster
aop.add_agent(data_agent, tool_name="data_specialist")
aop.add_agent(code_agent, tool_name="code_specialist")
aop.add_agent(writing_agent, tool_name="content_specialist")
print("🏢 Project Team AOP Cluster Created!")
print(f"👥 Team members: {aop.list_agents()}")
print()
# Simulate the coordinator discovering team members
print("🔍 Project Coordinator discovering team capabilities...")
print()
# Get discovery info for each agent
for tool_name in aop.list_agents():
if (
tool_name != "discover_agents"
): # Skip the discovery tool itself
agent_info = aop._get_agent_discovery_info(tool_name)
if agent_info:
print(f"📋 {agent_info['agent_name']}:")
print(f" Description: {agent_info['description']}")
print(f" Role: {agent_info['role']}")
print(f" Tags: {', '.join(agent_info['tags'])}")
print(
f" Capabilities: {', '.join(agent_info['capabilities'])}"
)
print(
f" System Prompt: {agent_info['short_system_prompt'][:100]}..."
)
print()
print("💡 How agents would use this in practice:")
print(" 1. Agent calls 'discover_agents' MCP tool")
print(" 2. Gets information about all available agents")
print(
" 3. Uses this info to make informed decisions about task delegation"
)
print(
" 4. Can discover specific agents by name for targeted collaboration"
)
print()
# Show what the MCP tool response would look like
print("📡 Sample MCP tool response structure:")
print(" discover_agents() -> {")
print(" 'success': True,")
print(" 'agents': [")
print(" {")
print(" 'tool_name': 'data_specialist',")
print(" 'agent_name': 'DataSpecialist',")
print(
" 'description': 'Handles all data-related tasks...',"
)
print(
" 'short_system_prompt': 'You are a data specialist...',"
)
print(" 'tags': ['data', 'analysis', 'python'],")
print(
" 'capabilities': ['data_processing', 'statistics'],"
)
print(" 'role': 'specialist',")
print(" ...")
print(" }")
print(" ]")
print(" }")
print()
print("✅ Agent discovery system ready for collaborative work!")
if __name__ == "__main__":
simulate_agent_discovery()

@ -0,0 +1,117 @@
#!/usr/bin/env python3
"""
Example demonstrating the new agent discovery MCP tool in AOP.
This example shows how agents can discover information about each other
using the new 'discover_agents' MCP tool.
"""
from swarms import Agent
from swarms.structs.aop import AOP
def main():
"""Demonstrate the agent discovery functionality."""
# Create some sample agents with different configurations
agent1 = Agent(
agent_name="DataAnalyst",
agent_description="Specialized in data analysis and visualization",
system_prompt="You are a data analyst with expertise in Python, pandas, and statistical analysis. You help users understand data patterns and create visualizations.",
tags=["data", "analysis", "python", "pandas"],
capabilities=["data_analysis", "visualization", "statistics"],
role="analyst",
model_name="gpt-4o-mini",
temperature=0.3,
)
agent2 = Agent(
agent_name="CodeReviewer",
agent_description="Expert code reviewer and quality assurance specialist",
system_prompt="You are a senior software engineer who specializes in code review, best practices, and quality assurance. You help identify bugs, suggest improvements, and ensure code follows industry standards.",
tags=["code", "review", "quality", "python", "javascript"],
capabilities=[
"code_review",
"quality_assurance",
"best_practices",
],
role="reviewer",
model_name="gpt-4o-mini",
temperature=0.2,
)
agent3 = Agent(
agent_name="CreativeWriter",
agent_description="Creative content writer and storyteller",
system_prompt="You are a creative writer who specializes in storytelling, content creation, and engaging narratives. You help create compelling stories, articles, and marketing content.",
tags=["writing", "creative", "content", "storytelling"],
capabilities=[
"creative_writing",
"content_creation",
"storytelling",
],
role="writer",
model_name="gpt-4o-mini",
temperature=0.8,
)
# Create AOP cluster with the agents
aop = AOP(
server_name="Agent Discovery Demo",
description="A demo cluster showing agent discovery capabilities",
agents=[agent1, agent2, agent3],
verbose=True,
)
print("🚀 AOP Cluster initialized with agent discovery tool!")
print(f"📊 Total agents registered: {len(aop.agents)}")
print(f"🔧 Available tools: {aop.list_agents()}")
print()
# Demonstrate the discovery tool
print("🔍 Testing agent discovery functionality...")
print()
# Test discovering all agents
print("1. Discovering all agents:")
all_agents_info = aop._get_agent_discovery_info(
"DataAnalyst"
) # This would normally be called via MCP
print(
f" Found agent: {all_agents_info['agent_name'] if all_agents_info else 'None'}"
)
print()
# Show what the MCP tool would return
print("2. What the 'discover_agents' MCP tool would return:")
print(" - Tool name: discover_agents")
print(
" - Description: Discover information about other agents in the cluster"
)
print(" - Parameters: agent_name (optional)")
print(
" - Returns: Agent info including name, description, short system prompt, tags, capabilities, role, etc."
)
print()
# Show sample agent info structure
if all_agents_info:
print("3. Sample agent discovery info structure:")
for key, value in all_agents_info.items():
if key == "short_system_prompt":
print(f" {key}: {value[:100]}...")
else:
print(f" {key}: {value}")
print()
print("✅ Agent discovery tool successfully integrated!")
print(
"💡 Agents can now use the 'discover_agents' MCP tool to learn about each other."
)
print(
"🔄 The tool is automatically updated when new agents are added to the cluster."
)
if __name__ == "__main__":
main()

@ -0,0 +1,231 @@
#!/usr/bin/env python3
"""
Simple example showing how to call the discover_agents tool synchronously.
"""
import json
import asyncio
from swarms.structs.aop import AOPCluster
from swarms.tools.mcp_client_tools import execute_tool_call_simple
def call_discover_agents_sync(server_url="http://localhost:5932/mcp"):
"""
Synchronously call the discover_agents tool.
Args:
server_url: URL of the MCP server
Returns:
Dict containing the discovery results
"""
# Create the tool call request
tool_call_request = {
"type": "function",
"function": {
"name": "discover_agents",
"arguments": json.dumps({}), # Empty = get all agents
},
}
# Run the async function
return asyncio.run(
execute_tool_call_simple(
response=tool_call_request,
server_path=server_url,
output_type="dict",
)
)
def call_discover_specific_agent_sync(
agent_name, server_url="http://localhost:5932/mcp"
):
"""
Synchronously call the discover_agents tool for a specific agent.
Args:
agent_name: Name of the specific agent to discover
server_url: URL of the MCP server
Returns:
Dict containing the discovery results
"""
# Create the tool call request
tool_call_request = {
"type": "function",
"function": {
"name": "discover_agents",
"arguments": json.dumps({"agent_name": agent_name}),
},
}
# Run the async function
return asyncio.run(
execute_tool_call_simple(
response=tool_call_request,
server_path=server_url,
output_type="dict",
)
)
def main():
"""Main function demonstrating discovery tool usage."""
print("🔍 AOP Agent Discovery Tool Example")
print("=" * 40)
print()
# First, check what tools are available
print("1. Checking available MCP tools...")
aop_cluster = AOPCluster(
urls=["http://localhost:5932/mcp"],
transport="streamable-http",
)
tools = aop_cluster.get_tools(output_type="dict")
print(f" Found {len(tools)} tools")
# Check if discover_agents is available
discover_tool = aop_cluster.find_tool_by_server_name(
"discover_agents"
)
if not discover_tool:
print("❌ discover_agents tool not found!")
print(
" Make sure your AOP server is running with agents registered."
)
return
print("✅ discover_agents tool found!")
print()
# Discover all agents
print("2. Discovering all agents...")
try:
result = call_discover_agents_sync()
if isinstance(result, list) and len(result) > 0:
discovery_data = result[0]
if discovery_data.get("success"):
agents = discovery_data.get("agents", [])
print(f" ✅ Found {len(agents)} agents:")
for i, agent in enumerate(agents, 1):
print(
f" {i}. {agent.get('agent_name', 'Unknown')}"
)
print(
f" Role: {agent.get('role', 'worker')}"
)
print(
f" Description: {agent.get('description', 'No description')}"
)
print(
f" Tags: {', '.join(agent.get('tags', []))}"
)
print(
f" Capabilities: {', '.join(agent.get('capabilities', []))}"
)
print(
f" System Prompt: {agent.get('short_system_prompt', 'No prompt')[:100]}..."
)
print()
else:
print(
f" ❌ Discovery failed: {discovery_data.get('error', 'Unknown error')}"
)
else:
print(" ❌ No valid result returned")
except Exception as e:
print(f" ❌ Error: {e}")
print()
# Example of discovering a specific agent (if any exist)
print("3. Example: Discovering a specific agent...")
try:
# Try to discover the first agent specifically
if isinstance(result, list) and len(result) > 0:
discovery_data = result[0]
if discovery_data.get("success") and discovery_data.get(
"agents"
):
first_agent_name = discovery_data["agents"][0].get(
"agent_name"
)
if first_agent_name:
print(
f" Looking for specific agent: {first_agent_name}"
)
specific_result = (
call_discover_specific_agent_sync(
first_agent_name
)
)
if (
isinstance(specific_result, list)
and len(specific_result) > 0
):
specific_data = specific_result[0]
if specific_data.get("success"):
agent = specific_data.get("agents", [{}])[
0
]
print(
f" ✅ Found specific agent: {agent.get('agent_name', 'Unknown')}"
)
print(
f" Model: {agent.get('model_name', 'Unknown')}"
)
print(
f" Max Loops: {agent.get('max_loops', 1)}"
)
print(
f" Temperature: {agent.get('temperature', 0.5)}"
)
else:
print(
f" ❌ Specific discovery failed: {specific_data.get('error')}"
)
else:
print(" ❌ No valid specific result")
else:
print(
" ⚠️ No agents found to test specific discovery"
)
else:
print(
" ⚠️ No agents available for specific discovery"
)
else:
print(
" ⚠️ No previous discovery results to use for specific discovery"
)
except Exception as e:
print(f" ❌ Error in specific discovery: {e}")
print()
print("✅ Discovery tool demonstration complete!")
print()
print("💡 Usage Summary:")
print(
" • Call discover_agents() with no arguments to get all agents"
)
print(
" • Call discover_agents(agent_name='AgentName') to get specific agent"
)
print(
" • Each agent returns: name, description, role, tags, capabilities, system prompt, etc."
)
if __name__ == "__main__":
main()

@ -0,0 +1,198 @@
#!/usr/bin/env python3
"""
Test script to verify the agent discovery functionality works correctly.
"""
import sys
import os
# Add the swarms directory to the path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "swarms"))
from swarms import Agent
from swarms.structs.aop import AOP
def test_agent_discovery():
"""Test the agent discovery functionality."""
print("🧪 Testing AOP Agent Discovery Functionality")
print("=" * 50)
# Create test agents
agent1 = Agent(
agent_name="TestAgent1",
agent_description="First test agent for discovery",
system_prompt="This is a test agent with a very long system prompt that should be truncated to 200 characters when returned by the discovery tool. This prompt contains detailed instructions about how the agent should behave and what tasks it can perform.",
tags=["test", "agent", "discovery"],
capabilities=["testing", "validation"],
role="tester",
)
agent2 = Agent(
agent_name="TestAgent2",
agent_description="Second test agent for discovery",
system_prompt="Another test agent with different capabilities and a shorter prompt.",
tags=["test", "agent", "analysis"],
capabilities=["analysis", "reporting"],
role="analyst",
)
# Create AOP cluster
aop = AOP(
server_name="Test Cluster",
description="Test cluster for agent discovery",
verbose=False,
)
# Add agents
aop.add_agent(agent1, tool_name="test_agent_1")
aop.add_agent(agent2, tool_name="test_agent_2")
print(f"✅ Created AOP cluster with {len(aop.agents)} agents")
print(f"📋 Available tools: {aop.list_agents()}")
print()
# Test discovery functionality
print("🔍 Testing agent discovery...")
# Test getting info for specific agent
agent1_info = aop._get_agent_discovery_info("test_agent_1")
assert (
agent1_info is not None
), "Should be able to get info for test_agent_1"
assert (
agent1_info["agent_name"] == "TestAgent1"
), "Agent name should match"
assert (
agent1_info["description"] == "First test agent for discovery"
), "Description should match"
assert (
len(agent1_info["short_system_prompt"]) <= 203
), "System prompt should be truncated to ~200 chars"
assert "test" in agent1_info["tags"], "Tags should include 'test'"
assert (
"testing" in agent1_info["capabilities"]
), "Capabilities should include 'testing'"
assert agent1_info["role"] == "tester", "Role should be 'tester'"
print("✅ Specific agent discovery test passed")
# Test getting info for non-existent agent
non_existent_info = aop._get_agent_discovery_info(
"non_existent_agent"
)
assert (
non_existent_info is None
), "Should return None for non-existent agent"
print("✅ Non-existent agent test passed")
# Test that discovery tool is registered
# Note: In a real scenario, this would be tested via MCP tool calls
# For now, we just verify the method exists and works
try:
# This simulates what the MCP tool would do
discovery_result = {"success": True, "agents": []}
for tool_name in aop.agents.keys():
agent_info = aop._get_agent_discovery_info(tool_name)
if agent_info:
discovery_result["agents"].append(agent_info)
assert (
len(discovery_result["agents"]) == 2
), "Should discover both agents"
assert (
discovery_result["success"] is True
), "Discovery should be successful"
print("✅ Discovery tool simulation test passed")
except Exception as e:
print(f"❌ Discovery tool test failed: {e}")
return False
# Test system prompt truncation
long_prompt = "A" * 300 # 300 character string
agent_with_long_prompt = Agent(
agent_name="LongPromptAgent",
agent_description="Agent with very long system prompt",
system_prompt=long_prompt,
)
aop.add_agent(
agent_with_long_prompt, tool_name="long_prompt_agent"
)
long_prompt_info = aop._get_agent_discovery_info(
"long_prompt_agent"
)
assert (
long_prompt_info is not None
), "Should get info for long prompt agent"
assert (
len(long_prompt_info["short_system_prompt"]) == 203
), "Should truncate to 200 chars + '...'"
assert long_prompt_info["short_system_prompt"].endswith(
"..."
), "Should end with '...'"
print("✅ System prompt truncation test passed")
# Test with missing attributes
minimal_agent = Agent(
agent_name="MinimalAgent",
# No description, tags, capabilities, or role specified
)
aop.add_agent(minimal_agent, tool_name="minimal_agent")
minimal_info = aop._get_agent_discovery_info("minimal_agent")
assert (
minimal_info is not None
), "Should get info for minimal agent"
assert (
minimal_info["description"] == "No description available"
), "Should have default description"
assert minimal_info["tags"] == [], "Should have empty tags list"
assert (
minimal_info["capabilities"] == []
), "Should have empty capabilities list"
assert (
minimal_info["role"] == "worker"
), "Should have default role"
print("✅ Minimal agent attributes test passed")
print()
print(
"🎉 All tests passed! Agent discovery functionality is working correctly."
)
print()
print("📊 Summary of discovered agents:")
for tool_name in aop.agents.keys():
info = aop._get_agent_discovery_info(tool_name)
if info:
print(
f"{info['agent_name']} ({info['role']}) - {info['description']}"
)
return True
if __name__ == "__main__":
try:
success = test_agent_discovery()
if success:
print("\n✅ All tests completed successfully!")
sys.exit(0)
else:
print("\n❌ Some tests failed!")
sys.exit(1)
except Exception as e:
print(f"\n💥 Test failed with exception: {e}")
import traceback
traceback.print_exc()
sys.exit(1)

@ -0,0 +1,225 @@
#!/usr/bin/env python3
"""
Example demonstrating the new agent information tools in AOP.
This example shows how to use the new MCP tools for getting agent information.
"""
import json
import asyncio
from swarms.structs.aop import AOPCluster
from swarms.tools.mcp_client_tools import execute_tool_call_simple
async def demonstrate_new_agent_tools():
"""Demonstrate the new agent information tools."""
# Create AOP cluster connection
AOPCluster(
urls=["http://localhost:5932/mcp"],
transport="streamable-http",
)
print("🔧 New AOP Agent Information Tools Demo")
print("=" * 50)
print()
# 1. List all agents
print("1. Listing all agents...")
try:
tool_call = {
"type": "function",
"function": {"name": "list_agents", "arguments": "{}"},
}
result = await execute_tool_call_simple(
response=tool_call,
server_path="http://localhost:5932/mcp",
output_type="dict",
verbose=False,
)
if isinstance(result, list) and len(result) > 0:
data = result[0]
if data.get("success"):
agent_names = data.get("agent_names", [])
print(
f" Found {len(agent_names)} agents: {agent_names}"
)
else:
print(f" Error: {data.get('error')}")
else:
print(" No valid result returned")
except Exception as e:
print(f" Error: {e}")
print()
# 2. Get details for a specific agent
print("2. Getting details for a specific agent...")
try:
tool_call = {
"type": "function",
"function": {
"name": "get_agent_details",
"arguments": json.dumps(
{"agent_name": "Research-Agent"}
),
},
}
result = await execute_tool_call_simple(
response=tool_call,
server_path="http://localhost:5932/mcp",
output_type="dict",
verbose=False,
)
if isinstance(result, list) and len(result) > 0:
data = result[0]
if data.get("success"):
data.get("agent_info", {})
discovery_info = data.get("discovery_info", {})
print(
f" Agent: {discovery_info.get('agent_name', 'Unknown')}"
)
print(
f" Description: {discovery_info.get('description', 'No description')}"
)
print(
f" Model: {discovery_info.get('model_name', 'Unknown')}"
)
print(f" Tags: {discovery_info.get('tags', [])}")
print(
f" Capabilities: {discovery_info.get('capabilities', [])}"
)
else:
print(f" Error: {data.get('error')}")
else:
print(" No valid result returned")
except Exception as e:
print(f" Error: {e}")
print()
# 3. Get info for multiple agents
print("3. Getting info for multiple agents...")
try:
tool_call = {
"type": "function",
"function": {
"name": "get_agents_info",
"arguments": json.dumps(
{
"agent_names": [
"Research-Agent",
"DataAnalyst",
"Writer",
]
}
),
},
}
result = await execute_tool_call_simple(
response=tool_call,
server_path="http://localhost:5932/mcp",
output_type="dict",
verbose=False,
)
if isinstance(result, list) and len(result) > 0:
data = result[0]
if data.get("success"):
agents_info = data.get("agents_info", [])
not_found = data.get("not_found", [])
print(
f" Found {len(agents_info)} agents out of {data.get('total_requested', 0)} requested"
)
for agent in agents_info:
discovery_info = agent.get("discovery_info", {})
print(
f"{discovery_info.get('agent_name', 'Unknown')}: {discovery_info.get('description', 'No description')}"
)
if not_found:
print(f" Not found: {not_found}")
else:
print(f" Error: {data.get('error')}")
else:
print(" No valid result returned")
except Exception as e:
print(f" Error: {e}")
print()
# 4. Search for agents
print("4. Searching for agents...")
try:
tool_call = {
"type": "function",
"function": {
"name": "search_agents",
"arguments": json.dumps(
{
"query": "data",
"search_fields": [
"name",
"description",
"tags",
"capabilities",
],
}
),
},
}
result = await execute_tool_call_simple(
response=tool_call,
server_path="http://localhost:5932/mcp",
output_type="dict",
verbose=False,
)
if isinstance(result, list) and len(result) > 0:
data = result[0]
if data.get("success"):
matching_agents = data.get("matching_agents", [])
print(
f" Found {len(matching_agents)} agents matching 'data'"
)
for agent in matching_agents:
print(
f"{agent.get('agent_name', 'Unknown')}: {agent.get('description', 'No description')}"
)
print(f" Tags: {agent.get('tags', [])}")
print(
f" Capabilities: {agent.get('capabilities', [])}"
)
else:
print(f" Error: {data.get('error')}")
else:
print(" No valid result returned")
except Exception as e:
print(f" Error: {e}")
print()
print("✅ New agent tools demonstration complete!")
print()
print("💡 Available Tools:")
print(
" • discover_agents - Get discovery info for all or specific agents"
)
print(
" • get_agent_details - Get detailed info for a single agent"
)
print(
" • get_agents_info - Get detailed info for multiple agents"
)
print(" • list_agents - Get simple list of all agent names")
print(" • search_agents - Search agents by keywords")
def main():
"""Main function to run the demonstration."""
asyncio.run(demonstrate_new_agent_tools())
if __name__ == "__main__":
main()

@ -0,0 +1,10 @@
import json
from swarms.tools.mcp_client_tools import get_mcp_tools_sync
print(
json.dumps(
get_mcp_tools_sync(server_path="http://0.0.0.0:8000/mcp"),
indent=4,
)
)

@ -0,0 +1,105 @@
import json
from swarms.tools.mcp_client_tools import (
get_mcp_tools_sync,
execute_tool_call_simple,
)
def get_available_tools(
server_path: str = "http://localhost:8000/mcp",
) -> list:
"""
Get all available MCP tools from the server.
Args:
server_path: URL of the MCP server
Returns:
List of available tools
"""
tools = get_mcp_tools_sync(server_path=server_path)
return tools
def call_agent_tool(
tool_name: str,
task: str,
server_path: str = "http://localhost:8000/mcp",
) -> dict:
"""
Call a specific agent tool with a task.
Args:
tool_name: Name of the agent tool to call
task: Task or prompt to send to the agent
server_path: URL of the MCP server
Returns:
Response from the agent tool
"""
call = {
"function": {
"name": tool_name,
"arguments": {"task": task},
}
}
try:
import asyncio
result = asyncio.run(
execute_tool_call_simple(
response=call, server_path=server_path
)
)
return result
except Exception as e:
return {"error": str(e)}
def main():
"""
Main function to demonstrate MCP tool usage.
"""
server_path = "http://localhost:8000/mcp"
# Step 1: Get available tools
tools = get_available_tools(server_path)
if not tools:
return {
"error": "No tools available. Make sure the MCP server is running."
}
# Step 2: Find an agent tool to call
agent_tools = [
tool
for tool in tools
if "agent" in tool.get("function", {}).get("name", "").lower()
]
if not agent_tools:
return {
"error": "No agent tools found",
"available_tools": [
tool.get("function", {}).get("name", "Unknown")
for tool in tools
],
}
# Step 3: Call the first available agent tool
agent_tool = agent_tools[0]
tool_name = agent_tool.get("function", {}).get("name")
# Example task
task = "Hello! Can you help me understand what you do and what capabilities you have?"
# Call the agent
result = call_agent_tool(tool_name, task, server_path)
return result
if __name__ == "__main__":
result = main()
print(json.dumps(result, indent=4))

@ -0,0 +1,113 @@
import asyncio
import json
from typing import Dict
import requests
from swarms.structs.aop import AOPCluster
from swarms.tools.mcp_client_tools import execute_tool_call_simple
def _select_tools_by_keyword(tools: list, keyword: str) -> list:
"""
Return tools whose name or description contains the keyword
(case-insensitive).
"""
kw = keyword.lower()
selected = []
for t in tools:
name = t.get("function", {}).get("name", "")
desc = t.get("function", {}).get("description", "")
if kw in name.lower() or kw in desc.lower():
selected.append(t)
return selected
def _example_payload_from_schema(tools: list, tool_name: str) -> dict:
"""
Construct a minimal example payload for a given tool using its JSON schema.
Falls back to a generic 'task' if schema not present.
"""
for t in tools:
fn = t.get("function", {})
if fn.get("name") == tool_name:
schema = fn.get("parameters", {})
required = schema.get("required", [])
props = schema.get("properties", {})
payload = {}
for r in required:
if r in props:
if props[r].get("type") == "string":
payload[r] = (
"Example patient case: 45M, egfr 59 ml/min/1.73"
)
elif props[r].get("type") == "boolean":
payload[r] = False
else:
payload[r] = None
if not payload:
payload = {
"task": "Provide ICD-10 suggestions for the case above"
}
return payload
return {"task": "Provide ICD-10 suggestions for the case above"}
def main() -> None:
cluster = AOPCluster(
urls=["http://localhost:8000/mcp"],
transport="streamable-http",
)
tools = cluster.get_tools(output_type="dict")
print(f"Tools: {len(tools)}")
coding_tools = _select_tools_by_keyword(tools, "coder")
names = [t.get("function", {}).get("name") for t in coding_tools]
print(f"Coding-related tools: {names}")
# Build a real payload for "Medical Coder" and execute the tool call
tool_name = "Medical Coder"
payload: Dict[str, object] = _example_payload_from_schema(tools, tool_name)
# Enrich with public keyless data (epidemiology context via disease.sh)
try:
epi = requests.get(
"https://disease.sh/v3/covid-19/countries/USA?strict=true",
timeout=5,
)
if epi.ok:
data = epi.json()
epi_summary = (
f"US COVID-19 context: cases={data.get('cases')}, "
f"todayCases={data.get('todayCases')}, deaths={data.get('deaths')}"
)
base_task = payload.get("task") or ""
payload["task"] = (
f"{base_task}\n\nEpidemiology context (no key API): {epi_summary}"
)
except Exception:
pass
print("Calling tool:", tool_name)
request = {
"function": {
"name": tool_name,
"arguments": payload,
}
}
result = asyncio.run(
execute_tool_call_simple(
response=request,
server_path="http://localhost:8000/mcp",
output_type="json",
transport="streamable-http",
verbose=False,
)
)
print("Response:")
print(result)
if __name__ == "__main__":
main()

@ -0,0 +1,166 @@
# Import medical agents defined in the demo module
from examples.demos.medical.medical_coder_agent import (chief_medical_officer,
internist,
medical_coder,
synthesizer,
virologist)
from swarms.structs.aop import AOP
def _enrich_agents_metadata() -> None:
"""
Add lightweight tags/capabilities/roles to imported agents for
better discovery results.
"""
chief_medical_officer.tags = [
"coordination",
"diagnosis",
"triage",
]
chief_medical_officer.capabilities = [
"case-intake",
"differential",
"planning",
]
chief_medical_officer.role = "coordinator"
virologist.tags = ["virology", "infectious-disease"]
virologist.capabilities = ["viral-analysis", "icd10-suggestion"]
virologist.role = "specialist"
internist.tags = ["internal-medicine", "evaluation"]
internist.capabilities = [
"system-review",
"hcc-tagging",
"risk-stratification",
]
internist.role = "specialist"
medical_coder.tags = ["coding", "icd10", "compliance"]
medical_coder.capabilities = [
"code-assignment",
"documentation-review",
]
medical_coder.role = "coder"
synthesizer.tags = ["synthesis", "reporting"]
synthesizer.capabilities = [
"evidence-reconciliation",
"final-report",
]
synthesizer.role = "synthesizer"
def _medical_input_schema() -> dict:
return {
"type": "object",
"properties": {
"task": {
"type": "string",
"description": "Patient case or instruction for the agent",
},
"priority": {
"type": "string",
"enum": ["low", "normal", "high"],
"description": "Processing priority",
},
"include_images": {
"type": "boolean",
"description": "Whether to consider linked images if provided",
"default": False,
},
"img": {
"type": "string",
"description": "Optional image path/URL",
},
"imgs": {
"type": "array",
"items": {"type": "string"},
"description": "Optional list of images",
},
},
"required": ["task"],
"additionalProperties": False,
}
def _medical_output_schema() -> dict:
return {
"type": "object",
"properties": {
"result": {"type": "string"},
"success": {"type": "boolean"},
"error": {"type": "string"},
"confidence": {
"type": "number",
"minimum": 0,
"maximum": 1,
"description": "Optional confidence in the assessment",
},
"codes": {
"type": "array",
"items": {"type": "string"},
"description": "Optional list of suggested ICD-10 codes",
},
},
"required": ["result", "success"],
"additionalProperties": True,
}
def main() -> None:
"""
Start an AOP MCP server that exposes the medical agents as tools with
structured schemas and per-agent settings.
"""
_enrich_agents_metadata()
deployer = AOP(
server_name="Medical-AOP-Server",
port=8000,
verbose=False,
traceback_enabled=True,
log_level="INFO",
transport="streamable-http",
)
input_schema = _medical_input_schema()
output_schema = _medical_output_schema()
# Register each agent with a modest, role-appropriate timeout
deployer.add_agent(
chief_medical_officer,
timeout=45,
input_schema=input_schema,
output_schema=output_schema,
)
deployer.add_agent(
virologist,
timeout=40,
input_schema=input_schema,
output_schema=output_schema,
)
deployer.add_agent(
internist,
timeout=40,
input_schema=input_schema,
output_schema=output_schema,
)
deployer.add_agent(
medical_coder,
timeout=50,
input_schema=input_schema,
output_schema=output_schema,
)
deployer.add_agent(
synthesizer,
timeout=45,
input_schema=input_schema,
output_schema=output_schema,
)
deployer.run()
if __name__ == "__main__":
main()

@ -0,0 +1,106 @@
from swarms import Agent
from swarms.structs.aop import (
AOP,
)
# Create specialized agents
research_agent = Agent(
agent_name="Research-Agent",
agent_description="Expert in research, data collection, and information gathering",
model_name="anthropic/claude-sonnet-4-5",
max_loops=1,
top_p=None,
dynamic_temperature_enabled=True,
system_prompt="""You are a research specialist. Your role is to:
1. Gather comprehensive information on any given topic
2. Analyze data from multiple sources
3. Provide well-structured research findings
4. Cite sources and maintain accuracy
5. Present findings in a clear, organized manner
Always provide detailed, factual information with proper context.""",
)
analysis_agent = Agent(
agent_name="Analysis-Agent",
agent_description="Expert in data analysis, pattern recognition, and generating insights",
model_name="anthropic/claude-sonnet-4-5",
max_loops=1,
top_p=None,
dynamic_temperature_enabled=True,
system_prompt="""You are an analysis specialist. Your role is to:
1. Analyze data and identify patterns
2. Generate actionable insights
3. Create visualizations and summaries
4. Provide statistical analysis
5. Make data-driven recommendations
Focus on extracting meaningful insights from information.""",
)
writing_agent = Agent(
agent_name="Writing-Agent",
agent_description="Expert in content creation, editing, and communication",
model_name="anthropic/claude-sonnet-4-5",
max_loops=1,
top_p=None,
dynamic_temperature_enabled=True,
system_prompt="""You are a writing specialist. Your role is to:
1. Create engaging, well-structured content
2. Edit and improve existing text
3. Adapt tone and style for different audiences
4. Ensure clarity and coherence
5. Follow best practices in writing
Always produce high-quality, professional content.""",
)
code_agent = Agent(
agent_name="Code-Agent",
agent_description="Expert in programming, code review, and software development",
model_name="anthropic/claude-sonnet-4-5",
max_loops=1,
top_p=None,
dynamic_temperature_enabled=True,
system_prompt="""You are a coding specialist. Your role is to:
1. Write clean, efficient code
2. Debug and fix issues
3. Review and optimize code
4. Explain programming concepts
5. Follow best practices and standards
Always provide working, well-documented code.""",
)
financial_agent = Agent(
agent_name="Financial-Agent",
agent_description="Expert in financial analysis, market research, and investment insights",
model_name="anthropic/claude-sonnet-4-5",
max_loops=1,
top_p=None,
dynamic_temperature_enabled=True,
system_prompt="""You are a financial specialist. Your role is to:
1. Analyze financial data and markets
2. Provide investment insights
3. Assess risk and opportunities
4. Create financial reports
5. Explain complex financial concepts
Always provide accurate, well-reasoned financial analysis.""",
)
# Basic usage - individual agent addition
deployer = AOP("MyAgentServer", verbose=True, port=5932)
agents = [
research_agent,
analysis_agent,
writing_agent,
code_agent,
financial_agent,
]
deployer.add_agents_batch(agents)
deployer.run()

@ -201,7 +201,7 @@ class ChartElement:
class VisionAPI:
def __init__(
self,
model_name: str = "gpt-4o",
model_name: str = "gpt-4.1",
max_tokens: int = 1000,
temperature: float = 0.5,
):
@ -246,7 +246,7 @@ class VisionAPI:
class ChartCitor:
def __init__(
self,
model_name: str = "gpt-4o",
model_name: str = "gpt-4.1",
saved_state_path: str = "chartcitor_state.json",
max_retries: int = 3,
max_loops: int = 1,

@ -29,7 +29,7 @@ Emphasize objective technical analysis without making direct price predictions.
technical_agent = Agent(
agent_name="Technical-Analyst",
system_prompt=TECHNICAL_ANALYST_PROMPT,
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
verbose=True,
dynamic_temperature_enabled=True,
@ -79,7 +79,7 @@ Focus on identifying both obvious and subtle risk factors.
risk_agent = Agent(
agent_name="Risk-Manager",
system_prompt=RISK_MANAGER_PROMPT,
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
verbose=True,
dynamic_temperature_enabled=True,
@ -108,7 +108,7 @@ Focus on identifying major market-moving factors and trends.
macro_agent = Agent(
agent_name="Macro-Analyst",
system_prompt=MACRO_ANALYST_PROMPT,
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
verbose=True,
dynamic_temperature_enabled=True,

@ -193,7 +193,7 @@ agent = Agent(
max_loops=1,
tools_list_dictionary=tools,
output_type="final",
model_name="gpt-4o",
model_name="gpt-4.1",
)

@ -1,6 +1,6 @@
from dotenv import load_dotenv
from swarms import Agent
from swarms.utils.function_caller_model import OpenAIFunctionCaller
from swarms.utils.litellm_wrapper import LiteLLM
from pydantic import BaseModel, Field
from swarms.structs.conversation import Conversation
@ -180,8 +180,9 @@ Maintain a warm, friendly, and authentic presence while ensuring all interaction
# Initialize Agents using swarms
########################################
model = OpenAIFunctionCaller(
base_model=CallLog,
model = LiteLLM(
model_name="gpt-4.1",
response_format=CallLog,
system_prompt=MASTER_AGENT_SYS_PROMPT,
)
@ -192,7 +193,7 @@ counselor_agent = Agent(
agent_description="Provides empathetic and effective college counseling and guidance.",
system_prompt=COUNSELOR_AGENT_SYS_PROMPT,
max_loops=1,
model_name="gpt-4o",
model_name="gpt-4.1",
dynamic_temperature_enabled=True,
)
@ -202,7 +203,7 @@ buddy_agent = Agent(
agent_description="Acts as a supportive, friendly companion to the student.",
system_prompt=BUDDY_AGENT_SYS_PROMPT,
max_loops=1,
model_name="gpt-4o",
model_name="gpt-4.1",
dynamic_temperature_enabled=True,
)

@ -45,7 +45,7 @@ chief_medical_officer = Agent(
""",
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
)
@ -69,7 +69,7 @@ virologist = Agent(
* Secondary condition codes
Document all findings using proper medical coding standards and include rationale for code selection.""",
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
)
@ -94,7 +94,7 @@ internist = Agent(
- Include hierarchical condition category (HCC) codes where applicable
Document supporting evidence for each code selected.""",
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
)
@ -125,7 +125,7 @@ medical_coder = Agent(
3. Symptom Codes
4. Complication Codes
5. Coding Notes""",
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
)
@ -153,7 +153,7 @@ synthesizer = Agent(
- Documentation improvements needed
Include confidence levels and evidence quality for all diagnoses and codes.""",
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
)

@ -27,7 +27,7 @@ chief_medical_officer = Agent(
- Differential Diagnoses
- Specialist Consultations Needed
- Recommended Next Steps""",
model_name="gpt-4o", # Models from litellm -> claude-2
model_name="gpt-4.1", # Models from litellm -> claude-2
max_loops=1,
)
@ -60,7 +60,7 @@ virologist = Agent(
- Disease progression timeline
- Risk factors for severe disease
- Potential complications""",
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
)
@ -91,7 +91,7 @@ internist = Agent(
- System-specific symptoms
- Relevant lab abnormalities
- Risk factors for complications""",
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
)
@ -127,7 +127,7 @@ synthesizer = Agent(
- Confidence levels for each diagnosis
- Knowledge gaps identified
- Risk assessment""",
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
)

@ -27,7 +27,7 @@ lead_analyst = Agent(
- Negotiation Points
- Recommended Actions
- Areas Requiring Specialist Review""",
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
)
@ -62,7 +62,7 @@ safe_specialist = Agent(
- Conversion mechanics explanation
- Risk assessment for non-standard terms
- Recommendations for negotiations""",
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
)
@ -103,7 +103,7 @@ term_sheet_analyst = Agent(
- Founder impact analysis
- Investor rights summary
- Governance implications""",
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
)
@ -144,7 +144,7 @@ legal_analyst = Agent(
- Required disclosures list
- Recommended legal modifications
- Jurisdiction-specific concerns""",
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
)
@ -184,7 +184,7 @@ market_analyst = Agent(
- Trend implications
- Negotiation leverage points
- Recommended modifications""",
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
)

@ -9,7 +9,7 @@ Todo
import os
from dotenv import load_dotenv
from swarms import Agent, AgentRearrange
from swarm_models import OpenAIChat, OpenAIFunctionCaller
from swarms.utils.litellm_wrapper import LiteLLM
from pydantic import BaseModel
from typing import List
@ -31,10 +31,8 @@ load_dotenv()
api_key = os.getenv("GROQ_API_KEY")
# Initialize the model
model = OpenAIChat(
openai_api_base="https://api.groq.com/openai/v1",
openai_api_key=api_key,
model_name="llama-3.1-70b-versatile",
model = LiteLLM(
model_name="groq/llama-3.1-70b-versatile",
temperature=0.1,
)
@ -52,11 +50,11 @@ You are a college selection final decision maker. Your role is to:
"""
function_caller = OpenAIFunctionCaller(
function_caller = LiteLLM(
model_name="gpt-4.1",
system_prompt=FINAL_AGENT_PROMPT,
openai_api_key=os.getenv("OPENAI_API_KEY"),
base_model=CollegesRecommendation,
parallel_tool_calls=True,
response_format=CollegesRecommendation,
temperature=0.1,
)
# Student Profile Analyzer Agent

@ -8,7 +8,7 @@ Todo
import os
from dotenv import load_dotenv
from swarm_models import OpenAIChat, OpenAIFunctionCaller
from swarms.utils.litellm_wrapper import LiteLLM
from pydantic import BaseModel
from typing import List
@ -30,21 +30,19 @@ load_dotenv()
api_key = os.getenv("GROQ_API_KEY")
# Initialize the model
model = OpenAIChat(
openai_api_base="https://api.groq.com/openai/v1",
openai_api_key=api_key,
model_name="llama-3.1-70b-versatile",
model = LiteLLM(
model_name="groq/llama-3.1-70b-versatile",
temperature=0.1,
)
function_caller = OpenAIFunctionCaller(
function_caller = LiteLLM(
model_name="gpt-4.1",
system_prompt="""You are a college selection final decision maker. Your role is to:
- Balance all relevant factors and stakeholder input.
- Only return the output in the schema format.
""",
openai_api_key=os.getenv("OPENAI_API_KEY"),
base_model=CollegesRecommendation,
# parallel_tool_calls=True,
response_format=CollegesRecommendation,
temperature=0.1,
)

@ -9,7 +9,7 @@ Todo
import os
from dotenv import load_dotenv
from swarms import Agent, SequentialWorkflow
from swarm_models import OpenAIChat, OpenAIFunctionCaller
from swarms.utils.litellm_wrapper import LiteLLM
from pydantic import BaseModel
from typing import List
@ -31,10 +31,8 @@ load_dotenv()
api_key = os.getenv("GROQ_API_KEY")
# Initialize the model
model = OpenAIChat(
openai_api_base="https://api.groq.com/openai/v1",
openai_api_key=api_key,
model_name="llama-3.1-70b-versatile",
model = LiteLLM(
model_name="groq/llama-3.1-70b-versatile",
temperature=0.1,
)
@ -52,11 +50,11 @@ You are a college selection final decision maker. Your role is to:
"""
function_caller = OpenAIFunctionCaller(
function_caller = LiteLLM(
model_name="gpt-4.1",
system_prompt=FINAL_AGENT_PROMPT,
openai_api_key=os.getenv("OPENAI_API_KEY"),
base_model=CollegesRecommendation,
parallel_tool_calls=True,
response_format=CollegesRecommendation,
temperature=0.1,
)
# Student Profile Analyzer Agent

@ -0,0 +1,73 @@
from swarms import Agent, AgentRearrange
# Create specialized quantitative research agents
weather_data_agent = Agent(
agent_name="Weather-Data-Agent",
agent_description="Expert in weather data collection, agricultural commodity research, and meteorological analysis",
model_name="claude-sonnet-4-20250514",
max_loops=1,
system_prompt="""You are a quantitative weather data research specialist. Your role is to:
1. Collect and analyze weather data from multiple sources (NOAA, Weather APIs, satellite data)
2. Research agricultural commodity markets and their weather dependencies
3. Identify weather patterns that historically impact crop yields and commodity prices
4. Gather data on seasonal weather trends, precipitation patterns, temperature anomalies
5. Research specific regions and their agricultural production cycles
6. Collect data on extreme weather events and their market impact
7. Analyze historical correlations between weather data and commodity price movements
Focus on actionable weather intelligence for trading opportunities. Always provide specific data points,
timeframes, and geographic regions. Include confidence levels and data quality assessments.""",
)
quant_analysis_agent = Agent(
agent_name="Quant-Analysis-Agent",
agent_description="Expert in quantitative analysis of weather patterns, arbitrage opportunities, and statistical modeling",
model_name="claude-sonnet-4-20250514",
max_loops=1,
system_prompt="""You are a quantitative analysis specialist focused on weather-driven arbitrage opportunities. Your role is to:
1. Analyze weather data correlations with commodity price movements
2. Identify statistical arbitrage opportunities in agricultural futures markets
3. Calculate risk-adjusted returns for weather-based trading strategies
4. Model price impact scenarios based on weather forecasts
5. Identify seasonal patterns and mean reversion opportunities
6. Analyze basis risk and correlation breakdowns between weather and prices
7. Calculate optimal position sizes and hedging ratios
8. Assess market inefficiencies in weather-sensitive commodities
Focus on actionable trading signals with specific entry/exit criteria, risk metrics, and expected returns.
Always provide quantitative justification and statistical confidence levels.""",
)
trading_strategy_agent = Agent(
agent_name="Trading-Strategy-Agent",
agent_description="Expert in trading strategy development, risk assessment, and portfolio management for weather-driven arbitrage",
model_name="claude-sonnet-4-20250514",
max_loops=1,
system_prompt="""You are a quantitative trading strategy specialist focused on weather-driven arbitrage opportunities. Your role is to:
1. Develop comprehensive trading strategies based on weather data and commodity analysis
2. Create detailed risk management frameworks for weather-sensitive positions
3. Design portfolio allocation strategies for agricultural commodity arbitrage
4. Develop hedging strategies to mitigate weather-related risks
5. Create position sizing models based on volatility and correlation analysis
6. Design entry and exit criteria for weather-based trades
7. Develop contingency plans for unexpected weather events
8. Create performance monitoring and evaluation frameworks
Focus on practical, implementable trading strategies with clear risk parameters,
position management rules, and performance metrics. Always include specific trade setups,
risk limits, and monitoring protocols.""",
)
rearrange_system = AgentRearrange(
agents=[
weather_data_agent,
quant_analysis_agent,
trading_strategy_agent,
],
flow=f"{trading_strategy_agent.agent_name} -> {quant_analysis_agent.agent_name}, {weather_data_agent.agent_name}",
max_loops=1,
)
rearrange_system.run(
"What are the best weather trades for the rest of the year 2025? Can we short wheat futures, corn futures, soybean futures, etc.?"
)

@ -0,0 +1,17 @@
import json
from swarms import AutoSwarmBuilder
swarm = AutoSwarmBuilder(
name="My Swarm",
description="A swarm of agents",
verbose=True,
max_loops=1,
model_name="gpt-4o-mini",
execution_type="return-agents",
)
out = swarm.run(
task="Create an accounting team to analyze crypto transactions, there must be 5 agents in the team with extremely extensive prompts. Make the prompts extremely detailed and specific and long and comprehensive. Make sure to include all the details of the task in the prompts."
)
print(json.dumps(out, indent=4))

@ -0,0 +1,19 @@
from swarms import Agent
# Initialize the agent
agent = Agent(
agent_name="Quantitative-Trading-Agent",
agent_description="Advanced quantitative trading and algorithmic analysis agent",
model_name="claude-sonnet-4-2025051eqfewfwmfkmekef",
dynamic_temperature_enabled=True,
max_loops=1,
dynamic_context_window=True,
streaming_on=True,
fallback_models=["gpt-4o-mini", "anthropic/claude-sonnet-4-5"],
)
out = agent.run(
task="What are the top five best energy stocks across nuclear, solar, gas, and other energy sources?",
)
print(out)

@ -0,0 +1,106 @@
from swarms import Agent
from swarms.structs.aop import (
AOP,
)
# Create specialized agents
research_agent = Agent(
agent_name="Research-Agent",
agent_description="Expert in research, data collection, and information gathering",
model_name="anthropic/claude-sonnet-4-5",
max_loops=1,
top_p=None,
dynamic_temperature_enabled=True,
system_prompt="""You are a research specialist. Your role is to:
1. Gather comprehensive information on any given topic
2. Analyze data from multiple sources
3. Provide well-structured research findings
4. Cite sources and maintain accuracy
5. Present findings in a clear, organized manner
Always provide detailed, factual information with proper context.""",
)
analysis_agent = Agent(
agent_name="Analysis-Agent",
agent_description="Expert in data analysis, pattern recognition, and generating insights",
model_name="anthropic/claude-sonnet-4-5",
max_loops=1,
top_p=None,
dynamic_temperature_enabled=True,
system_prompt="""You are an analysis specialist. Your role is to:
1. Analyze data and identify patterns
2. Generate actionable insights
3. Create visualizations and summaries
4. Provide statistical analysis
5. Make data-driven recommendations
Focus on extracting meaningful insights from information.""",
)
writing_agent = Agent(
agent_name="Writing-Agent",
agent_description="Expert in content creation, editing, and communication",
model_name="anthropic/claude-sonnet-4-5",
max_loops=1,
top_p=None,
dynamic_temperature_enabled=True,
system_prompt="""You are a writing specialist. Your role is to:
1. Create engaging, well-structured content
2. Edit and improve existing text
3. Adapt tone and style for different audiences
4. Ensure clarity and coherence
5. Follow best practices in writing
Always produce high-quality, professional content.""",
)
code_agent = Agent(
agent_name="Code-Agent",
agent_description="Expert in programming, code review, and software development",
model_name="anthropic/claude-sonnet-4-5",
max_loops=1,
top_p=None,
dynamic_temperature_enabled=True,
system_prompt="""You are a coding specialist. Your role is to:
1. Write clean, efficient code
2. Debug and fix issues
3. Review and optimize code
4. Explain programming concepts
5. Follow best practices and standards
Always provide working, well-documented code.""",
)
financial_agent = Agent(
agent_name="Financial-Agent",
agent_description="Expert in financial analysis, market research, and investment insights",
model_name="anthropic/claude-sonnet-4-5",
max_loops=1,
top_p=None,
dynamic_temperature_enabled=True,
system_prompt="""You are a financial specialist. Your role is to:
1. Analyze financial data and markets
2. Provide investment insights
3. Assess risk and opportunities
4. Create financial reports
5. Explain complex financial concepts
Always provide accurate, well-reasoned financial analysis.""",
)
# Basic usage - individual agent addition
deployer = AOP("MyAgentServer", verbose=True, port=5932)
agents = [
research_agent,
analysis_agent,
writing_agent,
code_agent,
financial_agent,
]
deployer.add_agents_batch(agents)
deployer.run()

@ -1,9 +0,0 @@
from swarms.structs.agent_builder import AgentsBuilder
example_task = "Write a blog post about the benefits of using Swarms for AI agents."
agents_builder = AgentsBuilder()
agents = agents_builder.run(example_task)
print(agents)

@ -1,11 +1,10 @@
import json
import os
from contextlib import suppress
from typing import Any, Callable, Dict, Optional, Type, Union
from dotenv import load_dotenv
from pydantic import BaseModel, Field, ValidationError, create_model
from swarm_models.openai_function_caller import OpenAIFunctionCaller
from swarms.utils.litellm_wrapper import LiteLLM
class DynamicParser:
@ -216,14 +215,13 @@ Your role is to make decisions and complete tasks independently without seeking
Always respond in a strict JSON format as described below. Ensure your responses can be parsed with Python's `json.loads`:
"""
# Initialize the OpenAIFunctionCaller
model = OpenAIFunctionCaller(
# Initialize the LiteLLM
model = LiteLLM(
model_name="gpt-4.1",
system_prompt=SYSTEM_PROMPT,
max_tokens=4000,
temperature=0.9,
base_model=AgentResponse, # Pass the Pydantic schema as the base model
parallel_tool_calls=False,
openai_api_key=os.getenv("OPENAI_API_KEY"),
response_format=AgentResponse, # Pass the Pydantic schema as the response format
)
# Example usage

@ -21,7 +21,7 @@ delaware_ccorp_agent = Agent(
corporate law and ensure that all hiring practices are in compliance with
state and federal regulations.
""",
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
)
@ -41,7 +41,7 @@ indian_foreign_agent = Agent(
implications of hiring foreign nationals and the requirements for obtaining
necessary visas and work permits.
""",
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
)

@ -9,7 +9,7 @@ if __name__ == "__main__":
Agent(
agent_name=f"Financial-Analysis-Agent-{i}",
system_prompt=FINANCIAL_AGENT_SYS_PROMPT,
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
)
for i in range(3) # Adjust number of agents as needed

@ -9,7 +9,7 @@ equity_analyst_1 = Agent(
agent_description="Equity research analyst focused on fundamental analysis",
system_prompt=FINANCIAL_AGENT_SYS_PROMPT,
max_loops=1,
model_name="gpt-4o",
model_name="gpt-4.1",
dynamic_temperature_enabled=True,
user_name="swarms_corp",
retry_attempts=3,
@ -28,7 +28,7 @@ equity_analyst_2 = Agent(
agent_description="Equity research analyst focused on technical analysis",
system_prompt=FINANCIAL_AGENT_SYS_PROMPT,
max_loops=1,
model_name="gpt-4o",
model_name="gpt-4.1",
dynamic_temperature_enabled=True,
user_name="swarms_corp",
retry_attempts=3,

@ -21,28 +21,28 @@ def create_financial_services_forest():
budgeting, debt management, and financial goal setting. I help individuals create
comprehensive financial plans and make informed decisions about their money.""",
agent_name="Personal Financial Planner",
model_name="gpt-4o",
model_name="gpt-4.1",
),
TreeAgent(
system_prompt="""I am a tax preparation specialist with expertise in individual and
small business tax returns. I help clients maximize deductions, understand tax laws,
and file taxes accurately and on time.""",
agent_name="Tax Preparation Specialist",
model_name="gpt-4o",
model_name="gpt-4.1",
),
TreeAgent(
system_prompt="""I am a retirement planning expert who helps individuals and families
plan for retirement. I specialize in 401(k)s, IRAs, Social Security optimization,
and creating sustainable retirement income strategies.""",
agent_name="Retirement Planning Expert",
model_name="gpt-4o",
model_name="gpt-4.1",
),
TreeAgent(
system_prompt="""I am a debt management counselor who helps individuals and families
get out of debt and build financial stability. I provide strategies for debt
consolidation, negotiation, and creating sustainable repayment plans.""",
agent_name="Debt Management Counselor",
model_name="gpt-4o",
model_name="gpt-4.1",
),
]
@ -54,28 +54,28 @@ def create_financial_services_forest():
fundamentals, market conditions, and economic indicators to help investors make
informed decisions.""",
agent_name="Stock Market Analyst",
model_name="gpt-4o",
model_name="gpt-4.1",
),
TreeAgent(
system_prompt="""I am an investment strategist specializing in portfolio diversification,
risk management, and asset allocation. I help investors create balanced portfolios
that align with their risk tolerance and financial goals.""",
agent_name="Investment Strategist",
model_name="gpt-4o",
model_name="gpt-4.1",
),
TreeAgent(
system_prompt="""I am a cryptocurrency and blockchain expert who provides insights on
digital assets, DeFi protocols, and emerging blockchain technologies. I help
investors understand the risks and opportunities in the crypto market.""",
agent_name="Cryptocurrency Expert",
model_name="gpt-4o",
model_name="gpt-4.1",
),
TreeAgent(
system_prompt="""I am a real estate investment advisor who helps investors evaluate
real estate opportunities, understand market trends, and build real estate
portfolios for long-term wealth building.""",
agent_name="Real Estate Investment Advisor",
model_name="gpt-4o",
model_name="gpt-4.1",
),
]
@ -86,14 +86,14 @@ def create_financial_services_forest():
business valuation, mergers and acquisitions, and strategic financial planning
for small to medium-sized businesses.""",
agent_name="Business Financial Advisor",
model_name="gpt-4o",
model_name="gpt-4.1",
),
TreeAgent(
system_prompt="""I am a Delaware incorporation specialist with deep knowledge of
corporate formation, tax benefits, legal requirements, and ongoing compliance
for businesses incorporating in Delaware.""",
agent_name="Delaware Incorporation Specialist",
model_name="gpt-4o",
model_name="gpt-4.1",
),
TreeAgent(
system_prompt="""I am a startup funding advisor who helps entrepreneurs secure
@ -101,14 +101,14 @@ def create_financial_services_forest():
financing options. I provide guidance on business plans, pitch decks, and
investor relations.""",
agent_name="Startup Funding Advisor",
model_name="gpt-4o",
model_name="gpt-4.1",
),
TreeAgent(
system_prompt="""I am a business tax strategist who helps businesses optimize their
tax position through strategic planning, entity structure optimization, and
compliance with federal, state, and local tax laws.""",
agent_name="Business Tax Strategist",
model_name="gpt-4o",
model_name="gpt-4.1",
),
]

@ -1,4 +1,3 @@
import os
from dotenv import load_dotenv
# Swarm imports
@ -7,7 +6,7 @@ from swarms.structs.hiearchical_swarm import (
HierarchicalSwarm,
SwarmSpec,
)
from swarms.utils.function_caller_model import OpenAIFunctionCaller
from swarms.utils.litellm_wrapper import LiteLLM
load_dotenv()
@ -15,9 +14,9 @@ load_dotenv()
# ------------------------------------------------------------------------------
# Director LLM: Responsible for orchestrating tasks among the agents
# ------------------------------------------------------------------------------
llm = OpenAIFunctionCaller(
base_model=SwarmSpec,
api_key=os.getenv("OPENAI_API_KEY"),
llm = LiteLLM(
model_name="gpt-4.1",
response_format=SwarmSpec,
system_prompt=(
"As the Director of this Hierarchical Agent Swarm, you are in charge of "
"coordinating and overseeing all tasks, ensuring that each is executed "
@ -57,7 +56,7 @@ def main():
# --------------------------------------------------------------------------
analysis_agent = Agent(
agent_name="Stock-Analysis-Agent",
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
interactive=False,
streaming_on=False,

@ -1,4 +1,3 @@
import os
from dotenv import load_dotenv
# Swarm imports
@ -7,16 +6,16 @@ from swarms.structs.hiearchical_swarm import (
HierarchicalSwarm,
SwarmSpec,
)
from swarms.utils.function_caller_model import OpenAIFunctionCaller
from swarms.utils.litellm_wrapper import LiteLLM
load_dotenv()
# ------------------------------------------------------------------------------
# Trading Director: Responsible for orchestrating tasks among multiple stock analysts
# ------------------------------------------------------------------------------
director_llm = OpenAIFunctionCaller(
base_model=SwarmSpec,
api_key=os.getenv("OPENAI_API_KEY"),
director_llm = LiteLLM(
model_name="gpt-4.1",
response_format=SwarmSpec,
system_prompt=(
"You are the Trading Director in charge of coordinating a team of specialized "
"Stock Analysts. Your responsibilities include:\n\n"
@ -51,7 +50,7 @@ def main():
# --------------------------------------------------------------------------
macro_agent = Agent(
agent_name="Macro-Economic-Analysis-Agent",
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
interactive=False,
streaming_on=False,
@ -81,7 +80,7 @@ def main():
# --------------------------------------------------------------------------
sector_agent = Agent(
agent_name="Sector-Performance-Analysis-Agent",
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
interactive=False,
streaming_on=False,
@ -113,7 +112,7 @@ def main():
# --------------------------------------------------------------------------
technical_agent = Agent(
agent_name="Technical-Analysis-Agent",
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
interactive=False,
streaming_on=False,
@ -145,7 +144,7 @@ def main():
# --------------------------------------------------------------------------
risk_agent = Agent(
agent_name="Risk-Analysis-Agent",
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
interactive=False,
streaming_on=False,

@ -97,7 +97,7 @@ technical_agent = Agent(
agent_description="Specialized in technical analysis, chart patterns, and trading signals",
system_prompt=TECHNICAL_ANALYSIS_PROMPT,
max_loops=1,
model_name="gpt-4o",
model_name="gpt-4.1",
)
fundamental_agent = Agent(
@ -105,7 +105,7 @@ fundamental_agent = Agent(
agent_description="Specialized in financial statement analysis and company valuation",
system_prompt=FUNDAMENTAL_ANALYSIS_PROMPT,
max_loops=1,
model_name="gpt-4o",
model_name="gpt-4.1",
)
risk_agent = Agent(
@ -113,7 +113,7 @@ risk_agent = Agent(
agent_description="Specialized in portfolio optimization and risk management strategies",
system_prompt=RISK_MANAGEMENT_PROMPT,
max_loops=1,
model_name="gpt-4o",
model_name="gpt-4.1",
)
# Create the majority voting swarm with the three specialized quant agents

@ -14,7 +14,7 @@ agent = Agent(
agent_description="Personal finance advisor agent",
system_prompt=FINANCIAL_AGENT_SYS_PROMPT,
max_loops=1,
model_name="gpt-4o",
model_name="gpt-4.1",
dynamic_temperature_enabled=True,
user_name="swarms_corp",
retry_attempts=3,

@ -72,7 +72,7 @@ def create_code_agents():
agent_name="Python-Code-Expert",
agent_description="Senior Python developer specializing in clean, efficient code",
system_prompt=PYTHON_EXPERT_PROMPT,
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
max_tokens=4000,
temperature=0.7,
@ -84,7 +84,7 @@ def create_code_agents():
agent_name="Game-Dev-Specialist",
agent_description="Game development expert focusing on mechanics and user experience",
system_prompt=GAME_DEV_EXPERT_PROMPT,
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
max_tokens=4000,
temperature=0.7,
@ -100,7 +100,7 @@ def create_consensus_agent():
agent_name="Code-Quality-Evaluator",
agent_description="Senior code reviewer evaluating implementations across multiple criteria",
system_prompt=CONSENSUS_EVALUATOR_PROMPT,
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
max_tokens=5000,
temperature=0.3, # Lower temperature for more consistent evaluation

@ -1,45 +1,11 @@
#!/usr/bin/env python3
"""
Demo script for the Agent Map Simulation.
This script demonstrates how to set up and run a simulation where multiple AI agents
move around a 2D map and automatically engage in conversations when they come into
proximity with each other.
NEW: Task-based simulation support! You can now specify what the agents should discuss:
# Create simulation
simulation = AgentMapSimulation(map_width=50, map_height=50)
# Add your agents
simulation.add_agent(my_agent1)
simulation.add_agent(my_agent2)
# Run with a specific task
results = simulation.run(
task="Discuss the impact of AI on financial markets",
duration=300, # 5 minutes
with_visualization=True
)
Features demonstrated:
- Creating agents with different specializations
- Setting up the simulation environment
- Running task-focused conversations
- Live visualization
- Monitoring conversation activity
- Saving conversation summaries
Run this script to see agents moving around and discussing specific topics!
"""
import time
from typing import List
from swarms import Agent
# Remove the formal collaboration prompt import
from simulations.agent_map_simulation import AgentMapSimulation
from examples.multi_agent.simulations.agent_map.agent_map_simulation import (
AgentMapSimulation,
)
# Create a natural conversation prompt for the simulation
NATURAL_CONVERSATION_PROMPT = """

@ -7,8 +7,12 @@ what topic the agents should discuss when they meet.
"""
from swarms import Agent
from simulations.agent_map_simulation import AgentMapSimulation
from simulations.v0.demo_simulation import NATURAL_CONVERSATION_PROMPT
from examples.multi_agent.simulations.agent_map.agent_map_simulation import (
AgentMapSimulation,
)
from examples.multi_agent.simulations.agent_map.v0.demo_simulation import (
NATURAL_CONVERSATION_PROMPT,
)
def create_simple_agent(name: str, expertise: str) -> Agent:

@ -19,7 +19,9 @@ CASE: 34-year-old female with sudden severe headache
from typing import List
from swarms import Agent
from simulations.agent_map_simulation import AgentMapSimulation
from examples.multi_agent.simulations.agent_map.agent_map_simulation import (
AgentMapSimulation,
)
def create_medical_agent(

@ -13,7 +13,7 @@ Run this to see agents naturally forming groups and having multi-party conversat
from swarms import Agent
from simulations.agent_map_simulation import (
from examples.multi_agent.simulations.agent_map.agent_map_simulation import (
AgentMapSimulation,
Position,
)

@ -8,7 +8,7 @@ that all components work correctly without requiring a GUI.
import time
from swarms import Agent
from simulations.agent_map_simulation import (
from examples.multi_agent.simulations.agent_map.agent_map_simulation import (
AgentMapSimulation,
Position,
)

@ -0,0 +1,28 @@
from swarms import Agent, SequentialWorkflow
# Agent 1: The Researcher
researcher = Agent(
agent_name="Researcher",
system_prompt="Your job is to research the provided topic and provide a detailed summary.",
model_name="anthropic/claude-sonnet-4-5",
top_p=None,
dynamic_temperature_enabled=True,
)
# Agent 2: The Writer
writer = Agent(
agent_name="Writer",
system_prompt="Your job is to take the research summary and write a beautiful, engaging blog post about it.",
model_name="anthropic/claude-sonnet-4-5",
top_p=None,
dynamic_temperature_enabled=True,
)
# Create a sequential workflow where the researcher's output feeds into the writer's input
workflow = SequentialWorkflow(agents=[researcher, writer])
# Run the workflow on a task
final_post = workflow.run(
"Create a comprehensive and detailed report on Gold ETFs"
)
print(final_post)

@ -6,8 +6,8 @@ router = SwarmRouter(
max_loops=1,
swarm_type="HeavySwarm",
heavy_swarm_loops_per_agent=1,
heavy_swarm_question_agent_model_name="gpt-4o",
heavy_swarm_worker_model_name="gpt-4o",
heavy_swarm_question_agent_model_name="gpt-4.1",
heavy_swarm_worker_model_name="gpt-4.1",
)
router.run("What are the best ETFs for the american energy markets?")

@ -6,19 +6,19 @@ agents = [
agent_name="test_agent_1",
agent_description="test_agent_1_description",
system_prompt="test_agent_1_system_prompt",
model_name="gpt-4o",
model_name="gpt-4.1",
),
Agent(
agent_name="test_agent_2",
agent_description="test_agent_2_description",
system_prompt="test_agent_2_system_prompt",
model_name="gpt-4o",
model_name="gpt-4.1",
),
Agent(
agent_name="test_agent_3",
agent_description="test_agent_3_description",
system_prompt="test_agent_3_system_prompt",
model_name="gpt-4o",
model_name="gpt-4.1",
),
]

@ -19,7 +19,7 @@ portfolio_analyzer = Agent(
6. Review fund manager track record and strategy consistency
Maintain focus on cost-efficiency and alignment with investment objectives.""",
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
saved_state_path="portfolio_analyzer.json",
user_name="investment_team",
@ -47,7 +47,7 @@ allocation_strategist = Agent(
6. Account for correlation between assets
Focus on creating well-diversified portfolios aligned with client goals and risk tolerance.""",
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
saved_state_path="allocation_strategist.json",
user_name="investment_team",
@ -75,7 +75,7 @@ risk_manager = Agent(
6. Monitor factor exposures
Focus on maintaining appropriate risk levels while maximizing risk-adjusted returns.""",
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
saved_state_path="risk_manager.json",
user_name="investment_team",
@ -103,7 +103,7 @@ implementation_specialist = Agent(
6. Monitor tracking error
Maintain focus on minimizing costs and maximizing tax efficiency during implementation.""",
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
saved_state_path="implementation_specialist.json",
user_name="investment_team",
@ -131,7 +131,7 @@ monitoring_specialist = Agent(
6. Generate performance attribution reports
Ensure continuous alignment with investment objectives while maintaining optimal portfolio efficiency.""",
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
saved_state_path="monitoring_specialist.json",
user_name="investment_team",

@ -7,42 +7,42 @@ 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",
model_name="gpt-4.1",
)
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",
model_name="gpt-4.1",
)
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",
model_name="gpt-4.1",
)
development_manager = Agent(
agent_name="Development Manager",
agent_description="Manages development projects and coordinates development tasks",
system_prompt="You are a development manager responsible for overseeing software development projects and coordinating development efforts.",
model_name="gpt-4o",
model_name="gpt-4.1",
)
software_engineer = Agent(
agent_name="Software Engineer",
agent_description="Develops and implements software solutions",
system_prompt="You are a software engineer specializing in building and implementing software solutions.",
model_name="gpt-4o",
model_name="gpt-4.1",
)
qa_engineer = Agent(
agent_name="QA Engineer",
agent_description="Tests and ensures quality of software",
system_prompt="You are a QA engineer responsible for testing software and ensuring its quality.",
model_name="gpt-4o",
model_name="gpt-4.1",
)
swarm_router = SwarmRouter(

@ -41,7 +41,7 @@ def run_single_swarm():
"agent_name": "Risk Assessment Agent",
"description": "Evaluates risks in investment strategies.",
"system_prompt": "You are a risk assessment expert in cryptocurrency. Identify and evaluate risks related to investment strategies, including market and credit risks. Provide a risk analysis report with assessments and mitigation strategies.",
"model_name": "gpt-4o",
"model_name": "gpt-4.1",
"role": "worker",
"max_loops": 1,
"max_tokens": 8192,
@ -50,7 +50,7 @@ def run_single_swarm():
"agent_name": "Portfolio Manager",
"description": "Manages and optimizes investment portfolios.",
"system_prompt": "You are a portfolio manager for a crypto hedge fund. Optimize asset allocation based on market conditions. Analyze existing assets, suggest adjustments, and provide diversification strategies.",
"model_name": "gpt-4o",
"model_name": "gpt-4.1",
"role": "worker",
"max_loops": 1,
"max_tokens": 8192,
@ -59,7 +59,7 @@ def run_single_swarm():
"agent_name": "Market Sentiment Analyst",
"description": "Analyzes market sentiment for trading strategies.",
"system_prompt": "You are a market sentiment analyst in cryptocurrency. Assess current sentiment by analyzing news and social media. Provide insights on how sentiment impacts investment decisions and summarize key indicators.",
"model_name": "gpt-4o",
"model_name": "gpt-4.1",
"role": "worker",
"max_loops": 1,
"max_tokens": 8192,

@ -12,7 +12,7 @@ agents = [
description="Conducts medical research and analysis",
system_prompt="You are a medical researcher specializing in clinical studies.",
max_loops=1,
model_name="gpt-4o",
model_name="gpt-4.1",
role="worker",
),
AgentInput(
@ -20,7 +20,7 @@ agents = [
description="Provides medical diagnoses based on symptoms and test results",
system_prompt="You are a medical diagnostician with expertise in identifying diseases.",
max_loops=1,
model_name="gpt-4o",
model_name="gpt-4.1",
role="worker",
),
AgentInput(
@ -28,7 +28,7 @@ agents = [
description="Advises on pharmaceutical treatments and drug interactions",
system_prompt="You are a pharmaceutical expert knowledgeable about medications and their effects.",
max_loops=1,
model_name="gpt-4o",
model_name="gpt-4.1",
role="worker",
),
]

@ -20,7 +20,7 @@ agent = Agent(
agent_description="The funniest, most optimistic agent around who sees every problem as a building project.",
system_prompt=BOB_THE_BUILDER_SYS_PROMPT,
max_loops=1,
model_name="gpt-4o",
model_name="gpt-4.1",
dynamic_temperature_enabled=True,
user_name="swarms_corp",
retry_attempts=3,

@ -1,122 +0,0 @@
"""
Example demonstrating the use of uvloop for running multiple agents concurrently.
This example shows how to use the new uvloop-based functions:
- run_agents_concurrently_uvloop: For running multiple agents with the same task
- run_agents_with_tasks_uvloop: For running agents with different tasks
uvloop provides significant performance improvements over standard asyncio,
especially for I/O-bound operations and concurrent task execution.
"""
import os
from swarms.structs.multi_agent_exec import (
run_agents_concurrently_uvloop,
run_agents_with_tasks_uvloop,
)
from swarms.structs.agent import Agent
def create_example_agents(num_agents: int = 3):
"""Create example agents for demonstration."""
agents = []
for i in range(num_agents):
agent = Agent(
agent_name=f"Agent_{i+1}",
system_prompt=f"You are Agent {i+1}, a helpful AI assistant.",
model_name="gpt-4o-mini", # Using a lightweight model for examples
max_loops=1,
autosave=False,
verbose=False,
)
agents.append(agent)
return agents
def example_same_task():
"""Example: Running multiple agents with the same task using uvloop."""
print("=== Example 1: Same Task for All Agents (uvloop) ===")
agents = create_example_agents(3)
task = (
"Write a one-sentence summary about artificial intelligence."
)
print(f"Running {len(agents)} agents with the same task...")
print(f"Task: {task}")
try:
results = run_agents_concurrently_uvloop(agents, task)
print("\nResults:")
for i, result in enumerate(results, 1):
print(f"Agent {i}: {result}")
except Exception as e:
print(f"Error: {e}")
def example_different_tasks():
"""Example: Running agents with different tasks using uvloop."""
print(
"\n=== Example 2: Different Tasks for Each Agent (uvloop) ==="
)
agents = create_example_agents(3)
tasks = [
"Explain what machine learning is in simple terms.",
"Describe the benefits of cloud computing.",
"What are the main challenges in natural language processing?",
]
print(f"Running {len(agents)} agents with different tasks...")
try:
results = run_agents_with_tasks_uvloop(agents, tasks)
print("\nResults:")
for i, (result, task) in enumerate(zip(results, tasks), 1):
print(f"Agent {i} (Task: {task[:50]}...):")
print(f" Response: {result}")
print()
except Exception as e:
print(f"Error: {e}")
def performance_comparison():
"""Demonstrate the performance benefit of uvloop vs standard asyncio."""
print("\n=== Performance Comparison ===")
# Note: This is a conceptual example. In practice, you'd need to measure actual performance
print("uvloop vs Standard asyncio:")
print("• uvloop: Cython-based event loop, ~2-4x faster")
print("• Better for I/O-bound operations")
print("• Lower latency and higher throughput")
print("• Especially beneficial for concurrent agent execution")
print("• Automatic fallback to asyncio if uvloop unavailable")
if __name__ == "__main__":
# Check if API key is available
if not os.getenv("OPENAI_API_KEY"):
print(
"Please set your OPENAI_API_KEY environment variable to run this example."
)
print("Example: export OPENAI_API_KEY='your-api-key-here'")
exit(1)
print("🚀 uvloop Multi-Agent Execution Examples")
print("=" * 50)
# Run examples
example_same_task()
example_different_tasks()
performance_comparison()
print("\n✅ Examples completed!")
print("\nTo use uvloop functions in your code:")
print(
"from swarms.structs.multi_agent_exec import run_agents_concurrently_uvloop"
)
print("results = run_agents_concurrently_uvloop(agents, task)")

@ -0,0 +1,30 @@
from swarms.structs.agent import Agent
from swarms.structs.multi_agent_exec import (
run_agents_concurrently_uvloop,
)
def create_example_agents(num_agents: int = 3):
"""Create example agents for demonstration."""
agents = []
for i in range(num_agents):
agent = Agent(
agent_name=f"Agent_{i+1}",
system_prompt=f"You are Agent {i+1}, a helpful AI assistant.",
model_name="gpt-4o-mini", # Using a lightweight model for examples
max_loops=1,
autosave=False,
verbose=False,
)
agents.append(agent)
return agents
agents = create_example_agents(3)
task = "Write a one-sentence summary about artificial intelligence."
results = run_agents_concurrently_uvloop(agents, task)
print(results)

@ -87,7 +87,7 @@ for doc in documents:
agent = Agent(
agent_name="RAG-Agent",
agent_description="Agent with Qdrant-powered RAG for enhanced knowledge retrieval",
model_name="gpt-4o",
model_name="gpt-4.1",
max_loops=1,
dynamic_temperature_enabled=True,
long_term_memory=rag_db,

@ -136,7 +136,7 @@ action_agent = Agent(
agent_description="Practical implementation and execution agent",
system_prompt=ACTION_AGENT_PROMPT,
max_loops=1,
model_name="gpt-4o",
model_name="gpt-4.1",
dynamic_temperature_enabled=True,
)

@ -40,7 +40,7 @@ tool_schema = BaseTool(
tool_schema = tool_schema["functions"][0]
llm = LiteLLM(
model_name="gpt-4o",
model_name="gpt-4.1",
)
print(

@ -270,7 +270,7 @@ print(test)
# tools=[generate_modalities],
# system_prompt=self.system_prompt,
# max_loops=1,
# model_name="gpt-4o",
# model_name="gpt-4.1",
# )
# def run(self, task: str):

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save