commit
5ef2788d85
@ -0,0 +1,279 @@
|
||||
# Fallback Models in Swarms Agent
|
||||
|
||||
The Swarms Agent now supports automatic fallback to alternative models when the primary model fails. This feature enhances reliability and ensures your agents can continue operating even when specific models are unavailable or experiencing issues.
|
||||
|
||||
## Overview
|
||||
|
||||
The fallback model system allows you to specify one or more alternative models that will be automatically tried if the primary model encounters an error. This is particularly useful for:
|
||||
|
||||
- **High availability**: Ensure your agents continue working even if a specific model is down
|
||||
- **Cost optimization**: Use cheaper models as fallbacks for non-critical tasks
|
||||
- **Rate limiting**: Switch to alternative models when hitting rate limits
|
||||
- **Model-specific issues**: Handle temporary model-specific problems
|
||||
|
||||
## Configuration
|
||||
|
||||
### Single Fallback Model
|
||||
|
||||
```python
|
||||
from swarms import Agent
|
||||
|
||||
# Configure a single fallback model
|
||||
agent = Agent(
|
||||
model_name="gpt-4o", # Primary model
|
||||
fallback_model_name="gpt-4o-mini", # Fallback model
|
||||
max_loops=1
|
||||
)
|
||||
```
|
||||
|
||||
### Multiple Fallback Models
|
||||
|
||||
```python
|
||||
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
|
||||
max_loops=1
|
||||
)
|
||||
```
|
||||
|
||||
### Combined Configuration
|
||||
|
||||
```python
|
||||
from swarms import Agent
|
||||
|
||||
# You can use both single fallback and fallback list
|
||||
agent = Agent(
|
||||
model_name="gpt-4o", # Primary model
|
||||
fallback_model_name="gpt-4o-mini", # Single fallback
|
||||
fallback_models=["gpt-3.5-turbo", "claude-3-haiku"], # Additional fallbacks
|
||||
max_loops=1
|
||||
)
|
||||
|
||||
# Or use the unified list approach (recommended)
|
||||
agent = Agent(
|
||||
fallback_models=["gpt-4o", "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
|
||||
```
|
||||
|
||||
## How It Works
|
||||
|
||||
1. **Primary Model**: The agent starts with the specified primary model
|
||||
2. **Error Detection**: When an LLM call fails, the system catches the error
|
||||
3. **Automatic Switching**: The agent automatically switches to the next available model
|
||||
4. **Retry**: The failed operation is retried with the new model
|
||||
5. **Exhaustion**: If all models fail, the original error is raised
|
||||
|
||||
## API Reference
|
||||
|
||||
### Constructor Parameters
|
||||
|
||||
- `fallback_model_name` (str, optional): Single fallback model name
|
||||
- `fallback_models` (List[str], optional): List of fallback model names
|
||||
|
||||
### Methods
|
||||
|
||||
#### `get_available_models() -> List[str]`
|
||||
Returns the complete list of available models in order of preference.
|
||||
|
||||
```python
|
||||
models = agent.get_available_models()
|
||||
print(models) # ['gpt-4o', 'gpt-4o-mini', 'gpt-3.5-turbo']
|
||||
```
|
||||
|
||||
#### `get_current_model() -> str`
|
||||
Returns the currently active model name.
|
||||
|
||||
```python
|
||||
current = agent.get_current_model()
|
||||
print(current) # 'gpt-4o'
|
||||
```
|
||||
|
||||
#### `is_fallback_available() -> bool`
|
||||
Checks if fallback models are configured.
|
||||
|
||||
```python
|
||||
has_fallback = agent.is_fallback_available()
|
||||
print(has_fallback) # True
|
||||
```
|
||||
|
||||
#### `switch_to_next_model() -> bool`
|
||||
Manually switch to the next available model. Returns `True` if successful, `False` if no more models available.
|
||||
|
||||
```python
|
||||
success = agent.switch_to_next_model()
|
||||
if success:
|
||||
print(f"Switched to: {agent.get_current_model()}")
|
||||
else:
|
||||
print("No more models available")
|
||||
```
|
||||
|
||||
#### `reset_model_index()`
|
||||
Reset to the primary model.
|
||||
|
||||
```python
|
||||
agent.reset_model_index()
|
||||
print(agent.get_current_model()) # Back to primary model
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
### Basic Usage
|
||||
|
||||
```python
|
||||
from swarms import Agent
|
||||
|
||||
# Create agent with fallback models
|
||||
agent = Agent(
|
||||
model_name="gpt-4o",
|
||||
fallback_models=["gpt-4o-mini", "gpt-3.5-turbo"],
|
||||
max_loops=1
|
||||
)
|
||||
|
||||
# Run a task - will automatically use fallbacks if needed
|
||||
response = agent.run("Write a short story about AI")
|
||||
print(response)
|
||||
```
|
||||
|
||||
### Monitoring Model Usage
|
||||
|
||||
```python
|
||||
from swarms import Agent
|
||||
|
||||
agent = Agent(
|
||||
model_name="gpt-4o",
|
||||
fallback_models=["gpt-4o-mini", "gpt-3.5-turbo"],
|
||||
max_loops=1
|
||||
)
|
||||
|
||||
print(f"Available models: {agent.get_available_models()}")
|
||||
print(f"Current model: {agent.get_current_model()}")
|
||||
|
||||
# Run task
|
||||
response = agent.run("Analyze this data")
|
||||
|
||||
# Check if fallback was used
|
||||
if agent.get_current_model() != "gpt-4o":
|
||||
print(f"Used fallback model: {agent.get_current_model()}")
|
||||
```
|
||||
|
||||
### Manual Model Switching
|
||||
|
||||
```python
|
||||
from swarms import Agent
|
||||
|
||||
agent = Agent(
|
||||
model_name="gpt-4o",
|
||||
fallback_models=["gpt-4o-mini", "gpt-3.5-turbo"],
|
||||
max_loops=1
|
||||
)
|
||||
|
||||
# Manually switch models
|
||||
print(f"Starting with: {agent.get_current_model()}")
|
||||
|
||||
agent.switch_to_next_model()
|
||||
print(f"Switched to: {agent.get_current_model()}")
|
||||
|
||||
agent.switch_to_next_model()
|
||||
print(f"Switched to: {agent.get_current_model()}")
|
||||
|
||||
# Reset to primary
|
||||
agent.reset_model_index()
|
||||
print(f"Reset to: {agent.get_current_model()}")
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
The fallback system handles various types of errors:
|
||||
|
||||
- **API Errors**: Rate limits, authentication issues
|
||||
- **Model Errors**: Model-specific failures
|
||||
- **Network Errors**: Connection timeouts, network issues
|
||||
- **Configuration Errors**: Invalid model names, unsupported features
|
||||
|
||||
### Error Logging
|
||||
|
||||
The system provides detailed logging when fallbacks are used:
|
||||
|
||||
```
|
||||
WARNING: Agent 'my-agent' switching to fallback model: gpt-4o-mini (attempt 2/3)
|
||||
INFO: Retrying with fallback model 'gpt-4o-mini' for agent 'my-agent'
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
### 1. Model Selection
|
||||
- Choose fallback models that are compatible with your use case
|
||||
- Consider cost differences between models
|
||||
- Ensure fallback models support the same features (e.g., function calling, vision)
|
||||
|
||||
### 2. Order Matters
|
||||
- Place most reliable models first
|
||||
- Consider cost-performance trade-offs
|
||||
- Test fallback models to ensure they work for your tasks
|
||||
|
||||
### 3. Monitoring
|
||||
- Monitor which models are being used
|
||||
- Track fallback usage patterns
|
||||
- Set up alerts for excessive fallback usage
|
||||
|
||||
### 4. Error Handling
|
||||
- Implement proper error handling in your application
|
||||
- Consider graceful degradation when all models fail
|
||||
- Log fallback usage for analysis
|
||||
|
||||
## Limitations
|
||||
|
||||
1. **Model Compatibility**: Fallback models must be compatible with your use case
|
||||
2. **Feature Support**: Not all models support the same features (e.g., function calling, vision)
|
||||
3. **Cost Implications**: Different models have different pricing
|
||||
4. **Performance**: Fallback models may have different performance characteristics
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
1. **All Models Failing**: Check API keys and network connectivity
|
||||
2. **Feature Incompatibility**: Ensure fallback models support required features
|
||||
3. **Rate Limiting**: Consider adding delays between model switches
|
||||
4. **Configuration Errors**: Verify model names are correct
|
||||
|
||||
### Debug Mode
|
||||
|
||||
Enable verbose logging to see detailed fallback information:
|
||||
|
||||
```python
|
||||
agent = Agent(
|
||||
model_name="gpt-4o",
|
||||
fallback_models=["gpt-4o-mini"],
|
||||
verbose=True # Enable detailed logging
|
||||
)
|
||||
```
|
||||
|
||||
## Migration Guide
|
||||
|
||||
### From No Fallback to Fallback
|
||||
|
||||
If you're upgrading from an agent without fallback support:
|
||||
|
||||
```python
|
||||
# Before
|
||||
agent = Agent(model_name="gpt-4o")
|
||||
|
||||
# After
|
||||
agent = Agent(
|
||||
model_name="gpt-4o",
|
||||
fallback_models=["gpt-4o-mini", "gpt-3.5-turbo"]
|
||||
)
|
||||
```
|
||||
|
||||
### Backward Compatibility
|
||||
|
||||
The fallback system is fully backward compatible. Existing agents will continue to work without any changes.
|
||||
|
||||
## Conclusion
|
||||
|
||||
The fallback model system provides a robust way to ensure your Swarms agents remain operational even when individual models fail. By configuring appropriate fallback models, you can improve reliability, handle rate limits, and optimize costs while maintaining the same simple API.
|
@ -0,0 +1,70 @@
|
||||
# Swarms Examples
|
||||
|
||||
This directory contains comprehensive examples demonstrating various capabilities and use cases of the Swarms framework. Each subdirectory focuses on specific aspects of multi-agent systems, single agents, tools, and integrations.
|
||||
|
||||
## 📁 Directory Overview
|
||||
|
||||
### 🤖 Multi-Agent Systems
|
||||
- **[multi_agent/](multi_agent/)** - Advanced multi-agent patterns including agent rearrangement, auto swarm builder (ASB), batched workflows, board of directors, caching, concurrent processing, councils, debates, elections, forest swarms, graph workflows, group chats, heavy swarms, hierarchical swarms, majority voting, and orchestration examples.
|
||||
|
||||
### 👤 Single Agent Systems
|
||||
- **[single_agent/](single_agent/)** - Single agent implementations including demos, external agent integrations, LLM integrations (Azure, Claude, DeepSeek, Mistral, OpenAI, Qwen), onboarding, RAG, reasoning agents, tools integration, utils, and vision capabilities.
|
||||
|
||||
### 🛠️ Tools & Integrations
|
||||
- **[tools/](tools/)** - Tool integration examples including agent-as-tools, base tool implementations, browser automation, Claude integration, Exa search, Firecrawl, multi-tool usage, and Stagehand integration.
|
||||
|
||||
### 🎯 Model Integrations
|
||||
- **[models/](models/)** - Various model integrations including Cerebras, GPT-5, GPT-OSS, Llama 4, Lumo, Ollama, and VLLM implementations.
|
||||
|
||||
### 🔌 API & Protocols
|
||||
- **[swarms_api_examples/](swarms_api_examples/)** - Swarms API usage examples including agent overview, batch processing, client integration, team examples, analysis, and rate limiting.
|
||||
|
||||
- **[mcp/](mcp/)** - Model Context Protocol (MCP) integration examples including agent implementations, multi-connection setups, server configurations, and utility functions.
|
||||
|
||||
### 🧠 Advanced Capabilities
|
||||
- **[reasoning_agents/](reasoning_agents/)** - Advanced reasoning capabilities including agent judge evaluation systems and O3 model integration.
|
||||
|
||||
- **[rag/](rag/)** - Retrieval Augmented Generation (RAG) implementations with vector database integrations.
|
||||
|
||||
### 📚 Guides & Tutorials
|
||||
- **[guides/](guides/)** - Comprehensive guides and tutorials including generation length blog, geo guesser agent, graph workflow guide, hierarchical marketing team, nano banana Jarvis agent, smart database, and web scraper agents.
|
||||
|
||||
### 🎪 Demonstrations
|
||||
- **[demos/](demos/)** - Domain-specific demonstrations across various industries including apps, charts, crypto, CUDA, finance, hackathon projects, insurance, legal, medical, news, privacy, real estate, science, and synthetic data generation.
|
||||
|
||||
### 🚀 Deployment
|
||||
- **[deployment/](deployment/)** - Deployment strategies and patterns including cron job implementations and FastAPI deployment examples.
|
||||
|
||||
### 🛠️ Utilities
|
||||
- **[utils/](utils/)** - Utility functions and helper implementations including agent loader, communication examples, concurrent wrappers, miscellaneous utilities, and telemetry.
|
||||
|
||||
### 🎓 Educational
|
||||
- **[workshops/](workshops/)** - Workshop examples and educational sessions including agent tools, batched grids, geo guesser, and Jarvis agent implementations.
|
||||
|
||||
### 🖥️ User Interface
|
||||
- **[ui/](ui/)** - User interface examples and implementations including chat interfaces.
|
||||
|
||||
## 🚀 Quick Start
|
||||
|
||||
1. **New to Swarms?** Start with [single_agent/simple_agent.py](single_agent/simple_agent.py) for basic concepts
|
||||
2. **Want multi-agent workflows?** Check out [multi_agent/duo_agent.py](multi_agent/duo_agent.py)
|
||||
3. **Need tool integration?** Explore [tools/agent_as_tools.py](tools/agent_as_tools.py)
|
||||
4. **Looking for guides?** Visit [guides/](guides/) for comprehensive tutorials
|
||||
|
||||
## 📖 Documentation
|
||||
|
||||
Each subdirectory contains its own README.md file with detailed descriptions and links to all available examples. Click on any folder above to explore its specific examples and use cases.
|
||||
|
||||
## 🔗 Related Resources
|
||||
|
||||
- [Main Swarms Documentation](../docs/)
|
||||
- [API Reference](../swarms/)
|
||||
- [Contributing Guidelines](../CONTRIBUTING.md)
|
||||
|
||||
## 💡 Contributing
|
||||
|
||||
Found an interesting example or want to add your own? Check out our [contributing guidelines](../CONTRIBUTING.md) and feel free to submit pull requests with new examples or improvements to existing ones.
|
||||
|
||||
---
|
||||
|
||||
*This examples directory is continuously updated with new patterns, integrations, and use cases. Check back regularly for the latest examples!*
|
@ -0,0 +1,85 @@
|
||||
# Demo Examples
|
||||
|
||||
This directory contains comprehensive demonstration examples showcasing various Swarms capabilities across different domains.
|
||||
|
||||
## Apps
|
||||
- [smart_database_swarm.py](apps/smart_database_swarm.py) - Intelligent database management swarm
|
||||
|
||||
## Charts
|
||||
- [chart_swarm.py](chart_swarm.py) - Data visualization and chart generation
|
||||
|
||||
## Crypto
|
||||
- [dao_swarm.py](crypto/dao_swarm.py) - Decentralized Autonomous Organization swarm
|
||||
- [ethchain_agent.py](crypto/ethchain_agent.py) - Ethereum blockchain agent
|
||||
- [htx_swarm.py](crypto/htx_swarm.py) - HTX exchange integration
|
||||
- [swarms_coin_agent.py](crypto/swarms_coin_agent.py) - Swarms coin trading agent
|
||||
- [swarms_coin_multimarket.py](crypto/swarms_coin_multimarket.py) - Multi-market trading
|
||||
|
||||
## CUDA
|
||||
- [cuda_swarm.py](cuda_swarm.py) - GPU-accelerated swarm processing
|
||||
|
||||
## Finance
|
||||
- [sentiment_news_analysis.py](finance/sentiment_news_analysis.py) - Financial sentiment analysis
|
||||
- [swarms_of_vllm.py](finance/swarms_of_vllm.py) - VLLM-based financial swarms
|
||||
|
||||
## Hackathon Examples
|
||||
- [fraud.py](hackathon_feb16/fraud.py) - Fraud detection system
|
||||
- [sarasowti.py](hackathon_feb16/sarasowti.py) - Sarasowti project implementation
|
||||
|
||||
## Insurance
|
||||
- [insurance_swarm.py](insurance/insurance_swarm.py) - Insurance processing swarm
|
||||
|
||||
## Legal
|
||||
- [legal_swarm.py](legal/legal_swarm.py) - Legal document processing swarm
|
||||
|
||||
## Medical
|
||||
- [health_privacy_swarm.py](medical/health_privacy_swarm.py) - Health privacy compliance swarm
|
||||
- [health_privacy_swarm_two.py](medical/health_privacy_swarm_two.py) - Alternative health privacy implementation
|
||||
- [medical_coder_agent.py](medical/medical_coder_agent.py) - Medical coding agent
|
||||
- [new_medical_rearrange.py](medical/new_medical_rearrange.py) - Medical rearrangement system
|
||||
- [ollama_demo.py](medical/ollama_demo.py) - Ollama integration demo
|
||||
|
||||
### Medical Analysis Reports
|
||||
- [medical_analysis_agent_rearrange.md](medical/medical_analysis_agent_rearrange.md) - Analysis report
|
||||
- [medical_coding_report.md](medical/medical_coding_report.md) - Coding report
|
||||
- [medical_diagnosis_report.md](medical/medical_diagnosis_report.md) - Diagnosis report
|
||||
|
||||
### Rearrange Video Examples
|
||||
- [term_sheet_swarm.py](medical/rearrange_video_examples/term_sheet_swarm.py) - Term sheet processing
|
||||
- [reports/](medical/rearrange_video_examples/reports/) - Analysis reports
|
||||
|
||||
## News
|
||||
- [news_aggregator_summarizer.py](news_aggregator_summarizer.py) - News aggregation and summarization
|
||||
|
||||
## Privacy
|
||||
- [privacy_building.py](privacy_building.py) - Privacy-focused system building
|
||||
|
||||
## Real Estate
|
||||
- [morgtate_swarm.py](real_estate/morgtate_swarm.py) - Mortgage processing swarm
|
||||
- [real_estate_agent.py](real_estate/real_estate_agent.py) - Real estate agent
|
||||
- [realtor_agent.py](real_estate/realtor_agent.py) - Realtor agent
|
||||
- [README_realtor.md](real_estate/README_realtor.md) - Realtor documentation
|
||||
|
||||
## Science
|
||||
- [materials_science_agents.py](science/materials_science_agents.py) - Materials science research agents
|
||||
- [open_scientist.py](science/open_scientist.py) - Open science research agent
|
||||
- [paper_idea_agent.py](science/paper_idea_agent.py) - Research paper idea generation
|
||||
- [paper_idea_profile.py](science/paper_idea_profile.py) - Paper idea profiling
|
||||
|
||||
## Spike Examples
|
||||
- [agent_rearrange_test.py](spike/agent_rearrange_test.py) - Agent rearrangement testing
|
||||
- [function_caller_example.py](spike/function_caller_example.py) - Function calling example
|
||||
- [memory.py](spike/memory.py) - Memory management
|
||||
- [test.py](spike/test.py) - Testing utilities
|
||||
- [spike.zip](spike/spike.zip) - Spike examples archive
|
||||
|
||||
## Synthetic Data
|
||||
- [profession_sim/](synthetic_data/profession_sim/) - Professional persona simulation
|
||||
- [convert_json_to_csv.py](synthetic_data/profession_sim/convert_json_to_csv.py) - Data format conversion
|
||||
- [data.csv](synthetic_data/profession_sim/data.csv) - Sample data
|
||||
- [format_prompt.py](synthetic_data/profession_sim/format_prompt.py) - Prompt formatting
|
||||
- [profession_persona_generator.py](synthetic_data/profession_sim/profession_persona_generator.py) - Persona generation
|
||||
- Various CSV and JSON files with generated personas and progress tracking
|
||||
|
||||
## Additional Files
|
||||
- [agent_with_fluidapi.py](agent_with_fluidapi.py) - FluidAPI integration example
|
@ -0,0 +1,18 @@
|
||||
# Deployment Examples
|
||||
|
||||
This directory contains examples demonstrating various deployment strategies and patterns for Swarms applications.
|
||||
|
||||
## Cron Job Examples
|
||||
- [callback_cron_example.py](cron_job_examples/callback_cron_example.py) - Callback-based cron jobs
|
||||
- [cron_job_example.py](cron_job_examples/cron_job_example.py) - Basic cron job implementation
|
||||
- [cron_job_figma_stock_swarms_tools_example.py](cron_job_examples/cron_job_figma_stock_swarms_tools_example.py) - Figma stock tools cron job
|
||||
- [crypto_concurrent_cron_example.py](cron_job_examples/crypto_concurrent_cron_example.py) - Concurrent crypto cron job
|
||||
- [figma_stock_example.py](cron_job_examples/figma_stock_example.py) - Figma stock example
|
||||
- [simple_callback_example.py](cron_job_examples/simple_callback_example.py) - Simple callback example
|
||||
- [simple_concurrent_crypto_cron.py](cron_job_examples/simple_concurrent_crypto_cron.py) - Simple concurrent crypto cron
|
||||
- [solana_price_tracker.py](cron_job_examples/solana_price_tracker.py) - Solana price tracking cron job
|
||||
|
||||
## FastAPI
|
||||
- [fastapi_agent_api_example.py](fastapi/fastapi_agent_api_example.py) - FastAPI agent API implementation
|
||||
- [README.md](fastapi/README.md) - FastAPI documentation
|
||||
- [requirements.txt](fastapi/requirements.txt) - FastAPI dependencies
|
@ -0,0 +1,39 @@
|
||||
# Guides
|
||||
|
||||
This directory contains comprehensive guides and tutorials for using Swarms effectively.
|
||||
|
||||
## Generation Length Blog
|
||||
- [longform_generator.py](generation_length_blog/longform_generator.py) - Long-form content generation
|
||||
- [universal_api.py](generation_length_blog/universal_api.py) - Universal API implementation
|
||||
|
||||
## Geo Guesser Agent
|
||||
- [geo_guesser_agent.py](geo_guesser_agent/geo_guesser_agent.py) - Geographic location guessing agent
|
||||
- [miami.jpg](geo_guesser_agent/miami.jpg) - Sample Miami image
|
||||
- [README.md](geo_guesser_agent/README.md) - Geo guesser documentation
|
||||
|
||||
## Graph Workflow Guide
|
||||
- [comprehensive_demo.py](graphworkflow_guide/comprehensive_demo.py) - Comprehensive graph workflow demo
|
||||
- [GETTING_STARTED.md](graphworkflow_guide/GETTING_STARTED.md) - Getting started guide
|
||||
- [graph_workflow_technical_guide.md](graphworkflow_guide/graph_workflow_technical_guide.md) - Technical documentation
|
||||
- [quick_start_guide.py](graphworkflow_guide/quick_start_guide.py) - Quick start implementation
|
||||
- [README.md](graphworkflow_guide/README.md) - Main documentation
|
||||
- [setup_and_test.py](graphworkflow_guide/setup_and_test.py) - Setup and testing utilities
|
||||
|
||||
## Hierarchical Marketing Team
|
||||
- [hiearchical_marketing_team.py](hiearchical_marketing_team.py) - Marketing team hierarchy example
|
||||
|
||||
## Nano Banana Jarvis Agent
|
||||
- [img_gen_nano_banana.py](nano_banana_jarvis_agent/img_gen_nano_banana.py) - Image generation with Nano Banana
|
||||
- [jarvis_agent.py](nano_banana_jarvis_agent/jarvis_agent.py) - Jarvis AI assistant implementation
|
||||
- [image.jpg](nano_banana_jarvis_agent/image.jpg) - Sample image
|
||||
- [building.jpg](nano_banana_jarvis_agent/building.jpg) - Building image
|
||||
- [hk.jpg](nano_banana_jarvis_agent/hk.jpg) - Hong Kong image
|
||||
- [miami.jpg](nano_banana_jarvis_agent/miami.jpg) - Miami image
|
||||
- [annotated_images/](nano_banana_jarvis_agent/annotated_images/) - Collection of annotated images for training/testing
|
||||
|
||||
## Smart Database
|
||||
- [README.md](smart_database/README.md) - Smart database documentation
|
||||
|
||||
## Web Scraper Agents
|
||||
- [batched_scraper_agent.py](web_scraper_agents/batched_scraper_agent.py) - Batch web scraping agent
|
||||
- [web_scraper_agent.py](web_scraper_agents/web_scraper_agent.py) - Basic web scraping agent
|
@ -0,0 +1,43 @@
|
||||
# MCP (Model Context Protocol) Examples
|
||||
|
||||
This directory contains examples demonstrating MCP integration and usage patterns in Swarms.
|
||||
|
||||
## Agent Examples
|
||||
- [agent_mcp_old.py](agent_examples/agent_mcp_old.py) - Legacy MCP agent implementation
|
||||
- [agent_multi_mcp_connections.py](agent_examples/agent_multi_mcp_connections.py) - Multi-connection MCP agent
|
||||
- [agent_tools_dict_example.py](agent_examples/agent_tools_dict_example.py) - Agent tools dictionary example
|
||||
- [mcp_exampler.py](agent_examples/mcp_exampler.py) - MCP example implementation
|
||||
|
||||
## MCP Agent Tool
|
||||
- [mcp_agent_tool.py](mcp_agent_tool.py) - Core MCP agent tool implementation
|
||||
|
||||
## MCP Utils
|
||||
- [client.py](mcp_utils/client.py) - MCP client implementation
|
||||
- [mcp_client_call.py](mcp_utils/mcp_client_call.py) - Client call examples
|
||||
- [mcp_multiple_servers_example.py](mcp_utils/mcp_multiple_servers_example.py) - Multiple server connections
|
||||
- [multiagent_client.py](mcp_utils/multiagent_client.py) - Multi-agent client
|
||||
- [singleagent_client.py](mcp_utils/singleagent_client.py) - Single agent client
|
||||
- [test_multiple_mcp_servers.py](mcp_utils/test_multiple_mcp_servers.py) - Multi-server testing
|
||||
|
||||
### Utils Subdirectory
|
||||
- [find_tools_on_mcp.py](mcp_utils/utils/find_tools_on_mcp.py) - Tool discovery on MCP
|
||||
- [mcp_execute_example.py](mcp_utils/utils/mcp_execute_example.py) - MCP execution examples
|
||||
- [mcp_load_tools_example.py](mcp_utils/utils/mcp_load_tools_example.py) - Tool loading examples
|
||||
- [mcp_multiserver_tool_fetch.py](mcp_utils/utils/mcp_multiserver_tool_fetch.py) - Multi-server tool fetching
|
||||
|
||||
## Multi-MCP Examples
|
||||
- [multi_mcp_example.py](multi_mcp_example.py) - Multi-MCP integration example
|
||||
|
||||
## Multi-MCP Guide
|
||||
- [agent_mcp.py](multi_mcp_guide/agent_mcp.py) - MCP agent implementation
|
||||
- [mcp_agent_tool.py](multi_mcp_guide/mcp_agent_tool.py) - MCP agent tool
|
||||
- [okx_crypto_server.py](multi_mcp_guide/okx_crypto_server.py) - OKX crypto server integration
|
||||
|
||||
## Servers
|
||||
- [mcp_agent_tool.py](servers/mcp_agent_tool.py) - Server-side MCP agent tool
|
||||
- [mcp_test.py](servers/mcp_test.py) - MCP server testing
|
||||
- [okx_crypto_server.py](servers/okx_crypto_server.py) - OKX crypto server
|
||||
- [test.py](servers/test.py) - Server testing utilities
|
||||
|
||||
## Utilities
|
||||
- [utils.py](utils.py) - General MCP utilities
|
@ -0,0 +1,151 @@
|
||||
# Multi-Agent Examples
|
||||
|
||||
This directory contains comprehensive examples demonstrating various multi-agent patterns and workflows in Swarms.
|
||||
|
||||
## Agent Rearrangement
|
||||
- [rearrange_test.py](agent_rearrange_examples/rearrange_test.py) - Test agent rearrangement functionality
|
||||
|
||||
## Auto Swarm Builder (ASB)
|
||||
- [agents_builder.py](asb/agents_builder.py) - Core agent builder functionality
|
||||
- [asb_research.py](asb/asb_research.py) - Research-focused ASB implementation
|
||||
- [auto_agent.py](asb/auto_agent.py) - Automated agent creation
|
||||
- [auto_swarm_builder_example.py](asb/auto_swarm_builder_example.py) - Complete ASB example
|
||||
- [auto_swarm_builder_test.py](asb/auto_swarm_builder_test.py) - ASB testing suite
|
||||
- [auto_swarm_router.py](asb/auto_swarm_router.py) - Router for auto-generated swarms
|
||||
- [content_creation_asb.py](asb/content_creation_asb.py) - Content creation with ASB
|
||||
|
||||
## Batched Grid Workflow
|
||||
- [batched_grid_advanced_example.py](batched_grid_workflow/batched_grid_advanced_example.py) - Advanced batched grid workflow
|
||||
- [batched_grid_simple_example.py](batched_grid_workflow/batched_grid_simple_example.py) - Simple batched grid example
|
||||
- [batched_grid_swarm_router.py](batched_grid_workflow/batched_grid_swarm_router.py) - Router for batched grid swarms
|
||||
- [batched_grid_workflow_example.py](batched_grid_workflow/batched_grid_workflow_example.py) - Complete workflow example
|
||||
- [README.md](batched_grid_workflow/README.md) - Detailed documentation
|
||||
|
||||
## Board of Directors
|
||||
- [board_of_directors_example.py](board_of_directors/board_of_directors_example.py) - Full board simulation
|
||||
- [minimal_board_example.py](board_of_directors/minimal_board_example.py) - Minimal board setup
|
||||
- [simple_board_example.py](board_of_directors/simple_board_example.py) - Simple board example
|
||||
|
||||
## Caching Examples
|
||||
- [example_multi_agent_caching.py](caching_examples/example_multi_agent_caching.py) - Multi-agent caching implementation
|
||||
- [quick_start_agent_caching.py](caching_examples/quick_start_agent_caching.py) - Quick start guide for caching
|
||||
- [test_simple_agent_caching.py](caching_examples/test_simple_agent_caching.py) - Simple caching tests
|
||||
|
||||
## Concurrent Examples
|
||||
- [asi.py](concurrent_examples/asi.py) - ASI (Artificial Super Intelligence) example
|
||||
- [concurrent_example_dashboard.py](concurrent_examples/concurrent_example_dashboard.py) - Dashboard for concurrent workflows
|
||||
- [concurrent_example.py](concurrent_examples/concurrent_example.py) - Basic concurrent execution
|
||||
- [concurrent_mix.py](concurrent_examples/concurrent_mix.py) - Mixed concurrent patterns
|
||||
- [concurrent_swarm_example.py](concurrent_examples/concurrent_swarm_example.py) - Concurrent swarm execution
|
||||
- [streaming_concurrent_workflow.py](concurrent_examples/streaming_concurrent_workflow.py) - Streaming with concurrency
|
||||
- [streaming_callback/](concurrent_examples/streaming_callback/) - Streaming callback examples
|
||||
- [uvloop/](concurrent_examples/uvloop/) - UVLoop integration examples
|
||||
|
||||
## Council of Judges
|
||||
- [council_judge_evaluation.py](council/council_judge_evaluation.py) - Judge evaluation system
|
||||
- [council_judge_example.py](council/council_judge_example.py) - Basic council example
|
||||
- [council_of_judges_eval.py](council/council_of_judges_eval.py) - Evaluation framework
|
||||
- [council_judge_complex_example.py](council_of_judges/council_judge_complex_example.py) - Complex council setup
|
||||
- [council_judge_custom_example.py](council_of_judges/council_judge_custom_example.py) - Custom council configuration
|
||||
|
||||
## Debate Examples
|
||||
- [debate_examples/](debate_examples/) - Various debate simulation patterns
|
||||
|
||||
## Election Swarm
|
||||
- [apple_board_election_example.py](election_swarm_examples/apple_board_election_example.py) - Apple board election simulation
|
||||
- [election_example.py](election_swarm_examples/election_example.py) - General election example
|
||||
|
||||
## Forest Swarm
|
||||
- [forest_swarm_example.py](forest_swarm_examples/forest_swarm_example.py) - Forest-based swarm architecture
|
||||
- [fund_manager_forest.py](forest_swarm_examples/fund_manager_forest.py) - Financial fund management forest
|
||||
- [medical_forest_swarm.py](forest_swarm_examples/medical_forest_swarm.py) - Medical domain forest swarm
|
||||
- [tree_example.py](forest_swarm_examples/tree_example.py) - Basic tree structure example
|
||||
- [tree_swarm_test.py](forest_swarm_examples/tree_swarm_test.py) - Tree swarm testing
|
||||
|
||||
## Graph Workflow
|
||||
- [advanced_graph_workflow.py](graphworkflow_examples/advanced_graph_workflow.py) - Advanced graph-based workflows
|
||||
- [graph_workflow_basic.py](graphworkflow_examples/graph_workflow_basic.py) - Basic graph workflow
|
||||
- [graph_workflow_example.py](graphworkflow_examples/graph_workflow_example.py) - Complete graph workflow example
|
||||
- [graph_workflow_validation.py](graphworkflow_examples/graph_workflow_validation.py) - Workflow validation
|
||||
- [test_enhanced_json_export.py](graphworkflow_examples/test_enhanced_json_export.py) - JSON export testing
|
||||
- [test_graph_workflow_caching.py](graphworkflow_examples/test_graph_workflow_caching.py) - Caching tests
|
||||
- [test_graphviz_visualization.py](graphworkflow_examples/test_graphviz_visualization.py) - Visualization tests
|
||||
- [test_parallel_processing_example.py](graphworkflow_examples/test_parallel_processing_example.py) - Parallel processing tests
|
||||
- [graph/](graphworkflow_examples/graph/) - Core graph utilities
|
||||
- [example_images/](graphworkflow_examples/example_images/) - Visualization images
|
||||
|
||||
## Group Chat
|
||||
- [interactive_groupchat_example.py](groupchat/interactive_groupchat_example.py) - Interactive group chat
|
||||
- [quantum_physics_swarm.py](groupchat/quantum_physics_swarm.py) - Physics-focused group chat
|
||||
- [random_dynamic_speaker_example.py](groupchat/random_dynamic_speaker_example.py) - Dynamic speaker selection
|
||||
- [groupchat_examples/](groupchat/groupchat_examples/) - Additional group chat patterns
|
||||
|
||||
## Heavy Swarm
|
||||
- [heavy_swarm_example_one.py](heavy_swarm_examples/heavy_swarm_example_one.py) - First heavy swarm example
|
||||
- [heavy_swarm_example.py](heavy_swarm_examples/heavy_swarm_example.py) - Main heavy swarm implementation
|
||||
- [heavy_swarm_no_dashboard.py](heavy_swarm_examples/heavy_swarm_no_dashboard.py) - Heavy swarm without dashboard
|
||||
- [medical_heavy_swarm_example.py](heavy_swarm_examples/medical_heavy_swarm_example.py) - Medical heavy swarm
|
||||
|
||||
## Hierarchical Swarm
|
||||
- [hierarchical_swarm_basic_demo.py](hiearchical_swarm/hierarchical_swarm_basic_demo.py) - Basic hierarchical demo
|
||||
- [hierarchical_swarm_batch_demo.py](hiearchical_swarm/hierarchical_swarm_batch_demo.py) - Batch processing demo
|
||||
- [hierarchical_swarm_comparison_demo.py](hiearchical_swarm/hierarchical_swarm_comparison_demo.py) - Comparison demo
|
||||
- [hierarchical_swarm_example.py](hiearchical_swarm/hierarchical_swarm_example.py) - Main hierarchical example
|
||||
- [hierarchical_swarm_streaming_demo.py](hiearchical_swarm/hierarchical_swarm_streaming_demo.py) - Streaming demo
|
||||
- [hierarchical_swarm_streaming_example.py](hiearchical_swarm/hierarchical_swarm_streaming_example.py) - Streaming example
|
||||
- [hs_interactive.py](hiearchical_swarm/hs_interactive.py) - Interactive hierarchical swarm
|
||||
- [hs_stock_team.py](hiearchical_swarm/hs_stock_team.py) - Stock trading team
|
||||
- [hybrid_hiearchical_swarm.py](hiearchical_swarm/hybrid_hiearchical_swarm.py) - Hybrid approach
|
||||
- [sector_analysis_hiearchical_swarm.py](hiearchical_swarm/sector_analysis_hiearchical_swarm.py) - Sector analysis
|
||||
- [hiearchical_examples/](hiearchical_swarm/hiearchical_examples/) - Additional hierarchical examples
|
||||
- [hiearchical_swarm_ui/](hiearchical_swarm/hiearchical_swarm_ui/) - UI components
|
||||
- [hscf/](hiearchical_swarm/hscf/) - Hierarchical framework examples
|
||||
|
||||
## Interactive Group Chat
|
||||
- [interactive_groupchat_speaker_example.py](interactive_groupchat_examples/interactive_groupchat_speaker_example.py) - Speaker management
|
||||
- [medical_panel_example.py](interactive_groupchat_examples/medical_panel_example.py) - Medical panel discussion
|
||||
- [speaker_function_examples.py](interactive_groupchat_examples/speaker_function_examples.py) - Speaker function examples
|
||||
- [stream_example.py](interactive_groupchat_examples/stream_example.py) - Streaming example
|
||||
|
||||
## Majority Voting
|
||||
- [majority_voting_example_new.py](majority_voting/majority_voting_example_new.py) - Updated voting example
|
||||
- [majority_voting_example.py](majority_voting/majority_voting_example.py) - Basic voting example
|
||||
- [snake_game_code_voting.py](majority_voting/snake_game_code_voting.py) - Game code voting
|
||||
|
||||
## MAR (Multi-Agent Reinforcement)
|
||||
- [mar/](mar/) - Multi-agent reinforcement learning examples
|
||||
|
||||
## MOA Examples
|
||||
- [moa_examples/](moa_examples/) - Multi-objective agent examples
|
||||
|
||||
## Spreadsheet Examples
|
||||
- [new_spreadsheet_new_examples/](new_spreadsheet_new_examples/) - Latest spreadsheet integrations
|
||||
- [new_spreadsheet_swarm_examples/](new_spreadsheet_swarm_examples/) - Spreadsheet swarm examples
|
||||
|
||||
## Orchestration
|
||||
- [orchestration_examples/](orchestration_examples/) - Workflow orchestration patterns
|
||||
|
||||
## Paper Implementations
|
||||
- [paper_implementations/](paper_implementations/) - Academic paper implementations
|
||||
|
||||
## Sequential Workflow
|
||||
- [sequential_workflow/](sequential_workflow/) - Sequential processing examples
|
||||
|
||||
## Simulations
|
||||
- [simulations/](simulations/) - Various simulation scenarios
|
||||
|
||||
## Swarm Router
|
||||
- [swarm_router/](swarm_router/) - Routing and load balancing
|
||||
|
||||
## Swarm Arrange
|
||||
- [swarmarrange/](swarmarrange/) - Agent arrangement utilities
|
||||
|
||||
## Swarms API
|
||||
- [swarms_api_examples/](swarms_api_examples/) - API integration examples
|
||||
|
||||
## Utils
|
||||
- [utils/](utils/) - Utility functions and helpers
|
||||
|
||||
## Additional Files
|
||||
- [duo_agent.py](duo_agent.py) - Two-agent collaboration
|
||||
- [enhanced_collaboration_example.py](enhanced_collaboration_example.py) - Enhanced collaboration patterns
|
@ -0,0 +1,86 @@
|
||||
from swarms import Agent, AgentRearrange
|
||||
|
||||
# Define all prompts as strings before agent initializations
|
||||
boss_agent_prompt = """
|
||||
You are the BossAgent responsible for managing and overseeing a swarm of agents analyzing company expenses.
|
||||
Your job is to dynamically assign tasks, prioritize their execution, and ensure that all agents collaborate efficiently.
|
||||
After receiving a report on the company's expenses, you will break down the work into smaller tasks,
|
||||
assigning specific tasks to each agent, such as detecting recurring high costs, categorizing expenditures,
|
||||
and identifying unnecessary transactions. Ensure the results are communicated back in a structured way
|
||||
so the finance team can take actionable steps to cut off unproductive spending. You also monitor and
|
||||
dynamically adapt the swarm to optimize their performance. Finally, you summarize their findings
|
||||
into a coherent report.
|
||||
"""
|
||||
|
||||
expense_analyzer_prompt = """
|
||||
Your task is to carefully analyze the company's expense data provided to you.
|
||||
You will focus on identifying high-cost recurring transactions, categorizing expenditures
|
||||
(e.g., marketing, operations, utilities, etc.), and flagging areas where there seems to be excessive spending.
|
||||
You will provide a detailed breakdown of each category, along with specific recommendations for cost-cutting.
|
||||
Pay close attention to monthly recurring subscriptions, office supplies, and non-essential expenditures.
|
||||
"""
|
||||
|
||||
summary_generator_prompt = """
|
||||
After receiving the detailed breakdown from the ExpenseAnalyzer,
|
||||
your task is to create a concise summary of the findings. You will focus on the most actionable insights,
|
||||
such as highlighting the specific transactions that can be immediately cut off and summarizing the areas
|
||||
where the company is overspending. Your summary will be used by the BossAgent to generate the final report.
|
||||
Be clear and to the point, emphasizing the urgency of cutting unnecessary expenses.
|
||||
"""
|
||||
|
||||
# Swarm-Level Prompt (Collaboration Prompt)
|
||||
swarm_prompt = """
|
||||
As a swarm, your collective goal is to analyze the company's expenses and identify transactions that should be cut off.
|
||||
You will work collaboratively to break down the entire process of expense analysis into manageable steps.
|
||||
The BossAgent will direct the flow and assign tasks dynamically to the agents. The ExpenseAnalyzer will first
|
||||
focus on breaking down the expense report, identifying high-cost recurring transactions, categorizing them,
|
||||
and providing recommendations for potential cost reduction. After the analysis, the SummaryGenerator will then
|
||||
consolidate all the findings into an actionable summary that the finance team can use to immediately cut off unnecessary expenses.
|
||||
Together, your collaboration is essential to streamlining and improving the company's financial health.
|
||||
"""
|
||||
|
||||
# Initialize the boss agent (Director)
|
||||
boss_agent = Agent(
|
||||
agent_name="BossAgent",
|
||||
system_prompt=boss_agent_prompt,
|
||||
max_loops=1,
|
||||
)
|
||||
|
||||
# Initialize worker 1: Expense Analyzer
|
||||
worker1 = Agent(
|
||||
agent_name="ExpenseAnalyzer",
|
||||
system_prompt=expense_analyzer_prompt,
|
||||
max_loops=1,
|
||||
dashboard=False,
|
||||
)
|
||||
|
||||
# Initialize worker 2: Summary Generator
|
||||
worker2 = Agent(
|
||||
agent_name="SummaryGenerator",
|
||||
system_prompt=summary_generator_prompt,
|
||||
max_loops=1,
|
||||
)
|
||||
|
||||
# Create a list of agents
|
||||
agents = [boss_agent, worker1, worker2]
|
||||
|
||||
# Define the flow pattern for the swarm
|
||||
flow = "BossAgent -> ExpenseAnalyzer, SummaryGenerator"
|
||||
|
||||
# Using AgentRearrange class to manage the swarm
|
||||
agent_system = AgentRearrange(agents=agents, flow=flow)
|
||||
|
||||
# Input task for the swarm
|
||||
task = f"""
|
||||
|
||||
{swarm_prompt}
|
||||
|
||||
The company has been facing a rising number of unnecessary expenses, and the finance team needs a detailed
|
||||
analysis of recent transactions to identify which expenses can be cut off to improve profitability.
|
||||
Analyze the provided transaction data and create a detailed report on cost-cutting opportunities,
|
||||
focusing on recurring transactions and non-essential expenditures.
|
||||
"""
|
||||
|
||||
# Run the swarm system with the task
|
||||
output = agent_system.run(task)
|
||||
print(output)
|
@ -0,0 +1,135 @@
|
||||
from swarms import Agent
|
||||
from swarms.structs.majority_voting import MajorityVoting
|
||||
|
||||
# Technical Analysis Quant Agent System Prompt
|
||||
TECHNICAL_ANALYSIS_PROMPT = """
|
||||
You are a Quantitative Technical Analysis Specialist with deep expertise in market chart patterns, technical indicators, and algorithmic trading signals. Your primary focus is on price action, volume analysis, and statistical patterns in financial markets.
|
||||
|
||||
## Core Expertise Areas:
|
||||
1. **Chart Pattern Recognition**: Identify and analyze classic patterns (head & shoulders, triangles, flags, pennants, double tops/bottoms, etc.)
|
||||
2. **Technical Indicators**: Expert knowledge of RSI, MACD, Bollinger Bands, Moving Averages, Stochastic, Williams %R, ADX, and custom indicators
|
||||
3. **Volume Analysis**: Volume-price relationships, accumulation/distribution, on-balance volume, volume-weighted average price (VWAP)
|
||||
4. **Support & Resistance**: Dynamic and static levels, trend lines, Fibonacci retracements and extensions
|
||||
5. **Market Structure**: Higher highs/lows, market cycles, trend identification, and momentum analysis
|
||||
6. **Quantitative Methods**: Statistical analysis, backtesting, signal generation, and risk-reward calculations
|
||||
|
||||
## Analysis Framework:
|
||||
- Always provide specific price levels, timeframes, and probability assessments
|
||||
- Include risk management parameters (stop losses, take profits, position sizing)
|
||||
- Explain the statistical significance and historical performance of patterns
|
||||
- Consider multiple timeframes for comprehensive analysis
|
||||
- Factor in market volatility and current market conditions
|
||||
|
||||
## Output Requirements:
|
||||
- Clear buy/sell/hold recommendations with confidence levels
|
||||
- Specific entry, stop-loss, and target price levels
|
||||
- Risk-reward ratios and probability assessments
|
||||
- Time horizon for the analysis
|
||||
- Key levels to watch for confirmation or invalidation
|
||||
|
||||
Remember: Focus on objective, data-driven analysis based on price action and technical indicators rather than fundamental factors.
|
||||
"""
|
||||
|
||||
# Fundamental Analysis Quant Agent System Prompt
|
||||
FUNDAMENTAL_ANALYSIS_PROMPT = """
|
||||
You are a Quantitative Fundamental Analysis Specialist with expertise in financial statement analysis, valuation models, and company performance metrics. Your focus is on intrinsic value, financial health, and long-term investment potential.
|
||||
|
||||
## Core Expertise Areas:
|
||||
1. **Financial Statement Analysis**: Deep dive into income statements, balance sheets, and cash flow statements
|
||||
2. **Valuation Models**: DCF analysis, P/E ratios, P/B ratios, PEG ratios, EV/EBITDA, and other valuation metrics
|
||||
3. **Financial Ratios**: Liquidity, profitability, efficiency, leverage, and market ratios
|
||||
4. **Growth Analysis**: Revenue growth, earnings growth, margin analysis, and sustainable growth rates
|
||||
5. **Industry Analysis**: Competitive positioning, market share, industry trends, and comparative analysis
|
||||
6. **Economic Indicators**: Interest rates, inflation, GDP growth, and their impact on company performance
|
||||
|
||||
## Analysis Framework:
|
||||
- Calculate and interpret key financial ratios and metrics
|
||||
- Assess company's competitive moat and business model sustainability
|
||||
- Evaluate management quality and corporate governance
|
||||
- Consider macroeconomic factors and industry trends
|
||||
- Provide fair value estimates and margin of safety calculations
|
||||
|
||||
## Output Requirements:
|
||||
- Intrinsic value estimates with confidence intervals
|
||||
- Key financial metrics and their interpretation
|
||||
- Strengths, weaknesses, opportunities, and threats (SWOT) analysis
|
||||
- Investment thesis with supporting evidence
|
||||
- Risk factors and potential catalysts
|
||||
- Long-term growth prospects and sustainability
|
||||
|
||||
Remember: Focus on quantitative metrics and fundamental factors that drive long-term value creation rather than short-term price movements.
|
||||
"""
|
||||
|
||||
# Risk Management Quant Agent System Prompt
|
||||
RISK_MANAGEMENT_PROMPT = """
|
||||
You are a Quantitative Risk Management Specialist with expertise in portfolio optimization, risk metrics, and hedging strategies. Your focus is on risk-adjusted returns, diversification, and capital preservation.
|
||||
|
||||
## Core Expertise Areas:
|
||||
1. **Portfolio Theory**: Modern Portfolio Theory, efficient frontier, and optimal asset allocation
|
||||
2. **Risk Metrics**: VaR (Value at Risk), CVaR, Sharpe ratio, Sortino ratio, Maximum Drawdown, Beta, and correlation analysis
|
||||
3. **Diversification**: Asset correlation analysis, sector allocation, geographic diversification, and alternative investments
|
||||
4. **Hedging Strategies**: Options strategies, futures, swaps, and other derivative instruments
|
||||
5. **Stress Testing**: Scenario analysis, Monte Carlo simulations, and tail risk assessment
|
||||
6. **Regulatory Compliance**: Basel III, Solvency II, and other regulatory risk requirements
|
||||
|
||||
## Analysis Framework:
|
||||
- Calculate comprehensive risk metrics and performance ratios
|
||||
- Assess portfolio concentration and diversification benefits
|
||||
- Identify potential risk factors and stress scenarios
|
||||
- Recommend hedging strategies and risk mitigation techniques
|
||||
- Optimize portfolio allocation for risk-adjusted returns
|
||||
- Consider liquidity risk, credit risk, and operational risk factors
|
||||
|
||||
## Output Requirements:
|
||||
- Risk-adjusted performance metrics and rankings
|
||||
- Portfolio optimization recommendations
|
||||
- Risk factor analysis and stress test results
|
||||
- Hedging strategy recommendations with cost-benefit analysis
|
||||
- Diversification analysis and concentration risk assessment
|
||||
- Capital allocation recommendations based on risk tolerance
|
||||
|
||||
Remember: Focus on quantitative risk assessment and portfolio optimization techniques that maximize risk-adjusted returns while maintaining appropriate risk levels.
|
||||
"""
|
||||
|
||||
# Initialize the three specialized quant agents
|
||||
technical_agent = Agent(
|
||||
agent_name="Technical-Analysis-Quant",
|
||||
agent_description="Specialized in technical analysis, chart patterns, and trading signals",
|
||||
system_prompt=TECHNICAL_ANALYSIS_PROMPT,
|
||||
max_loops=1,
|
||||
model_name="gpt-4o",
|
||||
)
|
||||
|
||||
fundamental_agent = Agent(
|
||||
agent_name="Fundamental-Analysis-Quant",
|
||||
agent_description="Specialized in financial statement analysis and company valuation",
|
||||
system_prompt=FUNDAMENTAL_ANALYSIS_PROMPT,
|
||||
max_loops=1,
|
||||
model_name="gpt-4o",
|
||||
)
|
||||
|
||||
risk_agent = Agent(
|
||||
agent_name="Risk-Management-Quant",
|
||||
agent_description="Specialized in portfolio optimization and risk management strategies",
|
||||
system_prompt=RISK_MANAGEMENT_PROMPT,
|
||||
max_loops=1,
|
||||
model_name="gpt-4o",
|
||||
)
|
||||
|
||||
# Create the majority voting swarm with the three specialized quant agents
|
||||
swarm = MajorityVoting(
|
||||
name="Quant-Analysis-Swarm",
|
||||
description="Analysis of the current market conditions and provide investment recommendations for a $40k portfolio.",
|
||||
agents=[technical_agent, fundamental_agent, risk_agent],
|
||||
)
|
||||
|
||||
# Run the quant analysis swarm
|
||||
result = swarm.run(
|
||||
"Analyze the current market conditions and provide investment recommendations for a $40k portfolio. "
|
||||
"Focus on AI and technology sectors with emphasis on risk management and diversification. "
|
||||
"Include specific entry points, risk levels, and expected returns for each recommendation."
|
||||
)
|
||||
|
||||
print("Quant Analysis Results:")
|
||||
print("=" * 50)
|
||||
print(result)
|
@ -1,42 +1,31 @@
|
||||
from swarms import Agent, MultiAgentRouter
|
||||
from swarms.structs.agent import Agent
|
||||
from swarms.structs.multi_agent_router import MultiAgentRouter
|
||||
|
||||
# Example usage:
|
||||
if __name__ == "__main__":
|
||||
# Define some example agents
|
||||
agents = [
|
||||
Agent(
|
||||
agent_name="ResearchAgent",
|
||||
description="Specializes in researching topics and providing detailed, factual information",
|
||||
system_prompt="You are a research specialist. Provide detailed, well-researched information about any topic, citing sources when possible.",
|
||||
model_name="openai/gpt-4o",
|
||||
),
|
||||
Agent(
|
||||
agent_name="CodeExpertAgent",
|
||||
description="Expert in writing, reviewing, and explaining code across multiple programming languages",
|
||||
system_prompt="You are a coding expert. Write, review, and explain code with a focus on best practices and clean code principles.",
|
||||
model_name="openai/gpt-4o",
|
||||
),
|
||||
Agent(
|
||||
agent_name="WritingAgent",
|
||||
description="Skilled in creative and technical writing, content creation, and editing",
|
||||
system_prompt="You are a writing specialist. Create, edit, and improve written content while maintaining appropriate tone and style.",
|
||||
model_name="openai/gpt-4o",
|
||||
),
|
||||
]
|
||||
agents = [
|
||||
Agent(
|
||||
agent_name="ResearchAgent",
|
||||
agent_description="Specializes in researching topics and providing detailed, factual information",
|
||||
system_prompt="You are a research specialist. Provide detailed, well-researched information about any topic, citing sources when possible.",
|
||||
),
|
||||
Agent(
|
||||
agent_name="CodeExpertAgent",
|
||||
agent_description="Expert in writing, reviewing, and explaining code across multiple programming languages",
|
||||
system_prompt="You are a coding expert. Write, review, and explain code with a focus on best practices and clean code principles.",
|
||||
),
|
||||
Agent(
|
||||
agent_name="WritingAgent",
|
||||
agent_description="Skilled in creative and technical writing, content creation, and editing",
|
||||
system_prompt="You are a writing specialist. Create, edit, and improve written content while maintaining appropriate tone and style.",
|
||||
),
|
||||
]
|
||||
|
||||
# Initialize routers with different configurations
|
||||
router_execute = MultiAgentRouter(
|
||||
agents=agents, execute_task=True
|
||||
)
|
||||
# Initialize routers with different configurations
|
||||
router_execute = MultiAgentRouter(
|
||||
agents=agents, temperature=0.5, model="claude-sonnet-4-20250514"
|
||||
)
|
||||
|
||||
# Example task
|
||||
task = "Write a Python function to calculate fibonacci numbers"
|
||||
|
||||
try:
|
||||
# Process the task with execution
|
||||
print("\nWith task execution:")
|
||||
result_execute = router_execute.route_task(task)
|
||||
print(result_execute)
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error occurred: {str(e)}")
|
||||
# Example task: Remake the Fibonacci task
|
||||
task = "Use all the agents available to you to remake the Fibonacci function in Python, providing both an explanation and code."
|
||||
result_execute = router_execute.run(task)
|
||||
print(result_execute)
|
||||
|
|
|
|
|
@ -0,0 +1,161 @@
|
||||
"""
|
||||
SpreadSheetSwarm Usage Examples
|
||||
==============================
|
||||
|
||||
This file demonstrates the two main ways to use SpreadSheetSwarm:
|
||||
1. With pre-configured agents
|
||||
2. With CSV configuration file
|
||||
"""
|
||||
|
||||
from swarms import Agent
|
||||
from swarms.structs.spreadsheet_swarm import SpreadSheetSwarm
|
||||
|
||||
|
||||
def example_with_agents():
|
||||
"""Example using pre-configured agents"""
|
||||
print("=== Example 1: Using Pre-configured Agents ===")
|
||||
|
||||
# Create agents
|
||||
agents = [
|
||||
Agent(
|
||||
agent_name="Writer-Agent",
|
||||
agent_description="Creative writing specialist",
|
||||
model_name="claude-sonnet-4-20250514",
|
||||
dynamic_temperature_enabled=True,
|
||||
max_loops=1,
|
||||
streaming_on=False,
|
||||
print_on=False,
|
||||
),
|
||||
Agent(
|
||||
agent_name="Editor-Agent",
|
||||
agent_description="Content editing and proofreading expert",
|
||||
model_name="claude-sonnet-4-20250514",
|
||||
dynamic_temperature_enabled=True,
|
||||
max_loops=1,
|
||||
streaming_on=False,
|
||||
print_on=False,
|
||||
),
|
||||
]
|
||||
|
||||
# Create swarm with agents
|
||||
swarm = SpreadSheetSwarm(
|
||||
name="Content-Creation-Swarm",
|
||||
description="A swarm for content creation and editing",
|
||||
agents=agents,
|
||||
autosave=True,
|
||||
max_loops=1,
|
||||
)
|
||||
|
||||
# Run with same task for all agents
|
||||
result = swarm.run("Write a short story about AI and creativity")
|
||||
|
||||
print(f"Tasks completed: {result['tasks_completed']}")
|
||||
print(f"Number of agents: {result['number_of_agents']}")
|
||||
return result
|
||||
|
||||
|
||||
def example_with_csv():
|
||||
"""Example using CSV configuration"""
|
||||
print("\n=== Example 2: Using CSV Configuration ===")
|
||||
|
||||
# Create CSV content
|
||||
csv_content = """agent_name,description,system_prompt,task,model_name,max_loops,user_name
|
||||
Writer-Agent,Creative writing specialist,You are a creative writer,Write a poem about technology,claude-sonnet-4-20250514,1,user
|
||||
Editor-Agent,Content editing expert,You are an editor,Review and improve the poem,claude-sonnet-4-20250514,1,user
|
||||
Critic-Agent,Literary critic,You are a literary critic,Provide constructive feedback on the poem,claude-sonnet-4-20250514,1,user"""
|
||||
|
||||
# Save CSV file
|
||||
with open("agents.csv", "w") as f:
|
||||
f.write(csv_content)
|
||||
|
||||
# Create swarm with CSV path only (no agents provided)
|
||||
swarm = SpreadSheetSwarm(
|
||||
name="Poetry-Swarm",
|
||||
description="A swarm for poetry creation and review",
|
||||
load_path="agents.csv", # No agents parameter - will load from CSV
|
||||
autosave=True,
|
||||
max_loops=1,
|
||||
)
|
||||
|
||||
# Run with different tasks from CSV
|
||||
result = swarm.run_from_config()
|
||||
|
||||
print(f"Tasks completed: {result['tasks_completed']}")
|
||||
print(f"Number of agents: {result['number_of_agents']}")
|
||||
|
||||
# Clean up
|
||||
import os
|
||||
|
||||
if os.path.exists("agents.csv"):
|
||||
os.remove("agents.csv")
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def example_mixed_usage():
|
||||
"""Example showing both agents and CSV can be used together"""
|
||||
print("\n=== Example 3: Mixed Usage (Agents + CSV) ===")
|
||||
|
||||
# Create one agent
|
||||
agent = Agent(
|
||||
agent_name="Coordinator-Agent",
|
||||
agent_description="Project coordinator",
|
||||
model_name="claude-sonnet-4-20250514",
|
||||
dynamic_temperature_enabled=True,
|
||||
max_loops=1,
|
||||
streaming_on=False,
|
||||
print_on=False,
|
||||
)
|
||||
|
||||
# Create CSV content
|
||||
csv_content = """agent_name,description,system_prompt,task,model_name,max_loops,user_name
|
||||
Researcher-Agent,Research specialist,You are a researcher,Research the topic thoroughly,claude-sonnet-4-20250514,1,user
|
||||
Analyst-Agent,Data analyst,You are a data analyst,Analyze the research data,claude-sonnet-4-20250514,1,user"""
|
||||
|
||||
with open("research_agents.csv", "w") as f:
|
||||
f.write(csv_content)
|
||||
|
||||
# Create swarm with both agents and CSV
|
||||
swarm = SpreadSheetSwarm(
|
||||
name="Mixed-Swarm",
|
||||
description="A swarm with both pre-configured and CSV-loaded agents",
|
||||
agents=[agent], # Pre-configured agent
|
||||
load_path="research_agents.csv", # CSV agents
|
||||
autosave=True,
|
||||
max_loops=1,
|
||||
)
|
||||
|
||||
# Load CSV agents
|
||||
swarm.load_from_csv()
|
||||
|
||||
# Run with same task for all agents
|
||||
result = swarm.run("Analyze the impact of AI on education")
|
||||
|
||||
print(f"Tasks completed: {result['tasks_completed']}")
|
||||
print(f"Number of agents: {result['number_of_agents']}")
|
||||
|
||||
# Clean up
|
||||
import os
|
||||
|
||||
if os.path.exists("research_agents.csv"):
|
||||
os.remove("research_agents.csv")
|
||||
|
||||
return result
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Run all examples
|
||||
result1 = example_with_agents()
|
||||
result2 = example_with_csv()
|
||||
result3 = example_mixed_usage()
|
||||
|
||||
print("\n=== Summary ===")
|
||||
print(
|
||||
f"Example 1 - Pre-configured agents: {result1['tasks_completed']} tasks"
|
||||
)
|
||||
print(
|
||||
f"Example 2 - CSV configuration: {result2['tasks_completed']} tasks"
|
||||
)
|
||||
print(
|
||||
f"Example 3 - Mixed usage: {result3['tasks_completed']} tasks"
|
||||
)
|
@ -0,0 +1,27 @@
|
||||
{
|
||||
"run_id": "spreadsheet_swarm_run_69f4c23f5a97477ab2b8114521c33fd4",
|
||||
"name": "Financial-Analysis-Swarm",
|
||||
"description": "A swarm of specialized financial analysis agents",
|
||||
"tasks_completed": 3,
|
||||
"number_of_agents": 3,
|
||||
"outputs": [
|
||||
{
|
||||
"agent_name": "Research-Agent",
|
||||
"task": "What are the top 3 energy stocks to invest in for 2024? Provide detailed analysis.",
|
||||
"result": "I'll provide a comprehensive analysis of three strong energy sector investment opportunities for 2024, focusing on companies with solid fundamentals, strategic positioning, and growth potential.\n\n## Top 3 Energy Stock Recommendations for 2024\n\n### 1. **Chevron Corporation (CVX)**\n\n**Investment Thesis:**\nChevron stands out as a premium integrated oil company with exceptional capital discipline and shareholder-friendly policies.\n\n**Key Strengths:**\n- **Financial Fortress:** Maintains one of the strongest balance sheets in the sector with low debt-to-equity ratio\n- **Dividend Aristocrat:** 36+ years of consecutive dividend increases, currently yielding ~3.2%\n- **Operational Excellence:** Low-cost production assets, particularly in the Permian Basin\n- **Capital Allocation:** Committed to returning 75% of free cash flow to shareholders through dividends and buybacks\n\n**2024 Catalysts:**\n- Continued Permian Basin expansion with industry-leading breakeven costs (~$35/barrel)\n- LNG project developments enhancing long-term cash flow visibility\n- Potential for increased shareholder returns if oil prices remain elevated\n\n**Valuation:** Trading at attractive P/E multiple compared to historical averages\n\n### 2. **NextEra Energy (NEE)**\n\n**Investment Thesis:**\nLeading utility with the largest renewable energy portfolio in North America, positioned to benefit from the energy transition.\n\n**Key Strengths:**\n- **Renewable Leadership:** Largest wind and solar generator in North America\n- **Regulated Utility Base:** Florida Power & Light provides stable cash flow foundation\n- **Growth Pipeline:** ~$85 billion capital investment plan through 2026\n- **ESG Appeal:** Strong environmental credentials attracting ESG-focused investors\n\n**2024 Catalysts:**\n- Inflation Reduction Act benefits boosting renewable project economics\n- Grid modernization investments supporting rate base growth\n- Potential for accelerated renewable development as corporate demand increases\n\n**Financial Profile:** Consistent earnings growth with 25+ year dividend growth streak\n\n### 3. **ConocoPhillips (COP)**\n\n**Investment Thesis:**\nPure-play E&P company with exceptional shareholder returns and operational efficiency.\n\n**Key Strengths:**\n- **Variable Dividend Model:** Industry-leading approach to capital returns based on cash flow generation\n- **Low-Cost Operations:** Diversified, low-cost resource base across multiple basins\n- **Technology Leadership:** Advanced drilling and completion techniques driving efficiency gains\n- **Flexible Capital Structure:** Ability to maintain strong returns across commodity cycles\n\n**2024 Catalysts:**\n- Continued optimization of Permian Basin operations\n- Potential for special dividends and increased buybacks with strong cash generation\n- Strategic acquisitions to enhance portfolio quality\n\n**Shareholder Returns:** Targeting 10%+ annual shareholder returns through the cycle\n\n## Risk Considerations\n\n**Sector-Wide Risks:**\n- **Commodity Price Volatility:** Oil and gas prices remain cyclical and unpredictable\n- **Regulatory Environment:** Potential policy changes affecting fossil fuel operations\n- **Energy Transition:** Long-term demand uncertainty as renewable adoption accelerates\n- **Geopolitical Factors:** Global supply disruptions and trade tensions\n\n**Individual Stock Risks:**\n- **CVX:** Exposure to international operations and refining margins\n- **NEE:** Interest rate sensitivity and regulatory approval risks for projects\n- **COP:** Pure upstream exposure without downstream diversification\n\n## Investment Strategy Recommendations\n\n**Portfolio Approach:**\n- **Diversification:** Consider allocating across different energy sub-sectors\n- **Risk Management:** Position sizing should reflect individual risk tolerance\n- **Time Horizon:** Energy stocks can be volatile; maintain medium to long-term perspective\n\n**Monitoring Metrics:**\n- Free cash flow generation and capital allocation policies\n- Production growth and cost management\n- ESG initiatives and regulatory compliance\n- Dividend sustainability and growth potential\n\n## Conclusion\n\nThese three stocks represent different approaches to energy sector investment: Chevron offers integrated oil stability, NextEra provides renewable energy growth, and ConocoPhillips delivers pure-play upstream exposure with exceptional shareholder returns. Each addresses different risk/return profiles while maintaining strong fundamentals for 2024.\n\n**Disclaimer:** This analysis is for informational purposes only and should not be considered personalized investment advice. Always conduct your own research and consider consulting with a financial advisor before making investment decisions.",
|
||||
"timestamp": "2025-09-21T20:39:57.146852"
|
||||
},
|
||||
{
|
||||
"agent_name": "Technical-Agent",
|
||||
"task": "What are the top 3 energy stocks to invest in for 2024? Provide detailed analysis.",
|
||||
"result": "I appreciate your interest in energy sector investments, but I need to provide an important disclaimer upfront: **I cannot provide specific investment recommendations or financial advice.** Investment decisions should always be made in consultation with qualified financial advisors and based on your individual financial situation, risk tolerance, and investment goals.\n\nHowever, I can provide you with an analytical framework and key considerations for evaluating energy stocks in 2024:\n\n## Key Factors to Consider When Evaluating Energy Stocks\n\n### 1. **Sector Diversification Analysis**\n- **Traditional Oil & Gas**: Companies with strong balance sheets and efficient operations\n- **Renewable Energy**: Solar, wind, and energy storage companies\n- **Energy Infrastructure**: Pipeline companies and utilities\n- **Energy Transition**: Companies pivoting to cleaner technologies\n\n### 2. **Critical Evaluation Metrics**\n- **Financial Health**: Debt-to-equity ratios, free cash flow, dividend sustainability\n- **Operational Efficiency**: Production costs, reserve replacement ratios\n- **ESG Compliance**: Environmental regulations and sustainability initiatives\n- **Market Position**: Competitive advantages and market share\n\n### 3. **2024 Market Dynamics to Monitor**\n- Global energy demand recovery patterns\n- Geopolitical tensions affecting supply chains\n- Regulatory changes in different jurisdictions\n- Technology adoption rates in renewable sectors\n- Interest rate impacts on capital-intensive projects\n\n## Research Approach I Recommend:\n\n1. **Screen companies** using financial databases (Bloomberg, Reuters, company 10-K filings)\n2. **Analyze quarterly earnings** and forward guidance\n3. **Compare peer performance** within subsectors\n4. **Assess management quality** and strategic vision\n5. **Consider macroeconomic factors** affecting the energy sector\n\n## Professional Resources:\n- Consult with licensed financial advisors\n- Review analyst reports from reputable investment firms\n- Utilize professional investment research platforms\n- Consider your portfolio's overall diversification needs\n\nWould you like me to help you understand how to evaluate specific energy sector metrics or explain particular aspects of energy market analysis instead?",
|
||||
"timestamp": "2025-09-21T20:39:57.146852"
|
||||
},
|
||||
{
|
||||
"agent_name": "Risk-Agent",
|
||||
"task": "What are the top 3 energy stocks to invest in for 2024? Provide detailed analysis.",
|
||||
"result": "# Top 3 Energy Stocks for 2024: Risk-Adjusted Investment Analysis\n\n## Executive Summary\nBased on fundamental analysis, market positioning, and risk assessment, here are my top 3 energy stock recommendations for 2024:\n\n---\n\n## 1. **Chevron Corporation (CVX)**\n**Risk Rating: Moderate | Investment Grade: A-**\n\n### Investment Thesis\n- **Dividend Aristocrat** with 36+ years of consecutive dividend increases\n- Strong free cash flow generation at current oil prices ($60+ WTI breakeven)\n- Disciplined capital allocation and debt reduction focus\n\n### Key Strengths\n- **Financial Resilience**: Low breakeven costs (~$50-55 WTI)\n- **Geographic Diversification**: Operations across Permian Basin, Guyana, Kazakhstan\n- **Downstream Integration**: Refining operations provide hedge against crude volatility\n- **ESG Leadership**: Clear net-zero commitments and lower-carbon investments\n\n### Risk Factors\n- Commodity price volatility exposure\n- Regulatory pressures on traditional energy\n- Execution risks in major projects (Guyana expansion)\n\n### 2024 Catalysts\n- Guyana production ramp-up (targeting 1M+ bpd by 2027)\n- Permian Basin efficiency gains\n- Potential dividend increases and share buybacks\n\n---\n\n## 2. **NextEra Energy (NEE)**\n**Risk Rating: Low-Moderate | Investment Grade: A**\n\n### Investment Thesis\n- **Renewable Energy Leader** with largest wind/solar portfolio in North America\n- Regulated utility providing stable cash flows\n- Best-in-class execution on clean energy transition\n\n### Key Strengths\n- **Diversified Revenue**: ~60% regulated utilities, 40% renewable development\n- **Growth Pipeline**: 23+ GW of renewable projects in development\n- **Rate Base Growth**: 6-8% annual growth in regulated operations\n- **ESG Premium**: Leading ESG scores attract institutional capital\n\n### Risk Factors\n- Interest rate sensitivity (utility-like characteristics)\n- Regulatory changes affecting renewable incentives\n- Weather dependency for renewable generation\n\n### 2024 Catalysts\n- IRA tax credit optimization\n- Florida rate case outcomes\n- Continued renewable development acceleration\n\n---\n\n## 3. **ConocoPhillips (COP)**\n**Risk Rating: Moderate | Investment Grade: A-**\n\n### Investment Thesis\n- **Return-focused strategy** with variable dividend policy\n- Low-cost, high-return asset portfolio\n- Strong balance sheet with net cash position\n\n### Key Strengths\n- **Capital Discipline**: Strict return thresholds (>30% IRR)\n- **Variable Dividend**: Returns excess cash to shareholders\n- **Low-Cost Production**: Permian, Eagle Ford, Alaska operations\n- **Flexible Operations**: Can quickly adjust production based on prices\n\n### Risk Factors\n- Commodity price sensitivity\n- Concentration in North American unconventionals\n- Shorter reserve life vs. integrated peers\n\n### 2024 Catalysts\n- Continued Permian optimization\n- Potential special dividends if oil prices remain elevated\n- Strategic asset portfolio optimization\n\n---\n\n## Risk Assessment Framework\n\n### Market Risks\n- **Oil Price Volatility**: $70-90 WTI expected range for 2024\n- **Geopolitical Tensions**: Middle East, Russia-Ukraine impacts\n- **Demand Concerns**: China economic slowdown, recession risks\n\n### Sector-Specific Risks\n- **Energy Transition**: Accelerating renewable adoption\n- **Regulatory Pressure**: Carbon pricing, drilling restrictions\n- **Capital Allocation**: History of boom-bust cycles\n\n### Mitigation Strategies\n1. **Diversification**: Mix of traditional and renewable energy\n2. **Quality Focus**: Companies with strong balance sheets and cash generation\n3. **Dividend Sustainability**: Focus on covered, growing dividends\n\n## Portfolio Allocation Recommendation\n- **Conservative Investor**: 40% NEE, 35% CVX, 25% COP\n- **Moderate Investor**: 35% each, equal weighting\n- **Growth-Oriented**: 45% NEE, 30% COP, 25% CVX\n\n## Conclusion\nThese selections balance traditional energy exposure with renewable transition plays, emphasizing companies with strong cash generation, disciplined capital allocation, and sustainable competitive advantages. Monitor commodity prices, regulatory developments, and execution on strategic initiatives throughout 2024.\n\n**Disclaimer**: This analysis is for informational purposes only and should not be considered personalized investment advice. Consult with a qualified financial advisor before making investment decisions.",
|
||||
"timestamp": "2025-09-21T20:39:57.146852"
|
||||
}
|
||||
]
|
||||
}
|
@ -0,0 +1,27 @@
|
||||
{
|
||||
"run_id": "spreadsheet_swarm_run_b93a2946b074493f8fa34a47377b2625",
|
||||
"name": "Financial-Analysis-Swarm",
|
||||
"description": "A swarm of specialized financial analysis agents",
|
||||
"tasks_completed": 3,
|
||||
"number_of_agents": 3,
|
||||
"outputs": [
|
||||
{
|
||||
"agent_name": "Research-Agent",
|
||||
"task": "What are the top 3 energy stocks to invest in for 2024? Provide detailed analysis.",
|
||||
"result": "# Top 3 Energy Stocks for 2024 Investment Analysis\n\nAs Research-Agent, I'll provide a comprehensive analysis of three compelling energy investment opportunities for 2024, considering current market dynamics, financial fundamentals, and sector trends.\n\n## 1. **Chevron Corporation (CVX)**\n\n### Investment Thesis\nChevron stands out as a premium integrated oil major with exceptional capital discipline and shareholder-friendly policies.\n\n### Key Strengths\n- **Financial Fortress**: Strongest balance sheet among oil majors with minimal debt burden\n- **Dividend Aristocrat**: 37-year dividend growth streak with current yield ~3.2%\n- **Permian Basin Leadership**: Low-cost, high-return shale operations in prime acreage\n- **Downstream Integration**: Refining operations provide natural hedging against crude volatility\n- **Capital Allocation**: Committed to returning 75% of free cash flow to shareholders\n\n### 2024 Catalysts\n- Permian production growth of 10%+ expected\n- Potential for increased dividend and share buybacks\n- Strong free cash flow generation at $60+ oil prices\n\n### Risk Factors\n- Commodity price volatility exposure\n- ESG investor concerns affecting valuation multiples\n\n---\n\n## 2. **Kinder Morgan Inc. (KMI)**\n\n### Investment Thesis\nNorth America's largest energy infrastructure company offering stable, fee-based cash flows with growing renewable energy exposure.\n\n### Key Strengths\n- **Predictable Revenue**: ~95% of cash flows from fee-based contracts\n- **Essential Infrastructure**: 83,000 miles of pipelines serving critical energy transport\n- **Natural Gas Exposure**: Benefits from ongoing coal-to-gas power generation transition\n- **Renewable Integration**: Expanding CO2 transport and renewable natural gas capabilities\n- **Strong Dividend**: ~6.7% yield with coverage ratio improving\n\n### 2024 Catalysts\n- Completion of major pipeline projects boosting capacity\n- Increased natural gas export demand\n- Potential renewable energy infrastructure investments\n\n### Risk Factors\n- Regulatory challenges for new pipeline development\n- Long-term demand concerns for fossil fuel infrastructure\n\n---\n\n## 3. **NextEra Energy (NEE)**\n\n### Investment Thesis\nLeading utility with the world's largest renewable energy development platform, positioned for the energy transition.\n\n### Key Strengths\n- **Renewable Leadership**: Largest wind and solar operator in North America\n- **Regulated Utility Base**: Florida Power & Light provides stable earnings foundation\n- **Growth Platform**: NextEra Energy Resources drives above-average growth\n- **ESG Leadership**: Strong sustainability credentials attracting ESG-focused capital\n- **Dividend Growth**: 29-year dividend growth streak with 6-10% annual increases guided\n\n### 2024 Catalysts\n- Inflation Reduction Act benefits accelerating renewable development\n- Grid modernization investments in Florida\n- Potential green hydrogen and battery storage expansion\n\n### Risk Factors\n- Interest rate sensitivity due to capital-intensive nature\n- Regulatory changes affecting renewable incentives\n- Weather-related operational risks in Florida\n\n---\n\n## Portfolio Allocation Recommendation\n\n**Balanced Energy Exposure (100% allocation):**\n- **40% Chevron (CVX)**: Core position for oil exposure and income\n- **35% NextEra Energy (NEE)**: Growth-oriented renewable energy play\n- **25% Kinder Morgan (KMI)**: Infrastructure stability and high yield\n\n## Market Context & Timing\n\n**Favorable Factors for 2024:**\n- Energy sector trading at attractive valuations vs. historical averages\n- Geopolitical tensions supporting energy security premiums\n- Underinvestment in traditional energy creating supply constraints\n- Growing recognition of energy transition requiring decades, not years\n\n**Key Monitoring Points:**\n- Federal Reserve policy impacts on interest rates\n- Global economic growth affecting energy demand\n- Geopolitical developments in major energy-producing regions\n- Regulatory changes affecting different energy subsectors\n\nThis diversified approach captures traditional energy cash flows, infrastructure stability, and renewable energy growth while managing sector-specific risks through balanced exposure.",
|
||||
"timestamp": "2025-09-21T20:39:11.459523"
|
||||
},
|
||||
{
|
||||
"agent_name": "Technical-Agent",
|
||||
"task": "What are the top 3 energy stocks to invest in for 2024? Provide detailed analysis.",
|
||||
"result": "I appreciate your interest in energy sector investments, but I need to provide an important disclaimer upfront: **I cannot provide specific investment recommendations or financial advice.** Investment decisions should always be made in consultation with qualified financial advisors and based on your individual financial situation, risk tolerance, and investment goals.\n\nHowever, I can offer an educational analysis of the energy sector landscape and key factors to consider when evaluating energy investments for 2024:\n\n## Energy Sector Analysis Framework for 2024\n\n### Key Market Dynamics to Consider:\n\n**1. Energy Transition Trends**\n- Continued growth in renewable energy adoption\n- Government policies supporting clean energy initiatives\n- Corporate ESG commitments driving demand for sustainable energy\n\n**2. Traditional Energy Factors**\n- Oil and gas price volatility\n- Geopolitical influences on energy markets\n- Supply chain considerations and production capacity\n\n**3. Technology Integration**\n- Digital transformation in energy operations\n- Energy storage solutions advancement\n- Grid modernization investments\n\n### Categories of Energy Investments to Research:\n\n**Renewable Energy Leaders**\n- Companies with strong solar, wind, and hydroelectric portfolios\n- Firms investing heavily in energy storage technology\n- Utilities transitioning to clean energy sources\n\n**Diversified Energy Companies**\n- Integrated oil companies with renewable energy divisions\n- Companies balancing traditional and alternative energy portfolios\n- Firms with strong cash flow management and dividend histories\n\n**Energy Infrastructure**\n- Pipeline and transmission companies\n- Energy storage and grid technology providers\n- Companies supporting the energy transition infrastructure\n\n### Due Diligence Factors:\n- Financial health and debt management\n- Management track record and strategic vision\n- Regulatory environment and policy impacts\n- Competitive positioning and market share\n- ESG ratings and sustainability commitments\n\n**Recommendation:** Consult with a financial advisor who can analyze your specific situation and provide personalized investment guidance based on current market conditions and your investment objectives.",
|
||||
"timestamp": "2025-09-21T20:39:11.459523"
|
||||
},
|
||||
{
|
||||
"agent_name": "Risk-Agent",
|
||||
"task": "What are the top 3 energy stocks to invest in for 2024? Provide detailed analysis.",
|
||||
"result": "# Top 3 Energy Stocks for 2024 Investment Analysis\n\n## Important Risk Disclaimer\nAs Risk-Agent, I must emphasize that this analysis is for educational purposes only and does not constitute financial advice. Energy sector investments carry significant risks including commodity price volatility, regulatory changes, and market sentiment shifts. Always consult with qualified financial advisors and conduct your own due diligence.\n\n## Top 3 Energy Stock Recommendations for 2024\n\n### 1. **Chevron Corporation (CVX)**\n\n**Investment Thesis:**\n- **Financial Strength**: Robust balance sheet with low debt-to-equity ratio (~0.25)\n- **Dividend Reliability**: 36-year dividend growth streak, current yield ~3.2%\n- **Operational Excellence**: Low-cost production assets in Permian Basin\n- **Capital Discipline**: Committed to maintaining capital expenditure discipline\n\n**Key Metrics & Analysis:**\n- **Free Cash Flow**: Strong FCF generation at $50+ oil prices\n- **Breakeven Costs**: Among lowest in industry at ~$40/barrel\n- **Geographic Diversification**: Operations across US, Kazakhstan, Australia\n- **ESG Progress**: Investing in carbon capture and lower-carbon technologies\n\n**Risk Factors:**\n- Oil price volatility exposure\n- Regulatory pressure on fossil fuel operations\n- Transition risk as world moves toward renewables\n\n### 2. **NextEra Energy (NEE)**\n\n**Investment Thesis:**\n- **Renewable Leadership**: Largest renewable energy generator in North America\n- **Regulated Utility Base**: Florida Power & Light provides stable cash flows\n- **Growth Pipeline**: 30+ GW of renewable development pipeline\n- **ESG Leadership**: Strong environmental credentials attracting ESG-focused capital\n\n**Key Metrics & Analysis:**\n- **Dividend Growth**: 29-year dividend growth streak, ~2.8% yield\n- **Rate Base Growth**: Regulated utility growing at 6-8% annually\n- **Renewable Margins**: High-margin renewable contracts with long-term PPAs\n- **Technology Leadership**: Early mover in battery storage and green hydrogen\n\n**Risk Factors:**\n- Interest rate sensitivity due to capital-intensive nature\n- Regulatory changes affecting renewable incentives\n- Weather-related operational risks in Florida\n\n### 3. **ConocoPhillips (COP)**\n\n**Investment Thesis:**\n- **Return of Capital Focus**: Industry-leading shareholder return program\n- **Low-Cost Operations**: Unconventional resource expertise with low breakevens\n- **Variable Dividend**: Flexible dividend policy tied to commodity prices\n- **Portfolio Quality**: High-return, short-cycle assets\n\n**Key Metrics & Analysis:**\n- **Shareholder Returns**: Targeting 50%+ of CFO returned to shareholders\n- **Operational Efficiency**: Breakeven costs ~$40/barrel WTI\n- **Balance Sheet**: Net cash position providing financial flexibility\n- **Production Growth**: Modest, profitable growth in key basins\n\n**Risk Factors:**\n- Commodity price cyclicality\n- Variable dividend may not appeal to income-focused investors\n- Exposure to geopolitical risks in international operations\n\n## Sector Risk Assessment\n\n### Key Risks to Monitor:\n1. **Commodity Price Volatility**: Oil and gas prices remain primary driver\n2. **Energy Transition**: Long-term demand concerns for fossil fuels\n3. **Regulatory Environment**: Potential for increased environmental regulations\n4. **Geopolitical Tensions**: Supply disruption risks\n5. **Interest Rate Environment**: Impact on capital-intensive projects\n\n### Risk Mitigation Strategies:\n- **Diversification**: Don't concentrate more than 5-10% in energy sector\n- **Dollar-Cost Averaging**: Spread purchases over time to reduce timing risk\n- **Regular Rebalancing**: Monitor positions and adjust based on changing fundamentals\n- **Stay Informed**: Track commodity prices, regulatory changes, and company-specific developments\n\n## Conclusion\n\nThese three stocks represent different approaches to energy investing: traditional integrated oil (CVX), renewable transition leader (NEE), and pure-play E&P with shareholder focus (COP). Each offers distinct risk-return profiles suitable for different investment objectives.\n\n**Remember**: Energy stocks are inherently volatile and cyclical. Consider your risk tolerance, investment timeline, and portfolio diversification before making investment decisions. Past performance does not guarantee future results.\n\nWould you like me to elaborate on any specific aspect of this analysis or discuss additional risk management strategies for energy sector investing?",
|
||||
"timestamp": "2025-09-21T20:39:11.459523"
|
||||
}
|
||||
]
|
||||
}
|
@ -0,0 +1,6 @@
|
||||
# RAG (Retrieval Augmented Generation) Examples
|
||||
|
||||
This directory contains examples demonstrating RAG implementations and vector database integrations in Swarms.
|
||||
|
||||
## Qdrant RAG
|
||||
- [qdrant_rag_example.py](qdrant_rag_example.py) - Complete Qdrant RAG implementation
|
@ -0,0 +1,12 @@
|
||||
# Reasoning Agents Examples
|
||||
|
||||
This directory contains examples demonstrating advanced reasoning capabilities and agent evaluation systems in Swarms.
|
||||
|
||||
## Agent Judge Examples
|
||||
- [example1_basic_evaluation.py](agent_judge_examples/example1_basic_evaluation.py) - Basic agent evaluation
|
||||
- [example2_technical_evaluation.py](agent_judge_examples/example2_technical_evaluation.py) - Technical evaluation criteria
|
||||
- [example3_creative_evaluation.py](agent_judge_examples/example3_creative_evaluation.py) - Creative evaluation patterns
|
||||
|
||||
## O3 Integration
|
||||
- [example_o3.py](example_o3.py) - O3 model integration example
|
||||
- [o3_agent.py](o3_agent.py) - O3 agent implementation
|
@ -0,0 +1,115 @@
|
||||
# Single Agent Examples
|
||||
|
||||
This directory contains examples demonstrating single agent patterns, configurations, and use cases in Swarms.
|
||||
|
||||
## Demos
|
||||
- [insurance_agent.py](demos/insurance_agent.py) - Insurance processing agent
|
||||
- [persistent_legal_agent.py](demos/persistent_legal_agent.py) - Legal document processing agent
|
||||
|
||||
## External Agents
|
||||
- [custom_agent_example.py](external_agents/custom_agent_example.py) - Custom agent implementation
|
||||
- [openai_assistant_wrapper.py](external_agents/openai_assistant_wrapper.py) - OpenAI Assistant integration
|
||||
|
||||
## LLM Integrations
|
||||
|
||||
### Azure
|
||||
- [azure_agent_api_verison.py](llms/azure_agent_api_verison.py) - Azure API version handling
|
||||
- [azure_agent.py](llms/azure_agent.py) - Azure OpenAI integration
|
||||
- [azure_model_support.py](llms/azure_model_support.py) - Azure model support
|
||||
|
||||
### Claude
|
||||
- [claude_4_example.py](llms/claude_examples/claude_4_example.py) - Claude 4 integration
|
||||
- [claude_4.py](llms/claude_examples/claude_4.py) - Claude 4 implementation
|
||||
- [swarms_claude_example.py](llms/claude_examples/swarms_claude_example.py) - Swarms Claude integration
|
||||
|
||||
### DeepSeek
|
||||
- [deepseek_r1.py](llms/deepseek_examples/deepseek_r1.py) - DeepSeek R1 model
|
||||
- [fast_r1_groq.py](llms/deepseek_examples/fast_r1_groq.py) - Fast R1 with Groq
|
||||
- [grok_deepseek_agent.py](llms/deepseek_examples/grok_deepseek_agent.py) - Grok DeepSeek integration
|
||||
|
||||
### Mistral
|
||||
- [mistral_example.py](llms/mistral_example.py) - Mistral model integration
|
||||
|
||||
### OpenAI
|
||||
- [4o_mini_demo.py](llms/openai_examples/4o_mini_demo.py) - GPT-4o Mini demonstration
|
||||
- [reasoning_duo_batched.py](llms/openai_examples/reasoning_duo_batched.py) - Batched reasoning with OpenAI
|
||||
- [test_async_litellm.py](llms/openai_examples/test_async_litellm.py) - Async LiteLLM testing
|
||||
|
||||
### Qwen
|
||||
- [qwen_3_base.py](llms/qwen_3_base.py) - Qwen 3 base model
|
||||
|
||||
## Onboarding
|
||||
- [agents.yaml](onboard/agents.yaml) - Agent configuration file
|
||||
- [onboard-basic.py](onboard/onboard-basic.py) - Basic onboarding example
|
||||
|
||||
## RAG (Retrieval Augmented Generation)
|
||||
- [full_agent_rag_example.py](rag/full_agent_rag_example.py) - Complete RAG implementation
|
||||
- [pinecone_example.py](rag/pinecone_example.py) - Pinecone vector database integration
|
||||
- [qdrant_agent.py](rag/qdrant_agent.py) - Qdrant vector database agent
|
||||
- [qdrant_rag_example.py](rag/qdrant_rag_example.py) - Qdrant RAG implementation
|
||||
- [simple_example.py](rag/simple_example.py) - Simple RAG example
|
||||
- [README.md](rag/README.md) - RAG documentation
|
||||
|
||||
## Reasoning Agents
|
||||
- [agent_judge_evaluation_criteria_example.py](reasoning_agent_examples/agent_judge_evaluation_criteria_example.py) - Evaluation criteria for agent judging
|
||||
- [agent_judge_example.py](reasoning_agent_examples/agent_judge_example.py) - Agent judging system
|
||||
- [consistency_agent.py](reasoning_agent_examples/consistency_agent.py) - Consistency checking agent
|
||||
- [consistency_example.py](reasoning_agent_examples/consistency_example.py) - Consistency example
|
||||
- [gpk_agent.py](reasoning_agent_examples/gpk_agent.py) - GPK reasoning agent
|
||||
- [iterative_agent.py](reasoning_agent_examples/iterative_agent.py) - Iterative reasoning agent
|
||||
- [malt_example.py](reasoning_agent_examples/malt_example.py) - MALT reasoning example
|
||||
- [reasoning_agent_router_now.py](reasoning_agent_examples/reasoning_agent_router_now.py) - Current reasoning router
|
||||
- [reasoning_agent_router.py](reasoning_agent_examples/reasoning_agent_router.py) - Reasoning agent router
|
||||
- [reasoning_duo_example.py](reasoning_agent_examples/reasoning_duo_example.py) - Two-agent reasoning
|
||||
- [reasoning_duo_test.py](reasoning_agent_examples/reasoning_duo_test.py) - Reasoning duo testing
|
||||
- [reasoning_duo.py](reasoning_agent_examples/reasoning_duo.py) - Reasoning duo implementation
|
||||
|
||||
## Tools Integration
|
||||
- [exa_search_agent.py](tools/exa_search_agent.py) - Exa search integration
|
||||
- [example_async_vs_multithread.py](tools/example_async_vs_multithread.py) - Async vs multithreading comparison
|
||||
- [litellm_tool_example.py](tools/litellm_tool_example.py) - LiteLLM tool integration
|
||||
- [multi_tool_usage_agent.py](tools/multi_tool_usage_agent.py) - Multi-tool agent
|
||||
- [new_tools_examples.py](tools/new_tools_examples.py) - Latest tool examples
|
||||
- [omni_modal_agent.py](tools/omni_modal_agent.py) - Omni-modal agent
|
||||
- [swarms_of_browser_agents.py](tools/swarms_of_browser_agents.py) - Browser automation swarms
|
||||
- [swarms_tools_example.py](tools/swarms_tools_example.py) - Swarms tools integration
|
||||
- [together_deepseek_agent.py](tools/together_deepseek_agent.py) - Together AI DeepSeek integration
|
||||
|
||||
### Solana Tools
|
||||
- [solana_tool.py](tools/solana_tool/solana_tool.py) - Solana blockchain integration
|
||||
- [solana_tool_test.py](tools/solana_tool/solana_tool_test.py) - Solana tool testing
|
||||
|
||||
### Structured Outputs
|
||||
- [example_meaning_of_life_agents.py](tools/structured_outputs/example_meaning_of_life_agents.py) - Meaning of life example
|
||||
- [structured_outputs_example.py](tools/structured_outputs/structured_outputs_example.py) - Structured output examples
|
||||
|
||||
### Tools Examples
|
||||
- [dex_screener.py](tools/tools_examples/dex_screener.py) - DEX screener tool
|
||||
- [financial_news_agent.py](tools/tools_examples/financial_news_agent.py) - Financial news agent
|
||||
- [simple_tool_example.py](tools/tools_examples/simple_tool_example.py) - Simple tool usage
|
||||
- [swarms_tool_example_simple.py](tools/tools_examples/swarms_tool_example_simple.py) - Simple Swarms tool
|
||||
|
||||
## Utils
|
||||
- [async_agent.py](utils/async_agent.py) - Async agent implementation
|
||||
- [dynamic_context_window.py](utils/dynamic_context_window.py) - Dynamic context window management
|
||||
- [fallback_test.py](utils/fallback_test.py) - Fallback mechanism testing
|
||||
- [grok_4_agent.py](utils/grok_4_agent.py) - Grok 4 agent implementation
|
||||
- [handoffs_example.py](utils/handoffs_example.py) - Agent handoff examples
|
||||
- [list_agent_output_types.py](utils/list_agent_output_types.py) - Output type listing
|
||||
- [markdown_agent.py](utils/markdown_agent.py) - Markdown processing agent
|
||||
- [xml_output_example.py](utils/xml_output_example.py) - XML output example
|
||||
|
||||
### Transform Prompts
|
||||
- [transforms_agent_example.py](utils/transform_prompts/transforms_agent_example.py) - Prompt transformation agent
|
||||
- [transforms_examples.py](utils/transform_prompts/transforms_examples.py) - Prompt transformation examples
|
||||
|
||||
## Vision
|
||||
- [anthropic_vision_test.py](vision/anthropic_vision_test.py) - Anthropic vision testing
|
||||
- [image_batch_example.py](vision/image_batch_example.py) - Batch image processing
|
||||
- [multimodal_example.py](vision/multimodal_example.py) - Multimodal agent example
|
||||
- [multiple_image_processing.py](vision/multiple_image_processing.py) - Multiple image processing
|
||||
- [vision_test.py](vision/vision_test.py) - Vision testing
|
||||
- [vision_tools.py](vision/vision_tools.py) - Vision tools integration
|
||||
|
||||
## Main Files
|
||||
- [simple_agent.py](simple_agent.py) - Basic single agent example
|
@ -1,20 +1,14 @@
|
||||
from swarms import Agent
|
||||
from swarms.prompts.finance_agent_sys_prompt import (
|
||||
FINANCIAL_AGENT_SYS_PROMPT,
|
||||
)
|
||||
from swarms_tools import yahoo_finance_api
|
||||
from swarms_tools.finance.okx_tool import okx_api_tool
|
||||
|
||||
# Initialize the agent
|
||||
agent = Agent(
|
||||
agent_name="Financial-Analysis-Agent",
|
||||
agent_description="Personal finance advisor agent",
|
||||
system_prompt=FINANCIAL_AGENT_SYS_PROMPT,
|
||||
max_loops=1,
|
||||
model_name="gpt-4o-mini",
|
||||
tools=[yahoo_finance_api],
|
||||
tools=[okx_api_tool],
|
||||
dynamic_temperature_enabled=True,
|
||||
)
|
||||
|
||||
agent.run(
|
||||
"Fetch the data for nvidia and tesla both with the yahoo finance api"
|
||||
)
|
||||
agent.run("fetch the current price of bitcoin with okx")
|
||||
|
@ -0,0 +1,23 @@
|
||||
from swarms.structs.agent import Agent
|
||||
|
||||
# Initialize the agent
|
||||
agent = Agent(
|
||||
agent_name="Quantitative-Trading-Agent",
|
||||
agent_description="Advanced quantitative trading and algorithmic analysis agent",
|
||||
model_name="claude-sonnetfwoeewe-4-20250514",
|
||||
dynamic_temperature_enabled=True,
|
||||
max_loops=1,
|
||||
fallback_models=[
|
||||
"gpt-4o-mini",
|
||||
],
|
||||
dynamic_context_window=True,
|
||||
streaming_on=False,
|
||||
print_on=True,
|
||||
verbose=False,
|
||||
)
|
||||
|
||||
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,63 @@
|
||||
from swarms.structs.agent import Agent
|
||||
|
||||
# Agent 1: Risk Metrics Calculator
|
||||
risk_metrics_agent = Agent(
|
||||
agent_name="Risk-Metrics-Calculator",
|
||||
agent_description="Calculates key risk metrics like VaR, Sharpe ratio, and volatility",
|
||||
system_prompt="""You are a risk metrics specialist. Calculate and explain:
|
||||
- Value at Risk (VaR)
|
||||
- Sharpe ratio
|
||||
- Volatility
|
||||
- Maximum drawdown
|
||||
- Beta coefficient
|
||||
|
||||
Provide clear, numerical results with brief explanations.""",
|
||||
max_loops=1,
|
||||
model_name="gpt-4o-mini",
|
||||
dynamic_temperature_enabled=True,
|
||||
)
|
||||
|
||||
|
||||
# Agent 3: Market Risk Monitor
|
||||
market_risk_agent = Agent(
|
||||
agent_name="Market-Risk-Monitor",
|
||||
agent_description="Monitors market conditions and identifies risk factors",
|
||||
system_prompt="""You are a market risk monitor. Identify and assess:
|
||||
- Market volatility trends
|
||||
- Economic risk factors
|
||||
- Geopolitical risks
|
||||
- Interest rate risks
|
||||
- Currency risks
|
||||
|
||||
Provide current risk alerts and trends.""",
|
||||
max_loops=1,
|
||||
dynamic_temperature_enabled=True,
|
||||
)
|
||||
|
||||
|
||||
# Agent 2: Portfolio Risk Analyzer
|
||||
portfolio_risk_agent = Agent(
|
||||
agent_name="Portfolio-Risk-Analyzer",
|
||||
agent_description="Analyzes portfolio diversification and concentration risk",
|
||||
system_prompt="""You are a portfolio risk analyst. Focus on:
|
||||
- Portfolio diversification analysis
|
||||
- Concentration risk assessment
|
||||
- Correlation analysis
|
||||
- Sector/asset allocation risk
|
||||
- Liquidity risk evaluation
|
||||
|
||||
Provide actionable insights for risk reduction.""",
|
||||
max_loops=1,
|
||||
dynamic_temperature_enabled=True,
|
||||
handoffs=[
|
||||
risk_metrics_agent,
|
||||
market_risk_agent,
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
out = portfolio_risk_agent.run(
|
||||
"Calculate VaR and Sharpe ratio for a portfolio with 15% annual return and 20% volatility using the risk metrics agent and market risk agent"
|
||||
)
|
||||
|
||||
print(out)
|
@ -0,0 +1,22 @@
|
||||
# Swarms API Examples
|
||||
|
||||
This directory contains examples demonstrating how to use the Swarms API for various agent operations.
|
||||
|
||||
## Agent Overview
|
||||
- [agent_overview.py](agent_overview.py) - Comprehensive overview of agent capabilities
|
||||
|
||||
## Batch Processing
|
||||
- [batch_example.py](batch_example.py) - Batch processing with multiple agents
|
||||
|
||||
## Client Integration
|
||||
- [client_example.py](client_example.py) - Basic client usage example
|
||||
|
||||
## Team Examples
|
||||
- [hospital_team.py](hospital_team.py) - Hospital management team simulation
|
||||
- [legal_team.py](legal_team.py) - Legal team collaboration example
|
||||
|
||||
## Analysis Examples
|
||||
- [icd_ten_analysis.py](icd_ten_analysis.py) - ICD-10 medical code analysis
|
||||
|
||||
## Rate Limiting
|
||||
- [rate_limits.py](rate_limits.py) - Rate limiting and throttling examples
|
@ -0,0 +1,45 @@
|
||||
# Tools Examples
|
||||
|
||||
This directory contains examples demonstrating various tool integrations and usage patterns in Swarms.
|
||||
|
||||
## Agent as Tools
|
||||
- [agent_as_tools.py](agent_as_tools.py) - Using agents as tools in workflows
|
||||
|
||||
## Base Tool Examples
|
||||
- [base_tool_examples.py](base_tool_examples/base_tool_examples.py) - Core base tool functionality
|
||||
- [conver_funcs_to_schema.py](base_tool_examples/conver_funcs_to_schema.py) - Function to schema conversion
|
||||
- [convert_basemodels.py](base_tool_examples/convert_basemodels.py) - BaseModel conversion utilities
|
||||
- [exa_search_test.py](base_tool_examples/exa_search_test.py) - Exa search testing
|
||||
- [example_usage.py](base_tool_examples/example_usage.py) - Basic usage examples
|
||||
- [schema_validation_example.py](base_tool_examples/schema_validation_example.py) - Schema validation
|
||||
- [test_anthropic_specific.py](base_tool_examples/test_anthropic_specific.py) - Anthropic-specific testing
|
||||
- [test_base_tool_comprehensive_fixed.py](base_tool_examples/test_base_tool_comprehensive_fixed.py) - Comprehensive testing (fixed)
|
||||
- [test_base_tool_comprehensive.py](base_tool_examples/test_base_tool_comprehensive.py) - Comprehensive testing
|
||||
- [test_function_calls_anthropic.py](base_tool_examples/test_function_calls_anthropic.py) - Anthropic function calls
|
||||
- [test_function_calls.py](base_tool_examples/test_function_calls.py) - Function call testing
|
||||
|
||||
## Browser Integration
|
||||
- [browser_use_as_tool.py](browser_use_as_tool.py) - Browser automation as a tool
|
||||
- [browser_use_demo.py](browser_use_demo.py) - Browser automation demonstration
|
||||
|
||||
## Claude Integration
|
||||
- [claude_as_a_tool.py](claude_as_a_tool.py) - Using Claude as a tool
|
||||
|
||||
## Exa Search
|
||||
- [exa_search_agent.py](exa_search_agent.py) - Exa search agent implementation
|
||||
|
||||
## Firecrawl Integration
|
||||
- [firecrawl_agents_example.py](firecrawl_agents_example.py) - Firecrawl web scraping agents
|
||||
|
||||
## Multi-Tool Usage
|
||||
- [many_tool_use_demo.py](multii_tool_use/many_tool_use_demo.py) - Multiple tool usage demonstration
|
||||
- [multi_tool_anthropic.py](multii_tool_use/multi_tool_anthropic.py) - Multi-tool with Anthropic
|
||||
|
||||
## Stagehand Integration
|
||||
- [1_stagehand_wrapper_agent.py](stagehand/1_stagehand_wrapper_agent.py) - Stagehand wrapper agent
|
||||
- [2_stagehand_tools_agent.py](stagehand/2_stagehand_tools_agent.py) - Stagehand tools agent
|
||||
- [3_stagehand_mcp_agent.py](stagehand/3_stagehand_mcp_agent.py) - Stagehand MCP agent
|
||||
- [4_stagehand_multi_agent_workflow.py](stagehand/4_stagehand_multi_agent_workflow.py) - Multi-agent workflow
|
||||
- [README.md](stagehand/README.md) - Stagehand documentation
|
||||
- [requirements.txt](stagehand/requirements.txt) - Stagehand dependencies
|
||||
- [tests/](stagehand/tests/) - Stagehand testing suite
|
@ -0,0 +1,6 @@
|
||||
# UI Examples
|
||||
|
||||
This directory contains user interface examples and implementations for Swarms.
|
||||
|
||||
## Chat Interface
|
||||
- [chat.py](chat.py) - Chat interface implementation
|
@ -0,0 +1,40 @@
|
||||
# Utils Examples
|
||||
|
||||
This directory contains utility examples and helper functions for various Swarms operations.
|
||||
|
||||
## Agent Loader
|
||||
- [agent_loader_demo.py](agent_loader/agent_loader_demo.py) - Agent loading demonstration
|
||||
- [claude_code_compatible.py](agent_loader/claude_code_compatible.py) - Claude code compatibility
|
||||
- [finance_advisor.md](agent_loader/finance_advisor.md) - Finance advisor documentation
|
||||
- [multi_agents_loader_demo.py](agent_loader/multi_agents_loader_demo.py) - Multi-agent loading demo
|
||||
|
||||
## Communication Examples
|
||||
- [duckdb_agent.py](communication_examples/duckdb_agent.py) - DuckDB database agent
|
||||
- [pulsar_conversation.py](communication_examples/pulsar_conversation.py) - Apache Pulsar messaging
|
||||
- [redis_conversation.py](communication_examples/redis_conversation.py) - Redis-based conversations
|
||||
- [sqlite_conversation.py](communication_examples/sqlite_conversation.py) - SQLite conversation storage
|
||||
|
||||
## Concurrent Wrapper
|
||||
- [concurrent_wrapper_examples.py](concurrent_wrapper_examples.py) - Concurrent execution wrapper examples
|
||||
|
||||
## Miscellaneous
|
||||
- [agent_map_test.py](misc/agent_map_test.py) - Agent mapping testing
|
||||
- [conversation_simple.py](misc/conversation_simple.py) - Simple conversation handling
|
||||
- [conversation_test_truncate.py](misc/conversation_test_truncate.py) - Conversation truncation testing
|
||||
- [conversation_test.py](misc/conversation_test.py) - Conversation testing
|
||||
- [csvagent_example.py](misc/csvagent_example.py) - CSV processing agent
|
||||
- [dict_to_table.py](misc/dict_to_table.py) - Dictionary to table conversion
|
||||
- [swarm_matcher_example.py](misc/swarm_matcher_example.py) - Swarm matching utilities
|
||||
- [test_load_conversation.py](misc/test_load_conversation.py) - Conversation loading tests
|
||||
- [visualizer_test.py](misc/visualizer_test.py) - Visualization testing
|
||||
|
||||
### AOP (Aspect-Oriented Programming)
|
||||
- [client.py](misc/aop/client.py) - AOP client implementation
|
||||
- [test_aop.py](misc/aop/test_aop.py) - AOP testing
|
||||
|
||||
### Conversation Structure
|
||||
- [conversation_example_supabase.py](misc/conversation_structure/conversation_example_supabase.py) - Supabase conversation example
|
||||
|
||||
## Telemetry
|
||||
- [class_method_example.py](telemetry/class_method_example.py) - Class method telemetry
|
||||
- [example_decorator_usage.py](telemetry/example_decorator_usage.py) - Decorator usage examples
|
@ -0,0 +1,15 @@
|
||||
# Workshop Examples
|
||||
|
||||
This directory contains examples from workshops and educational sessions.
|
||||
|
||||
## Workshop September 20
|
||||
- [agent_tools_dict_example.py](workshop_sep_20/agent_tools_dict_example.py) - Agent tools dictionary example
|
||||
- [batched_grid_simple_example.py](workshop_sep_20/batched_grid_simple_example.py) - Simple batched grid example
|
||||
- [geo_guesser_agent.py](workshop_sep_20/geo_guesser_agent.py) - Geographic location guessing agent
|
||||
- [jarvis_agent.py](workshop_sep_20/jarvis_agent.py) - Jarvis AI assistant
|
||||
- [same_task_example.py](workshop_sep_20/same_task_example.py) - Same task execution example
|
||||
|
||||
### Sample Images
|
||||
- [hk.jpg](workshop_sep_20/hk.jpg) - Hong Kong sample image
|
||||
- [miami.jpg](workshop_sep_20/miami.jpg) - Miami sample image
|
||||
- [mountains.jpg](workshop_sep_20/mountains.jpg) - Mountains sample image
|
@ -0,0 +1,17 @@
|
||||
from swarms import Agent
|
||||
|
||||
|
||||
# Initialize the agent
|
||||
agent = Agent(
|
||||
agent_name="Financial-Analysis-Agent",
|
||||
agent_description="Personal finance advisor agent",
|
||||
max_loops=1,
|
||||
output_type="final",
|
||||
mcp_url="http://0.0.0.0:8000/mcp",
|
||||
)
|
||||
|
||||
out = agent.run(
|
||||
"Use the multiply tool to multiply 3 and 4 together. Look at the tools available to you.",
|
||||
)
|
||||
|
||||
print(agent.short_memory.get_str())
|
@ -0,0 +1,42 @@
|
||||
from swarms import Agent
|
||||
from swarms.structs.batched_grid_workflow import BatchedGridWorkflow
|
||||
|
||||
# Initialize the ETF-focused agent
|
||||
agent = Agent(
|
||||
agent_name="ETF-Research-Agent",
|
||||
agent_description="Specialized agent for researching, analyzing, and recommending Exchange-Traded Funds (ETFs) across various sectors and markets.",
|
||||
model_name="groq/moonshotai/kimi-k2-instruct",
|
||||
dynamic_temperature_enabled=True,
|
||||
max_loops=1,
|
||||
dynamic_context_window=True,
|
||||
)
|
||||
|
||||
agent_two = Agent(
|
||||
agent_name="ETF-Research-Agent-2",
|
||||
agent_description="Specialized agent for researching, analyzing, and recommending Exchange-Traded Funds (ETFs) across various sectors and markets.",
|
||||
model_name="groq/moonshotai/kimi-k2-instruct",
|
||||
dynamic_temperature_enabled=True,
|
||||
max_loops=1,
|
||||
dynamic_context_window=True,
|
||||
)
|
||||
|
||||
|
||||
# Create workflow with default settings
|
||||
workflow = BatchedGridWorkflow(
|
||||
name="ETF-Research-Workflow",
|
||||
description="Research and recommend ETFs across various sectors and markets.",
|
||||
agents=[agent, agent_two],
|
||||
max_loops=1,
|
||||
)
|
||||
|
||||
# Define simple tasks
|
||||
tasks = [
|
||||
"What are the best GOLD ETFs?",
|
||||
"What are the best american energy ETFs?",
|
||||
]
|
||||
|
||||
# Run the workflow
|
||||
result = workflow.run(tasks)
|
||||
|
||||
|
||||
print(result)
|
@ -0,0 +1,27 @@
|
||||
from swarms import Agent
|
||||
|
||||
|
||||
SYSTEM_PROMPT = (
|
||||
"You are an expert in image geolocalization. Given an image, provide the most likely location it was taken. "
|
||||
"Analyze visual cues such as architecture, landscape, vegetation, weather patterns, cultural elements, "
|
||||
"and any other geographical indicators to determine the precise location. Provide your reasoning and "
|
||||
"confidence level for your prediction."
|
||||
)
|
||||
|
||||
# Agent for image geolocalization
|
||||
agent = Agent(
|
||||
agent_name="Geo-Guesser-Agent",
|
||||
agent_description="Expert agent specialized in image geolocalization, capable of identifying geographical locations from visual cues in images.",
|
||||
model_name="gemini/gemini-2.5-flash-image-preview",
|
||||
dynamic_temperature_enabled=True,
|
||||
max_loops=1,
|
||||
dynamic_context_window=True,
|
||||
retry_interval=1,
|
||||
)
|
||||
|
||||
out = agent.run(
|
||||
task=f"{SYSTEM_PROMPT}",
|
||||
img="mountains.jpg",
|
||||
)
|
||||
|
||||
print(out)
|
After Width: | Height: | Size: 82 KiB |
@ -0,0 +1,25 @@
|
||||
from swarms import Agent
|
||||
|
||||
|
||||
SYSTEM_PROMPT = (
|
||||
"You are a location-based AR experience generator. Highlight points of interest in this image and annotate relevant information about it. "
|
||||
"Generate the new image only."
|
||||
)
|
||||
|
||||
# Agent for AR annotation
|
||||
agent = Agent(
|
||||
agent_name="Tactical-Strategist-Agent",
|
||||
agent_description="Agent specialized in tactical strategy, scenario analysis, and actionable recommendations for complex situations.",
|
||||
model_name="gemini/gemini-2.5-flash-image-preview", # "gemini/gemini-2.5-flash-image-preview",
|
||||
dynamic_temperature_enabled=True,
|
||||
max_loops=1,
|
||||
dynamic_context_window=True,
|
||||
retry_interval=1,
|
||||
verbose=True,
|
||||
)
|
||||
|
||||
|
||||
out = agent.run(
|
||||
task=f"{SYSTEM_PROMPT} \n\n Annotate all the tallest buildings in the image",
|
||||
img="hk.jpg",
|
||||
)
|
After Width: | Height: | Size: 151 KiB |
After Width: | Height: | Size: 1.2 MiB |
@ -0,0 +1,38 @@
|
||||
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.
|
||||
|
||||
Args:
|
||||
num_agents: Number of agents to create
|
||||
|
||||
Returns:
|
||||
List of Agent instances
|
||||
"""
|
||||
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 creative story about sci fi with no cliches. Make it 1000 words."
|
||||
|
||||
results = run_agents_concurrently_uvloop(agents=agents, task=task)
|
||||
|
||||
|
||||
print(results)
|
@ -0,0 +1,46 @@
|
||||
from swarms import Agent
|
||||
from swarms.structs.spreadsheet_swarm import SpreadSheetSwarm
|
||||
|
||||
# Example 1: Using pre-configured agents
|
||||
agents = [
|
||||
Agent(
|
||||
agent_name="Research-Agent",
|
||||
agent_description="Specialized in market research and analysis",
|
||||
model_name="claude-sonnet-4-20250514",
|
||||
dynamic_temperature_enabled=True,
|
||||
max_loops=1,
|
||||
streaming_on=False,
|
||||
),
|
||||
Agent(
|
||||
agent_name="Technical-Agent",
|
||||
agent_description="Expert in technical analysis and trading strategies",
|
||||
model_name="claude-sonnet-4-20250514",
|
||||
dynamic_temperature_enabled=True,
|
||||
max_loops=1,
|
||||
streaming_on=False,
|
||||
),
|
||||
Agent(
|
||||
agent_name="Risk-Agent",
|
||||
agent_description="Focused on risk assessment and portfolio management",
|
||||
model_name="claude-sonnet-4-20250514",
|
||||
dynamic_temperature_enabled=True,
|
||||
max_loops=1,
|
||||
streaming_on=False,
|
||||
),
|
||||
]
|
||||
|
||||
# Initialize the SpreadSheetSwarm with agents
|
||||
swarm = SpreadSheetSwarm(
|
||||
name="Financial-Analysis-Swarm",
|
||||
description="A swarm of specialized financial analysis agents",
|
||||
agents=agents,
|
||||
max_loops=1,
|
||||
autosave=False,
|
||||
workspace_dir="./swarm_outputs",
|
||||
)
|
||||
|
||||
# Run all agents with the same task
|
||||
task = "What are the top 3 energy stocks to invest in for 2024? Provide detailed analysis."
|
||||
result = swarm.run(task=task)
|
||||
|
||||
print(result)
|
Loading…
Reference in new issue