commit
55c161bd2e
@ -1,33 +1,33 @@
|
|||||||
---
|
---
|
||||||
name: Lint
|
name: Lint
|
||||||
on: [push, pull_request] # yamllint disable-line rule:truthy
|
on: [push, pull_request] # yamllint disable-line rule:truthy
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
yaml-lint:
|
lint:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
- uses: actions/setup-python@v5
|
|
||||||
- run: pip install yamllint
|
- name: Set up Python
|
||||||
- run: yamllint .
|
uses: actions/setup-python@v5
|
||||||
flake8-lint:
|
with:
|
||||||
runs-on: ubuntu-latest
|
python-version: '3.10'
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
- name: Cache pip dependencies
|
||||||
- uses: actions/setup-python@v5
|
uses: actions/cache@v3
|
||||||
- run: pip install flake8
|
with:
|
||||||
- run: flake8 .
|
path: ~/.cache/pip
|
||||||
ruff-lint:
|
key: ${{ runner.os }}-pip-${{ hashFiles('**/pyproject.toml') }}
|
||||||
runs-on: ubuntu-latest
|
restore-keys: |
|
||||||
steps:
|
${{ runner.os }}-pip-
|
||||||
- uses: actions/checkout@v4
|
|
||||||
- uses: actions/setup-python@v5
|
- name: Install dependencies
|
||||||
- run: pip install ruff
|
run: |
|
||||||
- run: ruff format .
|
python -m pip install --upgrade pip
|
||||||
- run: ruff check --fix .
|
pip install black==24.2.0 ruff==0.2.1
|
||||||
pylint-lint:
|
|
||||||
runs-on: ubuntu-latest
|
- name: Check Black formatting
|
||||||
steps:
|
run: black . --check --diff
|
||||||
- uses: actions/checkout@v4
|
|
||||||
- uses: actions/setup-python@v5
|
- name: Run Ruff linting
|
||||||
- run: pip install pylint
|
run: ruff check .
|
||||||
- run: pylint swarms --recursive=y
|
|
||||||
|
@ -1,49 +0,0 @@
|
|||||||
# This workflow uses actions that are not certified by GitHub.
|
|
||||||
# They are provided by a third-party and are governed by
|
|
||||||
# separate terms of service, privacy policy, and support
|
|
||||||
# documentation.
|
|
||||||
|
|
||||||
# This workflow file requires a free account on Semgrep.dev to
|
|
||||||
# manage rules, file ignores, notifications, and more.
|
|
||||||
#
|
|
||||||
# See https://semgrep.dev/docs
|
|
||||||
|
|
||||||
name: Semgrep
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches: [ "master" ]
|
|
||||||
pull_request:
|
|
||||||
# The branches below must be a subset of the branches above
|
|
||||||
branches: [ "master" ]
|
|
||||||
schedule:
|
|
||||||
- cron: '19 7 * * 3'
|
|
||||||
|
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
semgrep:
|
|
||||||
permissions:
|
|
||||||
contents: read # for actions/checkout to fetch code
|
|
||||||
security-events: write # for github/codeql-action/upload-sarif to upload SARIF results
|
|
||||||
actions: read # only required for a private repository by github/codeql-action/upload-sarif to get the Action run status
|
|
||||||
name: Scan
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
# Checkout project source
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
|
|
||||||
# Scan code using project's configuration on https://semgrep.dev/manage
|
|
||||||
- uses: returntocorp/semgrep-action@713efdd345f3035192eaa63f56867b88e63e4e5d
|
|
||||||
with:
|
|
||||||
publishToken: ${{ secrets.SEMGREP_APP_TOKEN }}
|
|
||||||
publishDeployment: ${{ secrets.SEMGREP_DEPLOYMENT_ID }}
|
|
||||||
generateSarif: "1"
|
|
||||||
|
|
||||||
# Upload SARIF file generated in previous step
|
|
||||||
- name: Upload SARIF file
|
|
||||||
uses: github/codeql-action/upload-sarif@v3
|
|
||||||
with:
|
|
||||||
sarif_file: semgrep.sarif
|
|
||||||
if: always()
|
|
@ -0,0 +1,31 @@
|
|||||||
|
name: Run Tests
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [ "master" ]
|
||||||
|
pull_request:
|
||||||
|
branches: [ "master" ]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
test:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Set up Python 3.10
|
||||||
|
uses: actions/setup-python@v5
|
||||||
|
with:
|
||||||
|
python-version: "3.10"
|
||||||
|
|
||||||
|
- name: Install Poetry
|
||||||
|
run: |
|
||||||
|
curl -sSL https://install.python-poetry.org | python3 -
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: |
|
||||||
|
poetry install --with test
|
||||||
|
|
||||||
|
- name: Run tests
|
||||||
|
run: |
|
||||||
|
poetry run pytest tests/ -v
|
@ -0,0 +1,221 @@
|
|||||||
|
# Contributing to Swarms: Building the Infrastructure for The Agentic Economy
|
||||||
|
|
||||||
|
Multi-agent collaboration is the most important technology in human history. It will reshape civilization by enabling billions of autonomous agents to coordinate and solve problems at unprecedented scale.
|
||||||
|
|
||||||
|
!!! success "The Foundation of Tomorrow"
|
||||||
|
**Swarms** is the foundational infrastructure powering this autonomous economy. By contributing, you're building the systems that will enable the next generation of intelligent automation.
|
||||||
|
|
||||||
|
### What You're Building
|
||||||
|
|
||||||
|
=== "Autonomous Systems"
|
||||||
|
**Autonomous Resource Allocation**
|
||||||
|
|
||||||
|
Global supply chains and energy distribution optimized in real-time
|
||||||
|
|
||||||
|
=== "Intelligence Networks"
|
||||||
|
**Distributed Decision Making**
|
||||||
|
|
||||||
|
Collaborative intelligence networks across industries and governments
|
||||||
|
|
||||||
|
=== "Smart Markets"
|
||||||
|
**Self-Organizing Markets**
|
||||||
|
|
||||||
|
Agent-driven marketplaces that automatically balance supply and demand
|
||||||
|
|
||||||
|
=== "Problem Solving"
|
||||||
|
**Collaborative Problem Solving**
|
||||||
|
|
||||||
|
Massive agent swarms tackling climate change, disease, and scientific discovery
|
||||||
|
|
||||||
|
=== "Infrastructure"
|
||||||
|
**Adaptive Infrastructure**
|
||||||
|
|
||||||
|
Self-healing systems that evolve without human intervention
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Why Contribute to Swarms?
|
||||||
|
|
||||||
|
### :material-rocket-launch: Shape the Future of Civilization
|
||||||
|
|
||||||
|
!!! abstract "Your Impact"
|
||||||
|
- Define standards for multi-agent communication protocols
|
||||||
|
- Build architectural patterns for distributed intelligence systems
|
||||||
|
- Create frameworks for deploying agent swarms in production
|
||||||
|
- Establish ethical guidelines for autonomous agent collaboration
|
||||||
|
|
||||||
|
### :material-trophy: Recognition and Professional Development
|
||||||
|
|
||||||
|
!!! tip "Immediate Recognition"
|
||||||
|
- **Social Media Features** - All merged PRs showcased publicly
|
||||||
|
- **Bounty Programs** - Financial rewards for high-impact contributions
|
||||||
|
- **Fast-Track Hiring** - Priority consideration for core team positions
|
||||||
|
- **Community Spotlights** - Regular recognition and acknowledgments
|
||||||
|
|
||||||
|
!!! info "Career Benefits"
|
||||||
|
- Multi-agent expertise highly valued by AI industry
|
||||||
|
- Portfolio demonstrates cutting-edge technical skills
|
||||||
|
- Direct networking with leading researchers and companies
|
||||||
|
- Thought leadership opportunities in emerging field
|
||||||
|
|
||||||
|
### :material-brain: Technical Expertise Development
|
||||||
|
|
||||||
|
Master cutting-edge technologies:
|
||||||
|
|
||||||
|
| Technology Area | Skills You'll Develop |
|
||||||
|
|----------------|----------------------|
|
||||||
|
| **Swarm Intelligence** | Design sophisticated agent coordination mechanisms |
|
||||||
|
| **Distributed Computing** | Build scalable architectures for thousands of agents |
|
||||||
|
| **Communication Protocols** | Create novel interaction patterns |
|
||||||
|
| **Production AI** | Deploy and orchestrate enterprise-scale systems |
|
||||||
|
| **Research Implementation** | Turn cutting-edge papers into working code |
|
||||||
|
|
||||||
|
### :material-account-group: Research Community Access
|
||||||
|
|
||||||
|
!!! note "Collaborative Environment"
|
||||||
|
- Work with experts from academic institutions and industry
|
||||||
|
- Regular technical seminars and research discussions
|
||||||
|
- Structured mentorship from experienced contributors
|
||||||
|
- Applied research opportunities with real-world impact
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Contribution Opportunities
|
||||||
|
|
||||||
|
=== "New Contributors"
|
||||||
|
### :material-school: Perfect for Getting Started
|
||||||
|
|
||||||
|
- **Documentation** - Improve guides, tutorials, and API references
|
||||||
|
- **Bug Reports** - Identify and document issues
|
||||||
|
- **Code Quality** - Participate in testing and review processes
|
||||||
|
- **Community Support** - Help users in forums and discussions
|
||||||
|
|
||||||
|
=== "Experienced Developers"
|
||||||
|
### :material-code-braces: Advanced Technical Work
|
||||||
|
|
||||||
|
- **Core Architecture** - Design fundamental system components
|
||||||
|
- **Performance Optimization** - Enhance coordination and communication efficiency
|
||||||
|
- **Research Implementation** - Turn cutting-edge papers into working code
|
||||||
|
- **Integration Development** - Build connections with AI tools and platforms
|
||||||
|
|
||||||
|
=== "Researchers"
|
||||||
|
### :material-flask: Research and Innovation
|
||||||
|
|
||||||
|
- **Algorithm Development** - Implement novel multi-agent algorithms
|
||||||
|
- **Experimental Frameworks** - Create evaluation and benchmarking tools
|
||||||
|
- **Theoretical Contributions** - Develop research documentation and frameworks
|
||||||
|
- **Academic Collaboration** - Partner on funded research projects
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## How to Contribute
|
||||||
|
|
||||||
|
### Step 1: Get Started
|
||||||
|
|
||||||
|
!!! info "Essential Resources"
|
||||||
|
[:material-book-open-page-variant: **Documentation**](https://docs.swarms.world/en/latest/){ .md-button .md-button--primary }
|
||||||
|
[:material-github: **GitHub Repository**](https://github.com/kyegomez/swarms){ .md-button }
|
||||||
|
[:material-chat: **Community Channels**](#){ .md-button }
|
||||||
|
|
||||||
|
### Step 2: Find Your Path
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
graph TD
|
||||||
|
A[Choose Your Path] --> B[Browse Issues]
|
||||||
|
A --> C[Review Roadmap]
|
||||||
|
A --> D[Propose Ideas]
|
||||||
|
B --> E[good first issue]
|
||||||
|
B --> F[help wanted]
|
||||||
|
C --> G[Core Features]
|
||||||
|
C --> H[Research Areas]
|
||||||
|
D --> I[Discussion Forums]
|
||||||
|
```
|
||||||
|
|
||||||
|
### Step 3: Make Impact
|
||||||
|
|
||||||
|
1. **Fork & Setup** - Configure your development environment
|
||||||
|
2. **Develop** - Create your contribution
|
||||||
|
3. **Submit** - Open a pull request
|
||||||
|
4. **Collaborate** - Work with maintainers
|
||||||
|
5. **Celebrate** - See your work recognized
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Recognition Framework
|
||||||
|
|
||||||
|
### :material-flash: Immediate Benefits
|
||||||
|
|
||||||
|
!!! success "Instant Recognition"
|
||||||
|
| Benefit | Description |
|
||||||
|
|---------|-------------|
|
||||||
|
| **Social Media Features** | Every merged PR showcased publicly |
|
||||||
|
| **Community Recognition** | Contributor badges and documentation credits |
|
||||||
|
| **Professional References** | Formal acknowledgment for portfolios |
|
||||||
|
| **Direct Mentorship** | Access to core team guidance |
|
||||||
|
|
||||||
|
### :material-trending-up: Long-term Opportunities
|
||||||
|
|
||||||
|
!!! tip "Career Growth"
|
||||||
|
- **Team Positions** - Fast-track consideration for core team roles
|
||||||
|
- **Conference Speaking** - Present work at AI conferences and events
|
||||||
|
- **Industry Connections** - Network with leading AI organizations
|
||||||
|
- **Research Collaboration** - Partner with academic institutions
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Societal Impact
|
||||||
|
|
||||||
|
!!! abstract "Building Solutions for Humanity"
|
||||||
|
Swarms enables technology that addresses critical challenges:
|
||||||
|
|
||||||
|
=== "Research"
|
||||||
|
**Scientific Research**
|
||||||
|
|
||||||
|
Accelerate collaborative research and discovery across disciplines
|
||||||
|
|
||||||
|
=== "Healthcare"
|
||||||
|
**Healthcare Innovation**
|
||||||
|
|
||||||
|
Support drug discovery and personalized medicine development
|
||||||
|
|
||||||
|
=== "Environment"
|
||||||
|
**Environmental Solutions**
|
||||||
|
|
||||||
|
Monitor climate and optimize sustainability initiatives
|
||||||
|
|
||||||
|
=== "Education"
|
||||||
|
**Educational Technology**
|
||||||
|
|
||||||
|
Create adaptive learning systems for personalized education
|
||||||
|
|
||||||
|
=== "Economy"
|
||||||
|
**Economic Innovation**
|
||||||
|
|
||||||
|
Generate new opportunities and efficiency improvements
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Get Involved
|
||||||
|
|
||||||
|
### :material-link: Connect With Us
|
||||||
|
|
||||||
|
!!! info "Join the Community"
|
||||||
|
[:material-github: **GitHub Repository**](https://github.com/kyegomez/swarms){ .md-button .md-button--primary }
|
||||||
|
[:material-book: **Documentation**](https://docs.swarms.world/en/latest/){ .md-button }
|
||||||
|
[:material-forum: **Community Forums**](#){ .md-button }
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
!!! warning "The Future is Now"
|
||||||
|
Multi-agent collaboration will define the next century of human progress. The autonomous economy depends on the infrastructure we build today.
|
||||||
|
|
||||||
|
!!! success "Your Mission"
|
||||||
|
Your contribution to Swarms helps create the foundation for billions of autonomous agents working together to solve humanity's greatest challenges.
|
||||||
|
|
||||||
|
**Join us in building the most important technology of our time.**
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
<div class="result" markdown>
|
||||||
|
*Built with :material-heart: by the global Swarms community*
|
||||||
|
</div>
|
@ -0,0 +1,62 @@
|
|||||||
|
# Agent with Streaming
|
||||||
|
|
||||||
|
The Swarms framework provides powerful real-time streaming capabilities for agents, allowing you to see responses being generated token by token as they're produced by the language model. This creates a more engaging and interactive experience, especially useful for long-form content generation, debugging, or when you want to provide immediate feedback to users.
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
Install the swarms package using pip:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pip install -U swarms
|
||||||
|
```
|
||||||
|
|
||||||
|
## Basic Setup
|
||||||
|
|
||||||
|
1. First, set up your environment variables:
|
||||||
|
|
||||||
|
```python
|
||||||
|
WORKSPACE_DIR="agent_workspace"
|
||||||
|
OPENAI_API_KEY=""
|
||||||
|
```
|
||||||
|
|
||||||
|
## Step by Step
|
||||||
|
|
||||||
|
- Install and put your keys in `.env`
|
||||||
|
|
||||||
|
- Turn on streaming in `Agent()` with `streaming_on=True`
|
||||||
|
|
||||||
|
- Optional: If you want to pretty print it, you can do `print_on=True`; if not, it will print normally
|
||||||
|
|
||||||
|
## Code
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent
|
||||||
|
|
||||||
|
# Enable real-time streaming
|
||||||
|
agent = Agent(
|
||||||
|
agent_name="StoryAgent",
|
||||||
|
model_name="gpt-4o-mini",
|
||||||
|
streaming_on=True, # 🔥 This enables real streaming!
|
||||||
|
max_loops=1,
|
||||||
|
print_on=True, # By default, it's False for raw streaming!
|
||||||
|
)
|
||||||
|
|
||||||
|
# This will now stream in real-time with a beautiful UI!
|
||||||
|
response = agent.run("Tell me a detailed story about humanity colonizing the stars")
|
||||||
|
print(response)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Connect With Us
|
||||||
|
|
||||||
|
If you'd like technical support, join our Discord below and stay updated on our Twitter for new updates!
|
||||||
|
|
||||||
|
| Platform | Link | Description |
|
||||||
|
|----------|------|-------------|
|
||||||
|
| 📚 Documentation | [docs.swarms.world](https://docs.swarms.world) | Official documentation and guides |
|
||||||
|
| 📝 Blog | [Medium](https://medium.com/@kyeg) | Latest updates and technical articles |
|
||||||
|
| 💬 Discord | [Join Discord](https://discord.gg/jM3Z6M9uMq) | Live chat and community support |
|
||||||
|
| 🐦 Twitter | [@kyegomez](https://twitter.com/kyegomez) | Latest news and announcements |
|
||||||
|
| 👥 LinkedIn | [The Swarm Corporation](https://www.linkedin.com/company/the-swarm-corporation) | Professional network and updates |
|
||||||
|
| 📺 YouTube | [Swarms Channel](https://www.youtube.com/channel/UC9yXyitkbU_WSy7bd_41SqQ) | Tutorials and demos |
|
||||||
|
| 🎫 Events | [Sign up here](https://lu.ma/5p2jnc2v) | Join our community events |
|
||||||
|
|
@ -0,0 +1,387 @@
|
|||||||
|
|
||||||
|
# Welcome to Swarms Docs Home
|
||||||
|
|
||||||
|
[](https://discord.gg/jM3Z6M9uMq) [](https://www.youtube.com/@kyegomez3242) [](https://www.linkedin.com/in/kye-g-38759a207/) [](https://x.com/swarms_corp)
|
||||||
|
|
||||||
|
## What is Swarms?
|
||||||
|
|
||||||
|
**Swarms** is the **first and most reliable multi-agent production-grade framework** designed to orchestrate intelligent AI agents at scale. Built for enterprise applications, Swarms enables you to create sophisticated multi-agent systems that can handle complex tasks through collaboration, parallel processing, and intelligent task distribution.
|
||||||
|
|
||||||
|
### Key Capabilities
|
||||||
|
|
||||||
|
- **🏢 Production-Ready**: Enterprise-grade infrastructure with high reliability, comprehensive logging, and robust error handling
|
||||||
|
- **🤖 Multi-Agent Orchestration**: Support for hierarchical swarms, parallel processing, sequential workflows, and dynamic agent rearrangement
|
||||||
|
- **🔄 Flexible Integration**: Multi-model support, custom agent creation, extensive tool library, and multiple memory systems
|
||||||
|
- **📈 Scalable Architecture**: Concurrent processing, resource management, load balancing, and horizontal scaling capabilities
|
||||||
|
- **🛠️ Developer-Friendly**: Simple API, extensive documentation, active community, and CLI tools for rapid development
|
||||||
|
- **🔐 Enterprise Security**: Built-in error handling, rate limiting, monitoring integration, and audit logging
|
||||||
|
|
||||||
|
### Why Choose Swarms?
|
||||||
|
|
||||||
|
Swarms stands out as the **most reliable multi-agent framework** because it was built from the ground up for production environments. Unlike other frameworks that focus on research or simple demos, Swarms provides the infrastructure, tooling, and best practices needed to deploy multi-agent systems in real-world applications.
|
||||||
|
|
||||||
|
Whether you're building financial analysis systems, healthcare diagnostics, manufacturing optimization, or any other complex multi-agent application, Swarms provides the foundation you need to succeed.
|
||||||
|
|
||||||
|
Get started learning swarms with the following examples and more.
|
||||||
|
|
||||||
|
## Install 💻
|
||||||
|
|
||||||
|
```bash
|
||||||
|
$ pip3 install -U swarms
|
||||||
|
```
|
||||||
|
|
||||||
|
### Using uv (Recommended)
|
||||||
|
[uv](https://github.com/astral-sh/uv) is a fast Python package installer and resolver, written in Rust.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Install uv
|
||||||
|
$ curl -LsSf https://astral.sh/uv/install.sh | sh
|
||||||
|
|
||||||
|
# Install swarms using uv
|
||||||
|
$ uv pip install swarms
|
||||||
|
```
|
||||||
|
|
||||||
|
### Using poetry
|
||||||
|
```bash
|
||||||
|
# Install poetry if you haven't already
|
||||||
|
$ curl -sSL https://install.python-poetry.org | python3 -
|
||||||
|
|
||||||
|
# Add swarms to your project
|
||||||
|
$ poetry add swarms
|
||||||
|
```
|
||||||
|
|
||||||
|
### From source
|
||||||
|
```bash
|
||||||
|
# Clone the repository
|
||||||
|
$ git clone https://github.com/kyegomez/swarms.git
|
||||||
|
$ cd swarms
|
||||||
|
|
||||||
|
# Install with pip
|
||||||
|
$ pip install -e .
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Environment Configuration
|
||||||
|
|
||||||
|
[Learn more about the environment configuration here](https://docs.swarms.world/en/latest/swarms/install/env/)
|
||||||
|
|
||||||
|
```
|
||||||
|
OPENAI_API_KEY=""
|
||||||
|
WORKSPACE_DIR="agent_workspace"
|
||||||
|
ANTHROPIC_API_KEY=""
|
||||||
|
GROQ_API_KEY=""
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
### 🤖 Your First Agent
|
||||||
|
|
||||||
|
An **Agent** is the fundamental building block of a swarm—an autonomous entity powered by an LLM + Tools + Memory. [Learn more Here](https://docs.swarms.world/en/latest/swarms/structs/agent/)
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent
|
||||||
|
|
||||||
|
# Initialize a new agent
|
||||||
|
agent = Agent(
|
||||||
|
model_name="gpt-4o-mini", # Specify the LLM
|
||||||
|
max_loops=1, # Set the number of interactions
|
||||||
|
interactive=True, # Enable interactive mode for real-time feedback
|
||||||
|
)
|
||||||
|
|
||||||
|
# Run the agent with a task
|
||||||
|
agent.run("What are the key benefits of using a multi-agent system?")
|
||||||
|
```
|
||||||
|
|
||||||
|
### 🤝 Your First Swarm: Multi-Agent Collaboration
|
||||||
|
|
||||||
|
A **Swarm** consists of multiple agents working together. This simple example creates a two-agent workflow for researching and writing a blog post. [Learn More About SequentialWorkflow](https://docs.swarms.world/en/latest/swarms/structs/sequential_workflow/)
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent, SequentialWorkflow
|
||||||
|
|
||||||
|
# Agent 1: The Researcher
|
||||||
|
researcher = Agent(
|
||||||
|
agent_name="Researcher",
|
||||||
|
system_prompt="Your job is to research the provided topic and provide a detailed summary.",
|
||||||
|
model_name="gpt-4o-mini",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Agent 2: The Writer
|
||||||
|
writer = Agent(
|
||||||
|
agent_name="Writer",
|
||||||
|
system_prompt="Your job is to take the research summary and write a beautiful, engaging blog post about it.",
|
||||||
|
model_name="gpt-4o-mini",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Create a sequential workflow where the researcher's output feeds into the writer's input
|
||||||
|
workflow = SequentialWorkflow(agents=[researcher, writer])
|
||||||
|
|
||||||
|
# Run the workflow on a task
|
||||||
|
final_post = workflow.run("The history and future of artificial intelligence")
|
||||||
|
print(final_post)
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
-----
|
||||||
|
|
||||||
|
## 🏗️ Multi-Agent Architectures For Production Deployments
|
||||||
|
|
||||||
|
`swarms` provides a variety of powerful, pre-built multi-agent architectures enabling you to orchestrate agents in various ways. Choose the right structure for your specific problem to build efficient and reliable production systems.
|
||||||
|
|
||||||
|
| **Architecture** | **Description** | **Best For** |
|
||||||
|
|---|---|---|
|
||||||
|
| **[SequentialWorkflow](https://docs.swarms.world/en/latest/swarms/structs/sequential_workflow/)** | Agents execute tasks in a linear chain; one agent's output is the next one's input. | Step-by-step processes like data transformation pipelines, report generation. |
|
||||||
|
| **[ConcurrentWorkflow](https://docs.swarms.world/en/latest/swarms/structs/concurrent_workflow/)** | Agents run tasks simultaneously for maximum efficiency. | High-throughput tasks like batch processing, parallel data analysis. |
|
||||||
|
| **[AgentRearrange](https://docs.swarms.world/en/latest/swarms/structs/agent_rearrange/)** | Dynamically maps complex relationships (e.g., `a -> b, c`) between agents. | Flexible and adaptive workflows, task distribution, dynamic routing. |
|
||||||
|
| **[GraphWorkflow](https://docs.swarms.world/en/latest/swarms/structs/graph_workflow/)** | Orchestrates agents as nodes in a Directed Acyclic Graph (DAG). | Complex projects with intricate dependencies, like software builds. |
|
||||||
|
| **[MixtureOfAgents (MoA)](https://docs.swarms.world/en/latest/swarms/structs/moa/)** | Utilizes multiple expert agents in parallel and synthesizes their outputs. | Complex problem-solving, achieving state-of-the-art performance through collaboration. |
|
||||||
|
| **[GroupChat](https://docs.swarms.world/en/latest/swarms/structs/group_chat/)** | Agents collaborate and make decisions through a conversational interface. | Real-time collaborative decision-making, negotiations, brainstorming. |
|
||||||
|
| **[ForestSwarm](https://docs.swarms.world/en/latest/swarms/structs/forest_swarm/)** | Dynamically selects the most suitable agent or tree of agents for a given task. | Task routing, optimizing for expertise, complex decision-making trees. |
|
||||||
|
| **[SpreadSheetSwarm](https://docs.swarms.world/en/latest/swarms/structs/spreadsheet_swarm/)** | Manages thousands of agents concurrently, tracking tasks and outputs in a structured format. | Massive-scale parallel operations, large-scale data generation and analysis. |
|
||||||
|
| **[SwarmRouter](https://docs.swarms.world/en/latest/swarms/structs/swarm_router/)** | Universal orchestrator that provides a single interface to run any type of swarm with dynamic selection. | Simplifying complex workflows, switching between swarm strategies, unified multi-agent management. |
|
||||||
|
|
||||||
|
-----
|
||||||
|
|
||||||
|
### SequentialWorkflow
|
||||||
|
|
||||||
|
A `SequentialWorkflow` executes tasks in a strict order, forming a pipeline where each agent builds upon the work of the previous one. `SequentialWorkflow` is Ideal for processes that have clear, ordered steps. This ensures that tasks with dependencies are handled correctly.
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent, SequentialWorkflow
|
||||||
|
|
||||||
|
# Initialize agents for a 3-step process
|
||||||
|
# 1. Generate an idea
|
||||||
|
idea_generator = Agent(agent_name="IdeaGenerator", system_prompt="Generate a unique startup idea.", model_name="gpt-4o-mini")
|
||||||
|
# 2. Validate the idea
|
||||||
|
validator = Agent(agent_name="Validator", system_prompt="Take this startup idea and analyze its market viability.", model_name="gpt-4o-mini")
|
||||||
|
# 3. Create a pitch
|
||||||
|
pitch_creator = Agent(agent_name="PitchCreator", system_prompt="Write a 3-sentence elevator pitch for this validated startup idea.", model_name="gpt-4o-mini")
|
||||||
|
|
||||||
|
# Create the sequential workflow
|
||||||
|
workflow = SequentialWorkflow(agents=[idea_generator, validator, pitch_creator])
|
||||||
|
|
||||||
|
# Run the workflow
|
||||||
|
elevator_pitch = workflow.run()
|
||||||
|
print(elevator_pitch)
|
||||||
|
```
|
||||||
|
|
||||||
|
-----
|
||||||
|
|
||||||
|
|
||||||
|
### ConcurrentWorkflow (with `SpreadSheetSwarm`)
|
||||||
|
|
||||||
|
A concurrent workflow runs multiple agents simultaneously. `SpreadSheetSwarm` is a powerful implementation that can manage thousands of concurrent agents and log their outputs to a CSV file. Use this architecture for high-throughput tasks that can be performed in parallel, drastically reducing execution time.
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent, SpreadSheetSwarm
|
||||||
|
|
||||||
|
# Define a list of tasks (e.g., social media posts to generate)
|
||||||
|
platforms = ["Twitter", "LinkedIn", "Instagram"]
|
||||||
|
|
||||||
|
# Create an agent for each task
|
||||||
|
agents = [
|
||||||
|
Agent(
|
||||||
|
agent_name=f"{platform}-Marketer",
|
||||||
|
system_prompt=f"Generate a real estate marketing post for {platform}.",
|
||||||
|
model_name="gpt-4o-mini",
|
||||||
|
)
|
||||||
|
for platform in platforms
|
||||||
|
]
|
||||||
|
|
||||||
|
# Initialize the swarm to run these agents concurrently
|
||||||
|
swarm = SpreadSheetSwarm(
|
||||||
|
agents=agents,
|
||||||
|
autosave_on=True,
|
||||||
|
save_file_path="marketing_posts.csv",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Run the swarm with a single, shared task description
|
||||||
|
property_description = "A beautiful 3-bedroom house in sunny California."
|
||||||
|
swarm.run(task=f"Generate a post about: {property_description}")
|
||||||
|
# Check marketing_posts.csv for the results!
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### AgentRearrange
|
||||||
|
|
||||||
|
Inspired by `einsum`, `AgentRearrange` lets you define complex, non-linear relationships between agents using a simple string-based syntax. [Learn more](https://docs.swarms.world/en/latest/swarms/structs/agent_rearrange/). This architecture is Perfect for orchestrating dynamic workflows where agents might work in parallel, sequence, or a combination of both.
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent, AgentRearrange
|
||||||
|
|
||||||
|
# Define agents
|
||||||
|
researcher = Agent(agent_name="researcher", model_name="gpt-4o-mini")
|
||||||
|
writer = Agent(agent_name="writer", model_name="gpt-4o-mini")
|
||||||
|
editor = Agent(agent_name="editor", model_name="gpt-4o-mini")
|
||||||
|
|
||||||
|
# Define a flow: researcher sends work to both writer and editor simultaneously
|
||||||
|
# This is a one-to-many relationship
|
||||||
|
flow = "researcher -> writer, editor"
|
||||||
|
|
||||||
|
# Create the rearrangement system
|
||||||
|
rearrange_system = AgentRearrange(
|
||||||
|
agents=[researcher, writer, editor],
|
||||||
|
flow=flow,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Run the system
|
||||||
|
# The researcher will generate content, and then both the writer and editor
|
||||||
|
# will process that content in parallel.
|
||||||
|
outputs = rearrange_system.run("Analyze the impact of AI on modern cinema.")
|
||||||
|
print(outputs)
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
<!--
|
||||||
|
### GraphWorkflow
|
||||||
|
|
||||||
|
`GraphWorkflow` orchestrates tasks using a Directed Acyclic Graph (DAG), allowing you to manage complex dependencies where some tasks must wait for others to complete.
|
||||||
|
|
||||||
|
**Description:** Essential for building sophisticated pipelines, like in software development or complex project management, where task order and dependencies are critical.
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent, GraphWorkflow, Node, Edge, NodeType
|
||||||
|
|
||||||
|
# Define agents and a simple python function as nodes
|
||||||
|
code_generator = Agent(agent_name="CodeGenerator", system_prompt="Write Python code for the given task.", model_name="gpt-4o-mini")
|
||||||
|
code_tester = Agent(agent_name="CodeTester", system_prompt="Test the given Python code and find bugs.", model_name="gpt-4o-mini")
|
||||||
|
|
||||||
|
# Create nodes for the graph
|
||||||
|
node1 = Node(id="generator", agent=code_generator)
|
||||||
|
node2 = Node(id="tester", agent=code_tester)
|
||||||
|
|
||||||
|
# Create the graph and define the dependency
|
||||||
|
graph = GraphWorkflow()
|
||||||
|
graph.add_nodes([node1, node2])
|
||||||
|
graph.add_edge(Edge(source="generator", target="tester")) # Tester runs after generator
|
||||||
|
|
||||||
|
# Set entry and end points
|
||||||
|
graph.set_entry_points(["generator"])
|
||||||
|
graph.set_end_points(["tester"])
|
||||||
|
|
||||||
|
# Run the graph workflow
|
||||||
|
results = graph.run("Create a function that calculates the factorial of a number.")
|
||||||
|
print(results)
|
||||||
|
``` -->
|
||||||
|
|
||||||
|
----
|
||||||
|
|
||||||
|
### SwarmRouter: The Universal Swarm Orchestrator
|
||||||
|
|
||||||
|
The `SwarmRouter` simplifies building complex workflows by providing a single interface to run any type of swarm. Instead of importing and managing different swarm classes, you can dynamically select the one you need just by changing the `swarm_type` parameter. [Read the full documentation](https://docs.swarms.world/en/latest/swarms/structs/swarm_router/)
|
||||||
|
|
||||||
|
This makes your code cleaner and more flexible, allowing you to switch between different multi-agent strategies with ease. Here's a complete example that shows how to define agents and then use `SwarmRouter` to execute the same task using different collaborative strategies.
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent
|
||||||
|
from swarms.structs.swarm_router import SwarmRouter, SwarmType
|
||||||
|
|
||||||
|
# Define a few generic agents
|
||||||
|
writer = Agent(agent_name="Writer", system_prompt="You are a creative writer.", model_name="gpt-4o-mini")
|
||||||
|
editor = Agent(agent_name="Editor", system_prompt="You are an expert editor for stories.", model_name="gpt-4o-mini")
|
||||||
|
reviewer = Agent(agent_name="Reviewer", system_prompt="You are a final reviewer who gives a score.", model_name="gpt-4o-mini")
|
||||||
|
|
||||||
|
# The agents and task will be the same for all examples
|
||||||
|
agents = [writer, editor, reviewer]
|
||||||
|
task = "Write a short story about a robot who discovers music."
|
||||||
|
|
||||||
|
# --- Example 1: SequentialWorkflow ---
|
||||||
|
# Agents run one after another in a chain: Writer -> Editor -> Reviewer.
|
||||||
|
print("Running a Sequential Workflow...")
|
||||||
|
sequential_router = SwarmRouter(swarm_type=SwarmType.SequentialWorkflow, agents=agents)
|
||||||
|
sequential_output = sequential_router.run(task)
|
||||||
|
print(f"Final Sequential Output:\n{sequential_output}\n")
|
||||||
|
|
||||||
|
# --- Example 2: ConcurrentWorkflow ---
|
||||||
|
# All agents receive the same initial task and run at the same time.
|
||||||
|
print("Running a Concurrent Workflow...")
|
||||||
|
concurrent_router = SwarmRouter(swarm_type=SwarmType.ConcurrentWorkflow, agents=agents)
|
||||||
|
concurrent_outputs = concurrent_router.run(task)
|
||||||
|
# This returns a dictionary of each agent's output
|
||||||
|
for agent_name, output in concurrent_outputs.items():
|
||||||
|
print(f"Output from {agent_name}:\n{output}\n")
|
||||||
|
|
||||||
|
# --- Example 3: MixtureOfAgents ---
|
||||||
|
# All agents run in parallel, and a special 'aggregator' agent synthesizes their outputs.
|
||||||
|
print("Running a Mixture of Agents Workflow...")
|
||||||
|
aggregator = Agent(
|
||||||
|
agent_name="Aggregator",
|
||||||
|
system_prompt="Combine the story, edits, and review into a final document.",
|
||||||
|
model_name="gpt-4o-mini"
|
||||||
|
)
|
||||||
|
moa_router = SwarmRouter(
|
||||||
|
swarm_type=SwarmType.MixtureOfAgents,
|
||||||
|
agents=agents,
|
||||||
|
aggregator_agent=aggregator, # MoA requires an aggregator
|
||||||
|
)
|
||||||
|
aggregated_output = moa_router.run(task)
|
||||||
|
print(f"Final Aggregated Output:\n{aggregated_output}\n")
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
The `SwarmRouter` is a powerful tool for simplifying multi-agent orchestration. It provides a consistent and flexible way to deploy different collaborative strategies, allowing you to build more sophisticated applications with less code.
|
||||||
|
|
||||||
|
-------
|
||||||
|
|
||||||
|
### MixtureOfAgents (MoA)
|
||||||
|
|
||||||
|
The `MixtureOfAgents` architecture processes tasks by feeding them to multiple "expert" agents in parallel. Their diverse outputs are then synthesized by an aggregator agent to produce a final, high-quality result. [Learn more here](https://docs.swarms.world/en/latest/swarms/examples/moa_example/)
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent, MixtureOfAgents
|
||||||
|
|
||||||
|
# Define expert agents
|
||||||
|
financial_analyst = Agent(agent_name="FinancialAnalyst", system_prompt="Analyze financial data.", model_name="gpt-4o-mini")
|
||||||
|
market_analyst = Agent(agent_name="MarketAnalyst", system_prompt="Analyze market trends.", model_name="gpt-4o-mini")
|
||||||
|
risk_analyst = Agent(agent_name="RiskAnalyst", system_prompt="Analyze investment risks.", model_name="gpt-4o-mini")
|
||||||
|
|
||||||
|
# Define the aggregator agent
|
||||||
|
aggregator = Agent(
|
||||||
|
agent_name="InvestmentAdvisor",
|
||||||
|
system_prompt="Synthesize the financial, market, and risk analyses to provide a final investment recommendation.",
|
||||||
|
model_name="gpt-4o-mini"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Create the MoA swarm
|
||||||
|
moa_swarm = MixtureOfAgents(
|
||||||
|
agents=[financial_analyst, market_analyst, risk_analyst],
|
||||||
|
aggregator_agent=aggregator,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Run the swarm
|
||||||
|
recommendation = moa_swarm.run("Should we invest in NVIDIA stock right now?")
|
||||||
|
print(recommendation)
|
||||||
|
```
|
||||||
|
|
||||||
|
----
|
||||||
|
|
||||||
|
### GroupChat
|
||||||
|
|
||||||
|
`GroupChat` creates a conversational environment where multiple agents can interact, discuss, and collaboratively solve a problem. You can define the speaking order or let it be determined dynamically. This architecture is ideal for tasks that benefit from debate and multi-perspective reasoning, such as contract negotiation, brainstorming, or complex decision-making.
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent, GroupChat
|
||||||
|
|
||||||
|
# Define agents for a debate
|
||||||
|
tech_optimist = Agent(agent_name="TechOptimist", system_prompt="Argue for the benefits of AI in society.", model_name="gpt-4o-mini")
|
||||||
|
tech_critic = Agent(agent_name="TechCritic", system_prompt="Argue against the unchecked advancement of AI.", model_name="gpt-4o-mini")
|
||||||
|
|
||||||
|
# Create the group chat
|
||||||
|
chat = GroupChat(
|
||||||
|
agents=[tech_optimist, tech_critic],
|
||||||
|
max_loops=4, # Limit the number of turns in the conversation
|
||||||
|
)
|
||||||
|
|
||||||
|
# Run the chat with an initial topic
|
||||||
|
conversation_history = chat.run(
|
||||||
|
"Let's discuss the societal impact of artificial intelligence."
|
||||||
|
)
|
||||||
|
|
||||||
|
# Print the full conversation
|
||||||
|
for message in conversation_history:
|
||||||
|
print(f"[{message['agent_name']}]: {message['content']}")
|
||||||
|
```
|
||||||
|
|
||||||
|
|
@ -0,0 +1,884 @@
|
|||||||
|
# Agents Introduction
|
||||||
|
|
||||||
|
The Agent class is the core component of the Swarms framework, designed to create intelligent, autonomous AI agents capable of handling complex tasks through multi-modal processing, tool integration, and structured outputs. This comprehensive guide covers all aspects of the Agent class, from basic setup to advanced features.
|
||||||
|
|
||||||
|
## Table of Contents
|
||||||
|
|
||||||
|
1. [Prerequisites & Installation](#prerequisites--installation)
|
||||||
|
2. [Basic Agent Configuration](#basic-agent-configuration)
|
||||||
|
3. [Multi-Modal Capabilities](#multi-modal-capabilities)
|
||||||
|
4. [Tool Integration](#tool-integration)
|
||||||
|
5. [Structured Outputs](#structured-outputs)
|
||||||
|
6. [Advanced Features](#advanced-features)
|
||||||
|
7. [Best Practices](#best-practices)
|
||||||
|
8. [Complete Examples](#complete-examples)
|
||||||
|
|
||||||
|
## Prerequisites & Installation
|
||||||
|
|
||||||
|
### System Requirements
|
||||||
|
|
||||||
|
- Python 3.7+
|
||||||
|
|
||||||
|
- OpenAI API key (for GPT models)
|
||||||
|
|
||||||
|
- Anthropic API key (for Claude models)
|
||||||
|
|
||||||
|
### Installation
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pip3 install -U swarms
|
||||||
|
```
|
||||||
|
|
||||||
|
### Environment Setup
|
||||||
|
|
||||||
|
Create a `.env` file with your API keys:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
OPENAI_API_KEY="your-openai-api-key"
|
||||||
|
ANTHROPIC_API_KEY="your-anthropic-api-key"
|
||||||
|
WORKSPACE_DIR="agent_workspace"
|
||||||
|
```
|
||||||
|
|
||||||
|
## Basic Agent Configuration
|
||||||
|
|
||||||
|
### Core Agent Structure
|
||||||
|
|
||||||
|
The Agent class provides a comprehensive set of parameters for customization:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent
|
||||||
|
|
||||||
|
# Basic agent initialization
|
||||||
|
agent = Agent(
|
||||||
|
agent_name="MyAgent",
|
||||||
|
agent_description="A specialized AI agent for specific tasks",
|
||||||
|
system_prompt="You are a helpful assistant...",
|
||||||
|
model_name="gpt-4o-mini",
|
||||||
|
max_loops=1,
|
||||||
|
max_tokens=4096,
|
||||||
|
temperature=0.7,
|
||||||
|
output_type="str",
|
||||||
|
safety_prompt_on=True
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Key Configuration Parameters
|
||||||
|
|
||||||
|
| Parameter | Type | Description | Default |
|
||||||
|
|-----------|------|-------------|---------|
|
||||||
|
| `agent_name` | str | Unique identifier for the agent | Required |
|
||||||
|
| `agent_description` | str | Detailed description of capabilities | Required |
|
||||||
|
| `system_prompt` | str | Core instructions defining behavior | Required |
|
||||||
|
| `model_name` | str | AI model to use | "gpt-4o-mini" |
|
||||||
|
| `max_loops` | int | Maximum execution loops | 1 |
|
||||||
|
| `max_tokens` | int | Maximum response tokens | 4096 |
|
||||||
|
| `temperature` | float | Response creativity (0-1) | 0.7 |
|
||||||
|
| `output_type` | str | Response format type | "str" |
|
||||||
|
| `multi_modal` | bool | Enable image processing | False |
|
||||||
|
| `safety_prompt_on` | bool | Enable safety checks | True |
|
||||||
|
|
||||||
|
### Simple Example
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent
|
||||||
|
|
||||||
|
# Create a basic financial advisor agent
|
||||||
|
financial_agent = Agent(
|
||||||
|
agent_name="Financial-Advisor",
|
||||||
|
agent_description="Personal finance and investment advisor",
|
||||||
|
system_prompt="""You are an expert financial advisor with deep knowledge of:
|
||||||
|
- Investment strategies and portfolio management
|
||||||
|
- Risk assessment and mitigation
|
||||||
|
- Market analysis and trends
|
||||||
|
- Financial planning and budgeting
|
||||||
|
|
||||||
|
Provide clear, actionable advice while considering risk tolerance.""",
|
||||||
|
model_name="gpt-4o-mini",
|
||||||
|
max_loops=1,
|
||||||
|
temperature=0.3,
|
||||||
|
output_type="str"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Run the agent
|
||||||
|
response = financial_agent.run("What are the best investment strategies for a 30-year-old?")
|
||||||
|
print(response)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Multi-Modal Capabilities
|
||||||
|
|
||||||
|
### Image Processing
|
||||||
|
|
||||||
|
The Agent class supports comprehensive image analysis through vision-enabled models:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent
|
||||||
|
|
||||||
|
# Create a vision-enabled agent
|
||||||
|
vision_agent = Agent(
|
||||||
|
agent_name="Vision-Analyst",
|
||||||
|
agent_description="Advanced image analysis and quality control agent",
|
||||||
|
system_prompt="""You are an expert image analyst capable of:
|
||||||
|
- Detailed visual inspection and quality assessment
|
||||||
|
- Object detection and classification
|
||||||
|
- Scene understanding and context analysis
|
||||||
|
- Defect identification and reporting
|
||||||
|
|
||||||
|
Provide comprehensive analysis with specific observations.""",
|
||||||
|
model_name="gpt-4o-mini", # Vision-enabled model
|
||||||
|
multi_modal=True, # Enable multi-modal processing
|
||||||
|
max_loops=1,
|
||||||
|
output_type="str"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Analyze a single image
|
||||||
|
response = vision_agent.run(
|
||||||
|
task="Analyze this image for quality control purposes",
|
||||||
|
img="path/to/image.jpg"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Process multiple images
|
||||||
|
response = vision_agent.run(
|
||||||
|
task="Compare these images and identify differences",
|
||||||
|
imgs=["image1.jpg", "image2.jpg", "image3.jpg"],
|
||||||
|
summarize_multiple_images=True
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Supported Image Formats
|
||||||
|
|
||||||
|
| Format | Description | Max Size |
|
||||||
|
|--------|-------------|----------|
|
||||||
|
| JPEG/JPG | Standard compressed format | 20MB |
|
||||||
|
| PNG | Lossless with transparency | 20MB |
|
||||||
|
| GIF | Animated (first frame only) | 20MB |
|
||||||
|
| WebP | Modern efficient format | 20MB |
|
||||||
|
|
||||||
|
### Quality Control Example
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent
|
||||||
|
from swarms.prompts.logistics import Quality_Control_Agent_Prompt
|
||||||
|
|
||||||
|
def security_analysis(danger_level: str) -> str:
|
||||||
|
"""Analyze security danger level and return appropriate response."""
|
||||||
|
danger_responses = {
|
||||||
|
"low": "No immediate danger detected",
|
||||||
|
"medium": "Moderate security concern identified",
|
||||||
|
"high": "Critical security threat detected",
|
||||||
|
None: "No danger level assessment available"
|
||||||
|
}
|
||||||
|
return danger_responses.get(danger_level, "Unknown danger level")
|
||||||
|
|
||||||
|
# Quality control agent with tool integration
|
||||||
|
quality_agent = Agent(
|
||||||
|
agent_name="Quality-Control-Agent",
|
||||||
|
agent_description="Advanced quality control and security analysis agent",
|
||||||
|
system_prompt=f"""
|
||||||
|
{Quality_Control_Agent_Prompt}
|
||||||
|
|
||||||
|
You have access to security analysis tools. When analyzing images:
|
||||||
|
1. Identify potential safety hazards
|
||||||
|
2. Assess quality standards compliance
|
||||||
|
3. Determine appropriate danger levels (low, medium, high)
|
||||||
|
4. Use the security_analysis function for threat assessment
|
||||||
|
""",
|
||||||
|
model_name="gpt-4o-mini",
|
||||||
|
multi_modal=True,
|
||||||
|
max_loops=1,
|
||||||
|
tools=[security_analysis]
|
||||||
|
)
|
||||||
|
|
||||||
|
# Analyze factory image
|
||||||
|
response = quality_agent.run(
|
||||||
|
task="Analyze this factory image for safety and quality issues",
|
||||||
|
img="factory_floor.jpg"
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Tool Integration
|
||||||
|
|
||||||
|
### Creating Custom Tools
|
||||||
|
|
||||||
|
Tools are Python functions that extend your agent's capabilities:
|
||||||
|
|
||||||
|
```python
|
||||||
|
import json
|
||||||
|
import requests
|
||||||
|
from typing import Optional, Dict, Any
|
||||||
|
|
||||||
|
def get_weather_data(city: str, country: Optional[str] = None) -> str:
|
||||||
|
"""
|
||||||
|
Get current weather data for a specified city.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
city (str): The city name
|
||||||
|
country (Optional[str]): Country code (e.g., 'US', 'UK')
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: JSON formatted weather data
|
||||||
|
|
||||||
|
Example:
|
||||||
|
>>> weather = get_weather_data("San Francisco", "US")
|
||||||
|
>>> print(weather)
|
||||||
|
{"temperature": 18, "condition": "partly cloudy", ...}
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
# API call logic here
|
||||||
|
weather_data = {
|
||||||
|
"city": city,
|
||||||
|
"country": country,
|
||||||
|
"temperature": 18,
|
||||||
|
"condition": "partly cloudy",
|
||||||
|
"humidity": 65,
|
||||||
|
"wind_speed": 12
|
||||||
|
}
|
||||||
|
return json.dumps(weather_data, indent=2)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
return json.dumps({"error": f"Weather API error: {str(e)}"})
|
||||||
|
|
||||||
|
def calculate_portfolio_metrics(prices: list, weights: list) -> str:
|
||||||
|
"""
|
||||||
|
Calculate portfolio performance metrics.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
prices (list): List of asset prices
|
||||||
|
weights (list): List of portfolio weights
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: JSON formatted portfolio metrics
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
# Portfolio calculation logic
|
||||||
|
portfolio_value = sum(p * w for p, w in zip(prices, weights))
|
||||||
|
metrics = {
|
||||||
|
"total_value": portfolio_value,
|
||||||
|
"weighted_average": portfolio_value / sum(weights),
|
||||||
|
"asset_count": len(prices)
|
||||||
|
}
|
||||||
|
return json.dumps(metrics, indent=2)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
return json.dumps({"error": f"Calculation error: {str(e)}"})
|
||||||
|
```
|
||||||
|
|
||||||
|
### Tool Integration Example
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent
|
||||||
|
|
||||||
|
# Create agent with custom tools
|
||||||
|
multi_tool_agent = Agent(
|
||||||
|
agent_name="Multi-Tool-Assistant",
|
||||||
|
agent_description="Versatile assistant with weather and financial tools",
|
||||||
|
system_prompt="""You are a versatile assistant with access to:
|
||||||
|
- Weather data retrieval for any city
|
||||||
|
- Portfolio analysis and financial calculations
|
||||||
|
|
||||||
|
Use these tools to provide comprehensive assistance.""",
|
||||||
|
model_name="gpt-4o-mini",
|
||||||
|
max_loops=1,
|
||||||
|
tools=[get_weather_data, calculate_portfolio_metrics]
|
||||||
|
)
|
||||||
|
|
||||||
|
# Use the agent with tools
|
||||||
|
response = multi_tool_agent.run(
|
||||||
|
"What's the weather in New York and calculate metrics for a portfolio with prices [100, 150, 200] and weights [0.3, 0.4, 0.3]?"
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
### API Integration Tools
|
||||||
|
|
||||||
|
```python
|
||||||
|
import requests
|
||||||
|
import json
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
def get_cryptocurrency_price(coin_id: str, vs_currency: str = "usd") -> str:
|
||||||
|
"""Get current cryptocurrency price from CoinGecko API."""
|
||||||
|
try:
|
||||||
|
url = "https://api.coingecko.com/api/v3/simple/price"
|
||||||
|
params = {
|
||||||
|
"ids": coin_id,
|
||||||
|
"vs_currencies": vs_currency,
|
||||||
|
"include_market_cap": True,
|
||||||
|
"include_24hr_vol": True,
|
||||||
|
"include_24hr_change": True
|
||||||
|
}
|
||||||
|
|
||||||
|
response = requests.get(url, params=params, timeout=10)
|
||||||
|
response.raise_for_status()
|
||||||
|
return json.dumps(response.json(), indent=2)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
return json.dumps({"error": f"API error: {str(e)}"})
|
||||||
|
|
||||||
|
def get_top_cryptocurrencies(limit: int = 10) -> str:
|
||||||
|
"""Get top cryptocurrencies by market cap."""
|
||||||
|
try:
|
||||||
|
url = "https://api.coingecko.com/api/v3/coins/markets"
|
||||||
|
params = {
|
||||||
|
"vs_currency": "usd",
|
||||||
|
"order": "market_cap_desc",
|
||||||
|
"per_page": limit,
|
||||||
|
"page": 1
|
||||||
|
}
|
||||||
|
|
||||||
|
response = requests.get(url, params=params, timeout=10)
|
||||||
|
response.raise_for_status()
|
||||||
|
return json.dumps(response.json(), indent=2)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
return json.dumps({"error": f"API error: {str(e)}"})
|
||||||
|
|
||||||
|
# Crypto analysis agent
|
||||||
|
crypto_agent = Agent(
|
||||||
|
agent_name="Crypto-Analysis-Agent",
|
||||||
|
agent_description="Cryptocurrency market analysis and price tracking agent",
|
||||||
|
system_prompt="""You are a cryptocurrency analysis expert with access to:
|
||||||
|
- Real-time price data for any cryptocurrency
|
||||||
|
- Market capitalization rankings
|
||||||
|
- Trading volume and price change data
|
||||||
|
|
||||||
|
Provide insightful market analysis and investment guidance.""",
|
||||||
|
model_name="gpt-4o-mini",
|
||||||
|
max_loops=1,
|
||||||
|
tools=[get_cryptocurrency_price, get_top_cryptocurrencies]
|
||||||
|
)
|
||||||
|
|
||||||
|
# Analyze crypto market
|
||||||
|
response = crypto_agent.run("Analyze the current Bitcoin price and show me the top 5 cryptocurrencies")
|
||||||
|
```
|
||||||
|
|
||||||
|
## Structured Outputs
|
||||||
|
|
||||||
|
### Function Schema Definition
|
||||||
|
|
||||||
|
Define structured outputs using OpenAI's function calling format:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent
|
||||||
|
|
||||||
|
# Define function schemas for structured outputs
|
||||||
|
stock_analysis_schema = {
|
||||||
|
"type": "function",
|
||||||
|
"function": {
|
||||||
|
"name": "analyze_stock_performance",
|
||||||
|
"description": "Analyze stock performance with detailed metrics",
|
||||||
|
"parameters": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"ticker": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Stock ticker symbol (e.g., AAPL, GOOGL)"
|
||||||
|
},
|
||||||
|
"analysis_type": {
|
||||||
|
"type": "string",
|
||||||
|
"enum": ["technical", "fundamental", "comprehensive"],
|
||||||
|
"description": "Type of analysis to perform"
|
||||||
|
},
|
||||||
|
"time_period": {
|
||||||
|
"type": "string",
|
||||||
|
"enum": ["1d", "1w", "1m", "3m", "1y"],
|
||||||
|
"description": "Time period for analysis"
|
||||||
|
},
|
||||||
|
"metrics": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"type": "string",
|
||||||
|
"enum": ["price", "volume", "pe_ratio", "market_cap", "volatility"]
|
||||||
|
},
|
||||||
|
"description": "Metrics to include in analysis"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": ["ticker", "analysis_type"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
portfolio_optimization_schema = {
|
||||||
|
"type": "function",
|
||||||
|
"function": {
|
||||||
|
"name": "optimize_portfolio",
|
||||||
|
"description": "Optimize portfolio allocation based on risk and return",
|
||||||
|
"parameters": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"assets": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"symbol": {"type": "string"},
|
||||||
|
"current_weight": {"type": "number"},
|
||||||
|
"expected_return": {"type": "number"},
|
||||||
|
"risk_level": {"type": "string", "enum": ["low", "medium", "high"]}
|
||||||
|
},
|
||||||
|
"required": ["symbol", "current_weight"]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"risk_tolerance": {
|
||||||
|
"type": "string",
|
||||||
|
"enum": ["conservative", "moderate", "aggressive"]
|
||||||
|
},
|
||||||
|
"investment_horizon": {
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": 1,
|
||||||
|
"maximum": 30,
|
||||||
|
"description": "Investment time horizon in years"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": ["assets", "risk_tolerance"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Create agent with structured outputs
|
||||||
|
structured_agent = Agent(
|
||||||
|
agent_name="Structured-Financial-Agent",
|
||||||
|
agent_description="Financial analysis agent with structured output capabilities",
|
||||||
|
system_prompt="""You are a financial analysis expert that provides structured outputs.
|
||||||
|
Use the provided function schemas to format your responses consistently.""",
|
||||||
|
model_name="gpt-4o-mini",
|
||||||
|
max_loops=1,
|
||||||
|
tools_list_dictionary=[stock_analysis_schema, portfolio_optimization_schema]
|
||||||
|
)
|
||||||
|
|
||||||
|
# Generate structured analysis
|
||||||
|
response = structured_agent.run(
|
||||||
|
"Analyze Apple stock (AAPL) performance with comprehensive analysis for the last 3 months"
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Advanced Features
|
||||||
|
|
||||||
|
### Dynamic Temperature Control
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent
|
||||||
|
|
||||||
|
# Agent with dynamic temperature adjustment
|
||||||
|
adaptive_agent = Agent(
|
||||||
|
agent_name="Adaptive-Response-Agent",
|
||||||
|
agent_description="Agent that adjusts response creativity based on context",
|
||||||
|
system_prompt="You are an adaptive AI that adjusts your response style based on the task complexity.",
|
||||||
|
model_name="gpt-4o-mini",
|
||||||
|
dynamic_temperature_enabled=True, # Enable adaptive temperature
|
||||||
|
max_loops=1,
|
||||||
|
output_type="str"
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Output Type Configurations
|
||||||
|
|
||||||
|
```python
|
||||||
|
# Different output type examples
|
||||||
|
json_agent = Agent(
|
||||||
|
agent_name="JSON-Agent",
|
||||||
|
system_prompt="Always respond in valid JSON format",
|
||||||
|
output_type="json"
|
||||||
|
)
|
||||||
|
|
||||||
|
streaming_agent = Agent(
|
||||||
|
agent_name="Streaming-Agent",
|
||||||
|
system_prompt="Provide detailed streaming responses",
|
||||||
|
output_type="str-all-except-first"
|
||||||
|
)
|
||||||
|
|
||||||
|
final_only_agent = Agent(
|
||||||
|
agent_name="Final-Only-Agent",
|
||||||
|
system_prompt="Provide only the final result",
|
||||||
|
output_type="final"
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Safety and Content Filtering
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent
|
||||||
|
|
||||||
|
# Agent with enhanced safety features
|
||||||
|
safe_agent = Agent(
|
||||||
|
agent_name="Safe-Agent",
|
||||||
|
agent_description="Agent with comprehensive safety measures",
|
||||||
|
system_prompt="You are a helpful, harmless, and honest AI assistant.",
|
||||||
|
model_name="gpt-4o-mini",
|
||||||
|
safety_prompt_on=True, # Enable safety prompts
|
||||||
|
max_loops=1,
|
||||||
|
temperature=0.3 # Lower temperature for more consistent, safe responses
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Best Practices
|
||||||
|
|
||||||
|
### Error Handling and Robustness
|
||||||
|
|
||||||
|
```python
|
||||||
|
import logging
|
||||||
|
from swarms import Agent
|
||||||
|
|
||||||
|
# Configure logging
|
||||||
|
logging.basicConfig(level=logging.INFO)
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
def robust_agent_execution(agent, task, max_retries=3):
|
||||||
|
"""Execute agent with retry logic and error handling."""
|
||||||
|
for attempt in range(max_retries):
|
||||||
|
try:
|
||||||
|
response = agent.run(task)
|
||||||
|
logger.info(f"Agent execution successful on attempt {attempt + 1}")
|
||||||
|
return response
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Attempt {attempt + 1} failed: {str(e)}")
|
||||||
|
if attempt == max_retries - 1:
|
||||||
|
raise
|
||||||
|
time.sleep(2 ** attempt) # Exponential backoff
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Example usage
|
||||||
|
try:
|
||||||
|
result = robust_agent_execution(agent, "Analyze market trends")
|
||||||
|
print(result)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Agent execution failed: {e}")
|
||||||
|
```
|
||||||
|
|
||||||
|
### Performance Optimization
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent
|
||||||
|
import time
|
||||||
|
|
||||||
|
# Optimized agent configuration
|
||||||
|
optimized_agent = Agent(
|
||||||
|
agent_name="Optimized-Agent",
|
||||||
|
agent_description="Performance-optimized agent configuration",
|
||||||
|
system_prompt="You are an efficient AI assistant optimized for performance.",
|
||||||
|
model_name="gpt-4o-mini", # Faster model
|
||||||
|
max_loops=1, # Minimize loops
|
||||||
|
max_tokens=2048, # Reasonable token limit
|
||||||
|
temperature=0.5, # Balanced creativity
|
||||||
|
output_type="str"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Batch processing example
|
||||||
|
def process_tasks_batch(agent, tasks, batch_size=5):
|
||||||
|
"""Process multiple tasks efficiently."""
|
||||||
|
results = []
|
||||||
|
for i in range(0, len(tasks), batch_size):
|
||||||
|
batch = tasks[i:i + batch_size]
|
||||||
|
batch_results = []
|
||||||
|
|
||||||
|
for task in batch:
|
||||||
|
start_time = time.time()
|
||||||
|
result = agent.run(task)
|
||||||
|
execution_time = time.time() - start_time
|
||||||
|
|
||||||
|
batch_results.append({
|
||||||
|
"task": task,
|
||||||
|
"result": result,
|
||||||
|
"execution_time": execution_time
|
||||||
|
})
|
||||||
|
|
||||||
|
results.extend(batch_results)
|
||||||
|
time.sleep(1) # Rate limiting
|
||||||
|
|
||||||
|
return results
|
||||||
|
```
|
||||||
|
|
||||||
|
## Complete Examples
|
||||||
|
|
||||||
|
### Multi-Modal Quality Control System
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent
|
||||||
|
from swarms.prompts.logistics import Quality_Control_Agent_Prompt
|
||||||
|
|
||||||
|
def security_analysis(danger_level: str) -> str:
|
||||||
|
"""Analyze security danger level and return appropriate response."""
|
||||||
|
responses = {
|
||||||
|
"low": "✅ No immediate danger detected - Safe to proceed",
|
||||||
|
"medium": "⚠️ Moderate security concern - Requires attention",
|
||||||
|
"high": "🚨 Critical security threat - Immediate action required",
|
||||||
|
None: "❓ No danger level assessment available"
|
||||||
|
}
|
||||||
|
return responses.get(danger_level, "Unknown danger level")
|
||||||
|
|
||||||
|
def quality_assessment(quality_score: int) -> str:
|
||||||
|
"""Assess quality based on numerical score (1-10)."""
|
||||||
|
if quality_score >= 8:
|
||||||
|
return "✅ Excellent quality - Meets all standards"
|
||||||
|
elif quality_score >= 6:
|
||||||
|
return "⚠️ Good quality - Minor improvements needed"
|
||||||
|
elif quality_score >= 4:
|
||||||
|
return "❌ Poor quality - Significant issues identified"
|
||||||
|
else:
|
||||||
|
return "🚨 Critical quality failure - Immediate attention required"
|
||||||
|
|
||||||
|
# Advanced quality control agent
|
||||||
|
quality_control_system = Agent(
|
||||||
|
agent_name="Advanced-Quality-Control-System",
|
||||||
|
agent_description="Comprehensive quality control and security analysis system",
|
||||||
|
system_prompt=f"""
|
||||||
|
{Quality_Control_Agent_Prompt}
|
||||||
|
|
||||||
|
You are an advanced quality control system with the following capabilities:
|
||||||
|
|
||||||
|
1. Visual Inspection: Analyze images for defects, compliance, and safety
|
||||||
|
2. Security Assessment: Identify potential security threats and hazards
|
||||||
|
3. Quality Scoring: Provide numerical quality ratings (1-10 scale)
|
||||||
|
4. Detailed Reporting: Generate comprehensive analysis reports
|
||||||
|
|
||||||
|
When analyzing images:
|
||||||
|
- Identify specific defects or issues
|
||||||
|
- Assess compliance with safety standards
|
||||||
|
- Determine appropriate danger levels (low, medium, high)
|
||||||
|
- Provide quality scores and recommendations
|
||||||
|
- Use available tools for detailed analysis
|
||||||
|
|
||||||
|
Always provide specific, actionable feedback.
|
||||||
|
""",
|
||||||
|
model_name="gpt-4o-mini",
|
||||||
|
multi_modal=True,
|
||||||
|
max_loops=1,
|
||||||
|
tools=[security_analysis, quality_assessment],
|
||||||
|
output_type="str"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Process factory images
|
||||||
|
factory_images = ["factory_floor.jpg", "assembly_line.jpg", "safety_equipment.jpg"]
|
||||||
|
|
||||||
|
for image in factory_images:
|
||||||
|
print(f"\n--- Analyzing {image} ---")
|
||||||
|
response = quality_control_system.run(
|
||||||
|
task=f"Perform comprehensive quality control analysis of this image. Assess safety, quality, and provide specific recommendations.",
|
||||||
|
img=image
|
||||||
|
)
|
||||||
|
print(response)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Advanced Financial Analysis Agent
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent
|
||||||
|
import json
|
||||||
|
import requests
|
||||||
|
|
||||||
|
def get_market_data(symbol: str, period: str = "1y") -> str:
|
||||||
|
"""Get comprehensive market data for a symbol."""
|
||||||
|
# Simulated market data (replace with real API)
|
||||||
|
market_data = {
|
||||||
|
"symbol": symbol,
|
||||||
|
"current_price": 150.25,
|
||||||
|
"change_percent": 2.5,
|
||||||
|
"volume": 1000000,
|
||||||
|
"market_cap": 2500000000,
|
||||||
|
"pe_ratio": 25.5,
|
||||||
|
"dividend_yield": 1.8,
|
||||||
|
"52_week_high": 180.50,
|
||||||
|
"52_week_low": 120.30
|
||||||
|
}
|
||||||
|
return json.dumps(market_data, indent=2)
|
||||||
|
|
||||||
|
def calculate_risk_metrics(prices: list, benchmark_prices: list) -> str:
|
||||||
|
"""Calculate risk metrics for a portfolio."""
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
try:
|
||||||
|
returns = np.diff(prices) / prices[:-1]
|
||||||
|
benchmark_returns = np.diff(benchmark_prices) / benchmark_prices[:-1]
|
||||||
|
|
||||||
|
volatility = np.std(returns) * np.sqrt(252) # Annualized
|
||||||
|
sharpe_ratio = (np.mean(returns) / np.std(returns)) * np.sqrt(252)
|
||||||
|
max_drawdown = np.max(np.maximum.accumulate(prices) - prices) / np.max(prices)
|
||||||
|
|
||||||
|
beta = np.cov(returns, benchmark_returns)[0, 1] / np.var(benchmark_returns)
|
||||||
|
|
||||||
|
risk_metrics = {
|
||||||
|
"volatility": float(volatility),
|
||||||
|
"sharpe_ratio": float(sharpe_ratio),
|
||||||
|
"max_drawdown": float(max_drawdown),
|
||||||
|
"beta": float(beta)
|
||||||
|
}
|
||||||
|
|
||||||
|
return json.dumps(risk_metrics, indent=2)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
return json.dumps({"error": f"Risk calculation error: {str(e)}"})
|
||||||
|
|
||||||
|
# Financial analysis schemas
|
||||||
|
financial_analysis_schema = {
|
||||||
|
"type": "function",
|
||||||
|
"function": {
|
||||||
|
"name": "comprehensive_financial_analysis",
|
||||||
|
"description": "Perform comprehensive financial analysis with structured output",
|
||||||
|
"parameters": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"analysis_summary": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"overall_rating": {"type": "string", "enum": ["buy", "hold", "sell"]},
|
||||||
|
"confidence_level": {"type": "number", "minimum": 0, "maximum": 100},
|
||||||
|
"key_strengths": {"type": "array", "items": {"type": "string"}},
|
||||||
|
"key_concerns": {"type": "array", "items": {"type": "string"}},
|
||||||
|
"price_target": {"type": "number"},
|
||||||
|
"risk_level": {"type": "string", "enum": ["low", "medium", "high"]}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"technical_analysis": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"trend_direction": {"type": "string", "enum": ["bullish", "bearish", "neutral"]},
|
||||||
|
"support_levels": {"type": "array", "items": {"type": "number"}},
|
||||||
|
"resistance_levels": {"type": "array", "items": {"type": "number"}},
|
||||||
|
"momentum_indicators": {"type": "array", "items": {"type": "string"}}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": ["analysis_summary", "technical_analysis"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Advanced financial agent
|
||||||
|
financial_analyst = Agent(
|
||||||
|
agent_name="Advanced-Financial-Analyst",
|
||||||
|
agent_description="Comprehensive financial analysis and investment advisory agent",
|
||||||
|
system_prompt="""You are an expert financial analyst with advanced capabilities in:
|
||||||
|
|
||||||
|
- Fundamental analysis and valuation
|
||||||
|
- Technical analysis and chart patterns
|
||||||
|
- Risk assessment and portfolio optimization
|
||||||
|
- Market sentiment analysis
|
||||||
|
- Economic indicator interpretation
|
||||||
|
|
||||||
|
Your analysis should be:
|
||||||
|
- Data-driven and objective
|
||||||
|
- Risk-aware and practical
|
||||||
|
- Clearly structured and actionable
|
||||||
|
- Compliant with financial regulations
|
||||||
|
|
||||||
|
Use available tools to gather market data and calculate risk metrics.
|
||||||
|
Provide structured outputs using the defined schemas.""",
|
||||||
|
model_name="gpt-4o-mini",
|
||||||
|
max_loops=1,
|
||||||
|
tools=[get_market_data, calculate_risk_metrics],
|
||||||
|
tools_list_dictionary=[financial_analysis_schema],
|
||||||
|
output_type="json"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Comprehensive financial analysis
|
||||||
|
analysis_response = financial_analyst.run(
|
||||||
|
"Perform a comprehensive analysis of Apple Inc. (AAPL) including technical and fundamental analysis with structured recommendations"
|
||||||
|
)
|
||||||
|
|
||||||
|
print(json.dumps(json.loads(analysis_response), indent=2))
|
||||||
|
```
|
||||||
|
|
||||||
|
### Multi-Agent Collaboration System
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent
|
||||||
|
import json
|
||||||
|
|
||||||
|
# Specialized agents for different tasks
|
||||||
|
research_agent = Agent(
|
||||||
|
agent_name="Research-Specialist",
|
||||||
|
agent_description="Market research and data analysis specialist",
|
||||||
|
system_prompt="You are a market research expert specializing in data collection and analysis.",
|
||||||
|
model_name="gpt-4o-mini",
|
||||||
|
max_loops=1,
|
||||||
|
temperature=0.3
|
||||||
|
)
|
||||||
|
|
||||||
|
strategy_agent = Agent(
|
||||||
|
agent_name="Strategy-Advisor",
|
||||||
|
agent_description="Strategic planning and recommendation specialist",
|
||||||
|
system_prompt="You are a strategic advisor providing high-level recommendations based on research.",
|
||||||
|
model_name="gpt-4o-mini",
|
||||||
|
max_loops=1,
|
||||||
|
temperature=0.5
|
||||||
|
)
|
||||||
|
|
||||||
|
execution_agent = Agent(
|
||||||
|
agent_name="Execution-Planner",
|
||||||
|
agent_description="Implementation and execution planning specialist",
|
||||||
|
system_prompt="You are an execution expert creating detailed implementation plans.",
|
||||||
|
model_name="gpt-4o-mini",
|
||||||
|
max_loops=1,
|
||||||
|
temperature=0.4
|
||||||
|
)
|
||||||
|
|
||||||
|
def collaborative_analysis(topic: str):
|
||||||
|
"""Perform collaborative analysis using multiple specialized agents."""
|
||||||
|
|
||||||
|
# Step 1: Research Phase
|
||||||
|
research_task = f"Conduct comprehensive research on {topic}. Provide key findings, market data, and trends."
|
||||||
|
research_results = research_agent.run(research_task)
|
||||||
|
|
||||||
|
# Step 2: Strategy Phase
|
||||||
|
strategy_task = f"Based on this research: {research_results}\n\nDevelop strategic recommendations for {topic}."
|
||||||
|
strategy_results = strategy_agent.run(strategy_task)
|
||||||
|
|
||||||
|
# Step 3: Execution Phase
|
||||||
|
execution_task = f"Create a detailed implementation plan based on:\nResearch: {research_results}\nStrategy: {strategy_results}"
|
||||||
|
execution_results = execution_agent.run(execution_task)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"research": research_results,
|
||||||
|
"strategy": strategy_results,
|
||||||
|
"execution": execution_results
|
||||||
|
}
|
||||||
|
|
||||||
|
# Example: Collaborative investment analysis
|
||||||
|
investment_analysis = collaborative_analysis("renewable energy sector investment opportunities")
|
||||||
|
|
||||||
|
for phase, results in investment_analysis.items():
|
||||||
|
print(f"\n=== {phase.upper()} PHASE ===")
|
||||||
|
print(results)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Support and Resources
|
||||||
|
|
||||||
|
Join our community of agent engineers and researchers for technical support, cutting-edge updates, and exclusive access to world-class agent engineering insights!
|
||||||
|
|
||||||
|
| Platform | Description | Link |
|
||||||
|
|----------|-------------|------|
|
||||||
|
| 📚 Documentation | Official documentation and guides | [docs.swarms.world](https://docs.swarms.world) |
|
||||||
|
| 📝 Blog | Latest updates and technical articles | [Medium](https://medium.com/@kyeg) |
|
||||||
|
| 💬 Discord | Live chat and community support | [Join Discord](https://discord.gg/jM3Z6M9uMq) |
|
||||||
|
| 🐦 Twitter | Latest news and announcements | [@kyegomez](https://twitter.com/kyegomez) |
|
||||||
|
| 👥 LinkedIn | Professional network and updates | [The Swarm Corporation](https://www.linkedin.com/company/the-swarm-corporation) |
|
||||||
|
| 📺 YouTube | Tutorials and demos | [Swarms Channel](https://www.youtube.com/channel/UC9yXyitkbU_WSy7bd_41SqQ) |
|
||||||
|
| 🎫 Events | Join our community events | [Sign up here](https://lu.ma/5p2jnc2v) |
|
||||||
|
| 🚀 Onboarding Session | Get onboarded with Kye Gomez, creator and lead maintainer of Swarms | [Book Session](https://cal.com/swarms/swarms-onboarding-session) |
|
||||||
|
|
||||||
|
### Getting Help
|
||||||
|
|
||||||
|
If you encounter issues or need assistance:
|
||||||
|
|
||||||
|
1. **Check the Documentation**: Start with the official docs for comprehensive guides
|
||||||
|
2. **Search Issues**: Look through existing GitHub issues for similar problems
|
||||||
|
3. **Join Discord**: Get real-time help from the community
|
||||||
|
4. **Create an Issue**: Report bugs or request features on GitHub
|
||||||
|
5. **Follow Updates**: Stay informed about new releases and improvements
|
||||||
|
|
||||||
|
### Contributing
|
||||||
|
|
||||||
|
We welcome contributions! Here's how to get involved:
|
||||||
|
|
||||||
|
- **Report Bugs**: Help us improve by reporting issues
|
||||||
|
|
||||||
|
- **Suggest Features**: Share your ideas for new capabilities
|
||||||
|
|
||||||
|
- **Submit Code**: Contribute improvements and new features
|
||||||
|
|
||||||
|
- **Improve Documentation**: Help make our docs better
|
||||||
|
|
||||||
|
- **Share Examples**: Show how you're using Swarms in your projects
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
*This guide covers the essential aspects of the Swarms Agent class. For the most up-to-date information and advanced features, please refer to the official documentation and community resources.*
|
@ -0,0 +1,135 @@
|
|||||||
|
## Interactive Groupchat Examples
|
||||||
|
|
||||||
|
The Interactive GroupChat is a powerful multi-agent architecture that enables dynamic collaboration between multiple AI agents. This architecture allows agents to communicate with each other, respond to mentions using `@agent_name` syntax, and work together to solve complex tasks through structured conversation flows.
|
||||||
|
|
||||||
|
### Architecture Description
|
||||||
|
|
||||||
|
The Interactive GroupChat implements a **collaborative swarm architecture** where multiple specialized agents work together in a coordinated manner. Key features include:
|
||||||
|
|
||||||
|
- **Mention-based Communication**: Agents can be directed to specific tasks using `@agent_name` syntax
|
||||||
|
- **Flexible Speaker Functions**: Multiple speaking order strategies (round robin, random, priority-based)
|
||||||
|
- **Enhanced Collaboration**: Agents build upon each other's responses and avoid redundancy
|
||||||
|
- **Interactive Sessions**: Support for both automated and interactive conversation modes
|
||||||
|
- **Context Awareness**: Agents maintain conversation history and context
|
||||||
|
|
||||||
|
For comprehensive documentation on Interactive GroupChat, visit: [Interactive GroupChat Documentation](https://docs.swarms.world/en/latest/swarms/structs/interactive_groupchat/)
|
||||||
|
|
||||||
|
### Step-by-Step Showcase
|
||||||
|
|
||||||
|
* **Agent Creation**: Define specialized agents with unique expertise and system prompts
|
||||||
|
* **GroupChat Initialization**: Create the InteractiveGroupChat structure with desired speaker function
|
||||||
|
* **Task Definition**: Formulate tasks using `@agent_name` mentions to direct specific agents
|
||||||
|
* **Execution**: Run the group chat to generate collaborative responses
|
||||||
|
* **Response Processing**: Handle the coordinated output from multiple agents
|
||||||
|
* **Iteration**: Chain multiple tasks for complex workflows
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
Install the swarms package using pip:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pip install -U swarms
|
||||||
|
```
|
||||||
|
|
||||||
|
## Basic Setup
|
||||||
|
|
||||||
|
1. First, set up your environment variables:
|
||||||
|
|
||||||
|
```python
|
||||||
|
WORKSPACE_DIR="agent_workspace"
|
||||||
|
OPENAI_API_KEY=""
|
||||||
|
```
|
||||||
|
|
||||||
|
## Code
|
||||||
|
|
||||||
|
```python
|
||||||
|
"""
|
||||||
|
InteractiveGroupChat Speaker Function Examples
|
||||||
|
|
||||||
|
This example demonstrates how to use different speaker functions in the InteractiveGroupChat:
|
||||||
|
- Round Robin: Agents speak in a fixed order, cycling through the list
|
||||||
|
- Random: Agents speak in random order
|
||||||
|
- Priority: Agents speak based on priority weights
|
||||||
|
- Custom: User-defined speaker functions
|
||||||
|
|
||||||
|
The example also shows how agents can mention each other using @agent_name syntax.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from swarms import Agent
|
||||||
|
from swarms.structs.interactive_groupchat import (
|
||||||
|
InteractiveGroupChat,
|
||||||
|
random_speaker,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def create_example_agents():
|
||||||
|
"""Create example agents for demonstration."""
|
||||||
|
|
||||||
|
# Create agents with different expertise
|
||||||
|
analyst = Agent(
|
||||||
|
agent_name="analyst",
|
||||||
|
system_prompt="You are a data analyst. You excel at analyzing data, creating charts, and providing insights.",
|
||||||
|
model_name="gpt-4.1",
|
||||||
|
streaming_on=True,
|
||||||
|
print_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
researcher = Agent(
|
||||||
|
agent_name="researcher",
|
||||||
|
system_prompt="You are a research specialist. You are great at gathering information, fact-checking, and providing detailed research.",
|
||||||
|
model_name="gpt-4.1",
|
||||||
|
streaming_on=True,
|
||||||
|
print_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
writer = Agent(
|
||||||
|
agent_name="writer",
|
||||||
|
system_prompt="You are a content writer. You excel at writing clear, engaging content and summarizing information.",
|
||||||
|
model_name="gpt-4.1",
|
||||||
|
streaming_on=True,
|
||||||
|
print_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
return [analyst, researcher, writer]
|
||||||
|
|
||||||
|
|
||||||
|
def example_random():
|
||||||
|
agents = create_example_agents()
|
||||||
|
|
||||||
|
# Create group chat with random speaker function
|
||||||
|
group_chat = InteractiveGroupChat(
|
||||||
|
name="Random Team",
|
||||||
|
description="A team that speaks in random order",
|
||||||
|
agents=agents,
|
||||||
|
speaker_function=random_speaker,
|
||||||
|
interactive=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Test the random behavior
|
||||||
|
task = "Let's create a marketing strategy. @analyst @researcher @writer please contribute."
|
||||||
|
|
||||||
|
response = group_chat.run(task)
|
||||||
|
print(f"Response:\n{response}\n")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
# example_round_robin()
|
||||||
|
example_random()
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## Connect With Us
|
||||||
|
|
||||||
|
Join our community of agent engineers and researchers for technical support, cutting-edge updates, and exclusive access to world-class agent engineering insights!
|
||||||
|
|
||||||
|
| Platform | Description | Link |
|
||||||
|
|----------|-------------|------|
|
||||||
|
| 📚 Documentation | Official documentation and guides | [docs.swarms.world](https://docs.swarms.world) |
|
||||||
|
| 📝 Blog | Latest updates and technical articles | [Medium](https://medium.com/@kyeg) |
|
||||||
|
| 💬 Discord | Live chat and community support | [Join Discord](https://discord.gg/jM3Z6M9uMq) |
|
||||||
|
| 🐦 Twitter | Latest news and announcements | [@kyegomez](https://twitter.com/kyegomez) |
|
||||||
|
| 👥 LinkedIn | Professional network and updates | [The Swarm Corporation](https://www.linkedin.com/company/the-swarm-corporation) |
|
||||||
|
| 📺 YouTube | Tutorials and demos | [Swarms Channel](https://www.youtube.com/channel/UC9yXyitkbU_WSy7bd_41SqQ) |
|
||||||
|
| 🎫 Events | Join our community events | [Sign up here](https://lu.ma/5p2jnc2v) |
|
||||||
|
| 🚀 Onboarding Session | Get onboarded with Kye Gomez, creator and lead maintainer of Swarms | [Book Session](https://cal.com/swarms/swarms-onboarding-session) |
|
@ -1,28 +0,0 @@
|
|||||||
# Meme Agent Builder
|
|
||||||
|
|
||||||
- `pip3 install -U swarms`
|
|
||||||
- Add your OpenAI API key to the `.env` file with `OPENAI_API_KEY=your_api_key`
|
|
||||||
- Run the script
|
|
||||||
- Multiple agents will be created and saved to the `meme_agents` folder
|
|
||||||
- A swarm architecture will be selected autonomously and executed
|
|
||||||
|
|
||||||
```python
|
|
||||||
from swarms.structs.meme_agent_persona_generator import (
|
|
||||||
MemeAgentGenerator,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
example = MemeAgentGenerator(
|
|
||||||
name="Meme-Swarm",
|
|
||||||
description="A swarm of specialized AI agents collaborating on generating and sharing memes around cool media from 2001s",
|
|
||||||
max_loops=1,
|
|
||||||
)
|
|
||||||
|
|
||||||
print(
|
|
||||||
example.run(
|
|
||||||
"Generate funny meme agents around cool media from 2001s"
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
```
|
|
@ -0,0 +1,132 @@
|
|||||||
|
# Mixture of Agents Example
|
||||||
|
|
||||||
|
The Mixture of Agents (MoA) is a sophisticated multi-agent architecture that implements parallel processing with iterative refinement. This approach processes multiple specialized agents simultaneously, concatenates their outputs, and then performs multiple parallel runs to achieve consensus or enhanced results.
|
||||||
|
|
||||||
|
## How It Works
|
||||||
|
|
||||||
|
1. **Parallel Processing**: Multiple agents work simultaneously on the same input
|
||||||
|
2. **Output Concatenation**: Results from all agents are combined into a unified response
|
||||||
|
3. **Iterative Refinement**: The process repeats for `n` layers/iterations to improve quality
|
||||||
|
4. **Consensus Building**: Multiple runs help achieve more reliable and comprehensive outputs
|
||||||
|
|
||||||
|
This architecture is particularly effective for complex tasks that benefit from diverse perspectives and iterative improvement, such as financial analysis, risk assessment, and multi-faceted problem solving.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
Install the swarms package using pip:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pip install -U swarms
|
||||||
|
```
|
||||||
|
|
||||||
|
## Basic Setup
|
||||||
|
|
||||||
|
1. First, set up your environment variables:
|
||||||
|
|
||||||
|
```python
|
||||||
|
WORKSPACE_DIR="agent_workspace"
|
||||||
|
ANTHROPIC_API_KEY=""
|
||||||
|
```
|
||||||
|
|
||||||
|
## Code
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent, MixtureOfAgents
|
||||||
|
|
||||||
|
# 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",
|
||||||
|
random_model_enabled=True,
|
||||||
|
dynamic_temperature_enabled=True,
|
||||||
|
output_type="str-all-except-first",
|
||||||
|
max_tokens=4096,
|
||||||
|
)
|
||||||
|
|
||||||
|
# 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,
|
||||||
|
# model_name="gpt-4o-mini",
|
||||||
|
random_model_enabled=True,
|
||||||
|
dynamic_temperature_enabled=True,
|
||||||
|
output_type="str-all-except-first",
|
||||||
|
max_tokens=4096,
|
||||||
|
)
|
||||||
|
|
||||||
|
# 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,
|
||||||
|
# model_name="gpt-4o-mini",
|
||||||
|
random_model_enabled=True,
|
||||||
|
dynamic_temperature_enabled=True,
|
||||||
|
output_type="str-all-except-first",
|
||||||
|
max_tokens=4096,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
swarm = MixtureOfAgents(
|
||||||
|
agents=[
|
||||||
|
risk_metrics_agent,
|
||||||
|
portfolio_risk_agent,
|
||||||
|
market_risk_agent,
|
||||||
|
],
|
||||||
|
layers=1,
|
||||||
|
max_loops=1,
|
||||||
|
output_type="final",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
out = swarm.run(
|
||||||
|
"Calculate VaR and Sharpe ratio for a portfolio with 15% annual return and 20% volatility"
|
||||||
|
)
|
||||||
|
|
||||||
|
print(out)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Support and Community
|
||||||
|
|
||||||
|
If you're facing issues or want to learn more, check out the following resources to join our Discord, stay updated on Twitter, and watch tutorials on YouTube!
|
||||||
|
|
||||||
|
| Platform | Link | Description |
|
||||||
|
|----------|------|-------------|
|
||||||
|
| 📚 Documentation | [docs.swarms.world](https://docs.swarms.world) | Official documentation and guides |
|
||||||
|
| 📝 Blog | [Medium](https://medium.com/@kyeg) | Latest updates and technical articles |
|
||||||
|
| 💬 Discord | [Join Discord](https://discord.gg/jM3Z6M9uMq) | Live chat and community support |
|
||||||
|
| 🐦 Twitter | [@kyegomez](https://twitter.com/kyegomez) | Latest news and announcements |
|
||||||
|
| 👥 LinkedIn | [The Swarm Corporation](https://www.linkedin.com/company/the-swarm-corporation) | Professional network and updates |
|
||||||
|
| 📺 YouTube | [Swarms Channel](https://www.youtube.com/channel/UC9yXyitkbU_WSy7bd_41SqQ) | Tutorials and demos |
|
||||||
|
| 🎫 Events | [Sign up here](https://lu.ma/5p2jnc2v) | Join our community events |
|
||||||
|
|
@ -0,0 +1,171 @@
|
|||||||
|
# Model Providers Overview
|
||||||
|
|
||||||
|
Swarms supports a vast array of model providers, giving you the flexibility to choose the best model for your specific use case. Whether you need high-performance inference, cost-effective solutions, or specialized capabilities, Swarms has you covered.
|
||||||
|
|
||||||
|
## Supported Model Providers
|
||||||
|
|
||||||
|
| Provider | Description | Documentation |
|
||||||
|
|----------|-------------|---------------|
|
||||||
|
| **OpenAI** | Industry-leading language models including GPT-4, GPT-4o, and GPT-4o-mini. Perfect for general-purpose tasks, creative writing, and complex reasoning. | [OpenAI Integration](openai_example.md) |
|
||||||
|
| **Anthropic/Claude** | Advanced AI models known for their safety, helpfulness, and reasoning capabilities. Claude models excel at analysis, coding, and creative tasks. | [Claude Integration](claude.md) |
|
||||||
|
| **Groq** | Ultra-fast inference platform offering real-time AI responses. Ideal for applications requiring low latency and high throughput. | [Groq Integration](groq.md) |
|
||||||
|
| **Cohere** | Enterprise-grade language models with strong performance on business applications, text generation, and semantic search. | [Cohere Integration](cohere.md) |
|
||||||
|
| **DeepSeek** | Advanced reasoning models including the DeepSeek Reasoner (R1). Excellent for complex problem-solving and analytical tasks. | [DeepSeek Integration](deepseek.md) |
|
||||||
|
| **Ollama** | Local model deployment platform allowing you to run open-source models on your own infrastructure. No API keys required. | [Ollama Integration](ollama.md) |
|
||||||
|
| **OpenRouter** | Unified API gateway providing access to hundreds of models from various providers through a single interface. | [OpenRouter Integration](openrouter.md) |
|
||||||
|
| **XAI** | xAI's Grok models offering unique capabilities for research, analysis, and creative tasks with advanced reasoning abilities. | [XAI Integration](xai.md) |
|
||||||
|
| **vLLM** | High-performance inference library for serving large language models with optimized memory usage and throughput. | [vLLM Integration](vllm_integration.md) |
|
||||||
|
| **Llama4** | Meta's latest open-source language models including Llama-4-Maverick and Llama-4-Scout variants with expert routing capabilities. | [Llama4 Integration](llama4.md) |
|
||||||
|
|
||||||
|
## Quick Start
|
||||||
|
|
||||||
|
All model providers follow a consistent pattern in Swarms. Here's the basic template:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent
|
||||||
|
import os
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
|
||||||
|
load_dotenv()
|
||||||
|
|
||||||
|
# Initialize agent with your chosen model
|
||||||
|
agent = Agent(
|
||||||
|
agent_name="Your-Agent-Name",
|
||||||
|
model_name="gpt-4o-mini", # Varies by provider
|
||||||
|
system_prompt="Your system prompt here",
|
||||||
|
agent_description="Description of what your agent does.",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Run your agent
|
||||||
|
response = agent.run("Your query here")
|
||||||
|
```
|
||||||
|
|
||||||
|
## Model Selection Guide
|
||||||
|
|
||||||
|
### For High-Performance Applications
|
||||||
|
|
||||||
|
- **OpenAI GPT-4o**: Best overall performance and reasoning
|
||||||
|
|
||||||
|
- **Anthropic Claude**: Excellent safety and analysis capabilities
|
||||||
|
|
||||||
|
- **DeepSeek R1**: Advanced reasoning and problem-solving
|
||||||
|
|
||||||
|
### For Cost-Effective Solutions
|
||||||
|
|
||||||
|
- **OpenAI GPT-4o-mini**: Great performance at lower cost
|
||||||
|
|
||||||
|
- **Ollama**: Free local deployment
|
||||||
|
|
||||||
|
- **OpenRouter**: Access to cost-effective models
|
||||||
|
|
||||||
|
### For Real-Time Applications
|
||||||
|
|
||||||
|
- **Groq**: Ultra-fast inference
|
||||||
|
|
||||||
|
- **vLLM**: Optimized for high throughput
|
||||||
|
|
||||||
|
### For Specialized Tasks
|
||||||
|
|
||||||
|
- **Llama4**: Expert routing for complex workflows
|
||||||
|
|
||||||
|
- **XAI Grok**: Advanced research capabilities
|
||||||
|
|
||||||
|
- **Cohere**: Strong business applications
|
||||||
|
|
||||||
|
## Environment Setup
|
||||||
|
|
||||||
|
Most providers require API keys. Add them to your `.env` file:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# OpenAI
|
||||||
|
OPENAI_API_KEY=your_openai_key
|
||||||
|
|
||||||
|
# Anthropic
|
||||||
|
ANTHROPIC_API_KEY=your_anthropic_key
|
||||||
|
|
||||||
|
# Groq
|
||||||
|
GROQ_API_KEY=your_groq_key
|
||||||
|
|
||||||
|
# Cohere
|
||||||
|
COHERE_API_KEY=your_cohere_key
|
||||||
|
|
||||||
|
# DeepSeek
|
||||||
|
DEEPSEEK_API_KEY=your_deepseek_key
|
||||||
|
|
||||||
|
# OpenRouter
|
||||||
|
OPENROUTER_API_KEY=your_openrouter_key
|
||||||
|
|
||||||
|
# XAI
|
||||||
|
XAI_API_KEY=your_xai_key
|
||||||
|
```
|
||||||
|
|
||||||
|
!!! note "No API Key Required"
|
||||||
|
Ollama and vLLM can be run locally without API keys, making them perfect for development and testing.
|
||||||
|
|
||||||
|
## Advanced Features
|
||||||
|
|
||||||
|
### Multi-Model Workflows
|
||||||
|
|
||||||
|
Swarms allows you to create workflows that use different models for different tasks:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent, ConcurrentWorkflow
|
||||||
|
|
||||||
|
# Research agent using Claude for analysis
|
||||||
|
research_agent = Agent(
|
||||||
|
agent_name="Research-Agent",
|
||||||
|
model_name="claude-3-sonnet-20240229",
|
||||||
|
system_prompt="You are a research expert."
|
||||||
|
)
|
||||||
|
|
||||||
|
# Creative agent using GPT-4o for content generation
|
||||||
|
creative_agent = Agent(
|
||||||
|
agent_name="Creative-Agent",
|
||||||
|
model_name="gpt-4o",
|
||||||
|
system_prompt="You are a creative content expert."
|
||||||
|
)
|
||||||
|
|
||||||
|
# Workflow combining both agents
|
||||||
|
workflow = ConcurrentWorkflow(
|
||||||
|
name="Research-Creative-Workflow",
|
||||||
|
agents=[research_agent, creative_agent]
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Model Routing
|
||||||
|
|
||||||
|
Automatically route tasks to the most appropriate model:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent, ModelRouter
|
||||||
|
|
||||||
|
# Define model preferences for different task types
|
||||||
|
model_router = ModelRouter(
|
||||||
|
models={
|
||||||
|
"analysis": "claude-3-sonnet-20240229",
|
||||||
|
"creative": "gpt-4o",
|
||||||
|
"fast": "gpt-4o-mini",
|
||||||
|
"local": "ollama/llama2"
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
# Agent will automatically choose the best model
|
||||||
|
agent = Agent(
|
||||||
|
agent_name="Smart-Agent",
|
||||||
|
llm=model_router,
|
||||||
|
system_prompt="You are a versatile assistant."
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Getting Help
|
||||||
|
|
||||||
|
- **Documentation**: Each provider has detailed documentation with examples
|
||||||
|
|
||||||
|
- **Community**: Join the Swarms community for support and best practices
|
||||||
|
|
||||||
|
- **Issues**: Report bugs and request features on GitHub
|
||||||
|
|
||||||
|
- **Discussions**: Share your use cases and learn from others
|
||||||
|
|
||||||
|
!!! success "Ready to Get Started?"
|
||||||
|
Choose a model provider from the table above and follow the detailed integration guide. Each provider offers unique capabilities that can enhance your Swarms applications.
|
@ -0,0 +1,77 @@
|
|||||||
|
# Processing Multiple Images
|
||||||
|
|
||||||
|
This tutorial shows how to process multiple images with a single agent using Swarms' multi-modal capabilities. You'll learn to configure an agent for batch image analysis, enabling efficient processing for quality control, object detection, or image comparison tasks.
|
||||||
|
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
Install the swarms package using pip:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pip install -U swarms
|
||||||
|
```
|
||||||
|
|
||||||
|
## Basic Setup
|
||||||
|
|
||||||
|
1. First, set up your environment variables:
|
||||||
|
|
||||||
|
```python
|
||||||
|
WORKSPACE_DIR="agent_workspace"
|
||||||
|
ANTHROPIC_API_KEY=""
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
## Code
|
||||||
|
|
||||||
|
- Create a list of images by their file paths
|
||||||
|
|
||||||
|
- Pass it into the `Agent.run(imgs=[str])` parameter
|
||||||
|
|
||||||
|
- Activate `summarize_multiple_images=True` if you want the agent to output a summary of the image analyses
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent
|
||||||
|
from swarms.prompts.logistics import (
|
||||||
|
Quality_Control_Agent_Prompt,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# Image for analysis
|
||||||
|
factory_image = "image.jpg"
|
||||||
|
|
||||||
|
# Quality control agent
|
||||||
|
quality_control_agent = Agent(
|
||||||
|
agent_name="Quality Control Agent",
|
||||||
|
agent_description="A quality control agent that analyzes images and provides a detailed report on the quality of the product in the image.",
|
||||||
|
model_name="claude-3-5-sonnet-20240620",
|
||||||
|
system_prompt=Quality_Control_Agent_Prompt,
|
||||||
|
multi_modal=True,
|
||||||
|
max_loops=1,
|
||||||
|
output_type="str-all-except-first",
|
||||||
|
summarize_multiple_images=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
response = quality_control_agent.run(
|
||||||
|
task="what is in the image?",
|
||||||
|
imgs=[factory_image, factory_image],
|
||||||
|
)
|
||||||
|
|
||||||
|
print(response)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Support and Community
|
||||||
|
|
||||||
|
If you're facing issues or want to learn more, check out the following resources to join our Discord, stay updated on Twitter, and watch tutorials on YouTube!
|
||||||
|
|
||||||
|
| Platform | Link | Description |
|
||||||
|
|----------|------|-------------|
|
||||||
|
| 📚 Documentation | [docs.swarms.world](https://docs.swarms.world) | Official documentation and guides |
|
||||||
|
| 📝 Blog | [Medium](https://medium.com/@kyeg) | Latest updates and technical articles |
|
||||||
|
| 💬 Discord | [Join Discord](https://discord.gg/jM3Z6M9uMq) | Live chat and community support |
|
||||||
|
| 🐦 Twitter | [@kyegomez](https://twitter.com/kyegomez) | Latest news and announcements |
|
||||||
|
| 👥 LinkedIn | [The Swarm Corporation](https://www.linkedin.com/company/the-swarm-corporation) | Professional network and updates |
|
||||||
|
| 📺 YouTube | [Swarms Channel](https://www.youtube.com/channel/UC9yXyitkbU_WSy7bd_41SqQ) | Tutorials and demos |
|
||||||
|
| 🎫 Events | [Sign up here](https://lu.ma/5p2jnc2v) | Join our community events |
|
||||||
|
|
@ -0,0 +1,72 @@
|
|||||||
|
# The Swarms Index
|
||||||
|
|
||||||
|
The Swarms Index is a comprehensive catalog of repositories under The Swarm Corporation, showcasing a wide array of tools, frameworks, and templates designed for building, deploying, and managing autonomous AI agents and multi-agent systems. These repositories focus on enterprise-grade solutions, spanning industries like healthcare, finance, marketing, and more, with an emphasis on scalability, security, and performance. Many repositories include templates to help developers quickly set up production-ready applications.
|
||||||
|
|
||||||
|
| Name | Description | Link |
|
||||||
|
|------|-------------|------|
|
||||||
|
| Phala-Deployment-Template | A guide and template for running Swarms Agents in a Trusted Execution Environment (TEE) using Phala Cloud, ensuring secure and isolated execution. | [https://github.com/The-Swarm-Corporation/Phala-Deployment-Template](https://github.com/The-Swarm-Corporation/Phala-Deployment-Template) |
|
||||||
|
| Swarms-API-Status-Page | A status page for monitoring the health and performance of the Swarms API. | [https://github.com/The-Swarm-Corporation/Swarms-API-Status-Page](https://github.com/The-Swarm-Corporation/Swarms-API-Status-Page) |
|
||||||
|
| Swarms-API-Phala-Template | A deployment solution template for running Swarms API on Phala Cloud, optimized for secure and scalable agent orchestration. | [https://github.com/The-Swarm-Corporation/Swarms-API-Phala-Template](https://github.com/The-Swarm-Corporation/Swarms-API-Phala-Template) |
|
||||||
|
| DevSwarm | Develop production-grade applications effortlessly with a single prompt, powered by a swarm of v0-driven autonomous agents operating 24/7 for fully autonomous software development. | [https://github.com/The-Swarm-Corporation/DevSwarm](https://github.com/The-Swarm-Corporation/DevSwarm) |
|
||||||
|
| Enterprise-Grade-Agents-Course | A comprehensive course teaching students to build, deploy, and manage autonomous agents for enterprise workflows using the Swarms library, focusing on scalability and integration. | [https://github.com/The-Swarm-Corporation/Enterprise-Grade-Agents-Course](https://github.com/The-Swarm-Corporation/Enterprise-Grade-Agents-Course) |
|
||||||
|
| agentverse | A collection of agents from top frameworks like Langchain, Griptape, and CrewAI, integrated into the Swarms ecosystem. | [https://github.com/The-Swarm-Corporation/agentverse](https://github.com/The-Swarm-Corporation/agentverse) |
|
||||||
|
| InsuranceSwarm | A swarm of agents to automate document processing and fraud detection in insurance claims. | [https://github.com/The-Swarm-Corporation/InsuranceSwarm](https://github.com/The-Swarm-Corporation/InsuranceSwarm) |
|
||||||
|
| swarms-examples | A vast array of examples for enterprise-grade and production-ready applications using the Swarms framework. | [https://github.com/The-Swarm-Corporation/swarms-examples](https://github.com/The-Swarm-Corporation/swarms-examples) |
|
||||||
|
| auto-ai-research-team | Automates AI research at an OpenAI level to accelerate innovation using swarms of agents. | [https://github.com/The-Swarm-Corporation/auto-ai-research-team](https://github.com/The-Swarm-Corporation/auto-ai-research-team) |
|
||||||
|
| Agents-Beginner-Guide | A definitive beginner's guide to AI agents and multi-agent systems, explaining fundamentals and industry applications. | [https://github.com/The-Swarm-Corporation/Agents-Beginner-Guide](https://github.com/The-Swarm-Corporation/Agents-Beginner-Guide) |
|
||||||
|
| Solana-Ecosystem-MCP | A collection of Solana tools wrapped in MCP servers for blockchain development. | [https://github.com/The-Swarm-Corporation/Solana-Ecosystem-MCP](https://github.com/The-Swarm-Corporation/Solana-Ecosystem-MCP) |
|
||||||
|
| automated-crypto-fund | A fully automated crypto fund leveraging swarms of LLM agents for real-money trading. | [https://github.com/The-Swarm-Corporation/automated-crypto-fund](https://github.com/The-Swarm-Corporation/automated-crypto-fund) |
|
||||||
|
| Mryaid | The first multi-agent social media platform powered by Swarms. | [https://github.com/The-Swarm-Corporation/Mryaid](https://github.com/The-Swarm-Corporation/Mryaid) |
|
||||||
|
| pharma-swarm | A swarm of autonomous agents for chemical analysis in the pharmaceutical industry. | [https://github.com/The-Swarm-Corporation/pharma-swarm](https://github.com/The-Swarm-Corporation/pharma-swarm) |
|
||||||
|
| Automated-Prompt-Engineering-Hub | A hub for tools and resources focused on automated prompt engineering for generative AI. | [https://github.com/The-Swarm-Corporation/Automated-Prompt-Engineering-Hub](https://github.com/The-Swarm-Corporation/Automated-Prompt-Engineering-Hub) |
|
||||||
|
| Multi-Agent-Template-App | A simple, reliable, and high-performance template for building multi-agent applications. | [https://github.com/The-Swarm-Corporation/Multi-Agent-Template-App](https://github.com/The-Swarm-Corporation/Multi-Agent-Template-App) |
|
||||||
|
| Cookbook | Examples and guides for using the Swarms Framework effectively. | [https://github.com/The-Swarm-Corporation/Cookbook](https://github.com/The-Swarm-Corporation/Cookbook) |
|
||||||
|
| SwarmDB | A production-grade message queue system for agent communication and LLM backend load balancing. | [https://github.com/The-Swarm-Corporation/SwarmDB](https://github.com/The-Swarm-Corporation/SwarmDB) |
|
||||||
|
| CryptoTaxSwarm | A personal advisory tax swarm for cryptocurrency transactions. | [https://github.com/The-Swarm-Corporation/CryptoTaxSwarm](https://github.com/The-Swarm-Corporation/CryptoTaxSwarm) |
|
||||||
|
| Multi-Agent-Marketing-Course | A course on automating marketing operations with enterprise-grade multi-agent collaboration. | [https://github.com/The-Swarm-Corporation/Multi-Agent-Marketing-Course](https://github.com/The-Swarm-Corporation/Multi-Agent-Marketing-Course) |
|
||||||
|
| Swarms-BrandBook | Branding guidelines and assets for Swarms.ai, embodying innovation and collaboration. | [https://github.com/The-Swarm-Corporation/Swarms-BrandBook](https://github.com/The-Swarm-Corporation/Swarms-BrandBook) |
|
||||||
|
| AgentAPI | A definitive API for managing and interacting with AI agents. | [https://github.com/The-Swarm-Corporation/AgentAPI](https://github.com/The-Swarm-Corporation/AgentAPI) |
|
||||||
|
| Research-Paper-Writer-Swarm | Automates the creation of high-quality research papers in LaTeX using Swarms agents. | [https://github.com/The-Swarm-Corporation/Research-Paper-Writer-Swarm](https://github.com/The-Swarm-Corporation/Research-Paper-Writer-Swarm) |
|
||||||
|
| swarms-sdk | A Python client for the Swarms API, providing a simple interface for managing AI swarms. | [https://github.com/The-Swarm-Corporation/swarms-sdk](https://github.com/The-Swarm-Corporation/swarms-sdk) |
|
||||||
|
| FluidAPI | A framework for interacting with APIs using natural language, simplifying complex requests. | [https://github.com/The-Swarm-Corporation/FluidAPI](https://github.com/The-Swarm-Corporation/FluidAPI) |
|
||||||
|
| MedicalCoderSwarm | A multi-agent system for comprehensive medical diagnosis and coding using specialized AI agents. | [https://github.com/The-Swarm-Corporation/MedicalCoderSwarm](https://github.com/The-Swarm-Corporation/MedicalCoderSwarm) |
|
||||||
|
| BackTesterAgent | An AI-powered backtesting framework for automated trading strategy validation and optimization. | [https://github.com/The-Swarm-Corporation/BackTesterAgent](https://github.com/The-Swarm-Corporation/BackTesterAgent) |
|
||||||
|
| .ai | The first natural language programming language powered by Swarms. | [https://github.com/The-Swarm-Corporation/.ai](https://github.com/The-Swarm-Corporation/.ai) |
|
||||||
|
| AutoHedge | An autonomous hedge fund leveraging swarm intelligence for market analysis and trade execution. | [https://github.com/The-Swarm-Corporation/AutoHedge](https://github.com/The-Swarm-Corporation/AutoHedge) |
|
||||||
|
| radiology-swarm | A multi-agent system for advanced radiological analysis, diagnosis, and treatment planning. | [https://github.com/The-Swarm-Corporation/radiology-swarm](https://github.com/The-Swarm-Corporation/radiology-swarm) |
|
||||||
|
| MedGuard | A Python library ensuring HIPAA compliance for LLM agents in healthcare applications. | [https://github.com/The-Swarm-Corporation/MedGuard](https://github.com/The-Swarm-Corporation/MedGuard) |
|
||||||
|
| doc-master | A lightweight Python library for automated file reading and content extraction. | [https://github.com/The-Swarm-Corporation/doc-master](https://github.com/The-Swarm-Corporation/doc-master) |
|
||||||
|
| Open-Aladdin | An open-source risk-management tool for stock and security risk analysis. | [https://github.com/The-Swarm-Corporation/Open-Aladdin](https://github.com/The-Swarm-Corporation/Open-Aladdin) |
|
||||||
|
| TickrAgent | A scalable Python library for building financial agents for comprehensive stock analysis. | [https://github.com/The-Swarm-Corporation/TickrAgent](https://github.com/The-Swarm-Corporation/TickrAgent) |
|
||||||
|
| NewsAgent | An enterprise-grade news aggregation agent for fetching, querying, and summarizing news. | [https://github.com/The-Swarm-Corporation/NewsAgent](https://github.com/The-Swarm-Corporation/NewsAgent) |
|
||||||
|
| Research-Paper-Hive | A platform for discovering and engaging with relevant research papers efficiently. | [https://github.com/The-Swarm-Corporation/Research-Paper-Hive](https://github.com/The-Swarm-Corporation/Research-Paper-Hive) |
|
||||||
|
| MedInsight-Pro | Revolutionizes medical research summarization for healthcare innovators. | [https://github.com/The-Swarm-Corporation/MedInsight-Pro](https://github.com/The-Swarm-Corporation/MedInsight-Pro) |
|
||||||
|
| swarms-memory | Pre-built wrappers for RAG systems like ChromaDB, Weaviate, and Pinecone. | [https://github.com/The-Swarm-Corporation/swarms-memory](https://github.com/The-Swarm-Corporation/swarms-memory) |
|
||||||
|
| CryptoAgent | An enterprise-grade solution for fetching, analyzing, and summarizing cryptocurrency data. | [https://github.com/The-Swarm-Corporation/CryptoAgent](https://github.com/The-Swarm-Corporation/CryptoAgent) |
|
||||||
|
| AgentParse | A high-performance parsing library for mapping structured data into agent-understandable blocks. | [https://github.com/The-Swarm-Corporation/AgentParse](https://github.com/The-Swarm-Corporation/AgentParse) |
|
||||||
|
| CodeGuardian | An intelligent agent for automating the generation of production-grade unit tests for Python code. | [https://github.com/The-Swarm-Corporation/CodeGuardian](https://github.com/The-Swarm-Corporation/CodeGuardian) |
|
||||||
|
| Marketing-Swarm-Template | A framework for creating multi-platform marketing content using Swarms AI agents. | [https://github.com/The-Swarm-Corporation/Marketing-Swarm-Template](https://github.com/The-Swarm-Corporation/Marketing-Swarm-Template) |
|
||||||
|
| HTX-Swarm | A multi-agent system for real-time market analysis of HTX exchange data. | [https://github.com/The-Swarm-Corporation/HTX-Swarm](https://github.com/The-Swarm-Corporation/HTX-Swarm) |
|
||||||
|
| MultiModelOptimizer | A hierarchical parameter synchronization approach for joint training of transformer models. | [https://github.com/The-Swarm-Corporation/MultiModelOptimizer](https://github.com/The-Swarm-Corporation/MultiModelOptimizer) |
|
||||||
|
| MortgageUnderwritingSwarm | A multi-agent pipeline for automating mortgage underwriting processes. | [https://github.com/The-Swarm-Corporation/MortgageUnderwritingSwarm](https://github.com/The-Swarm-Corporation/MortgageUnderwritingSwarm) |
|
||||||
|
| DermaSwarm | A multi-agent system for dermatologists to diagnose and treat skin conditions collaboratively. | [https://github.com/The-Swarm-Corporation/DermaSwarm](https://github.com/The-Swarm-Corporation/DermaSwarm) |
|
||||||
|
| IoTAgents | Integrates IoT data with AI agents for seamless parsing and processing of data streams. | [https://github.com/The-Swarm-Corporation/IoTAgents](https://github.com/The-Swarm-Corporation/IoTAgents) |
|
||||||
|
| eth-agent | An autonomous agent for analyzing on-chain Ethereum data. | [https://github.com/The-Swarm-Corporation/eth-agent](https://github.com/The-Swarm-Corporation/eth-agent) |
|
||||||
|
| Medical-Swarm-One-Click | A template for building safe, reliable, and production-grade medical multi-agent systems. | [https://github.com/The-Swarm-Corporation/Medical-Swarm-One-Click](https://github.com/The-Swarm-Corporation/Medical-Swarm-One-Click) |
|
||||||
|
| Swarms-Example-1-Click-Template | A one-click template for building Swarms applications quickly. | [https://github.com/The-Swarm-Corporation/Swarms-Example-1-Click-Template](https://github.com/The-Swarm-Corporation/Swarms-Example-1-Click-Template) |
|
||||||
|
| Custom-Swarms-Spec-Template | An official specification template for custom swarm development using the Swarms Framework. | [https://github.com/The-Swarm-Corporation/Custom-Swarms-Spec-Template](https://github.com/The-Swarm-Corporation/Custom-Swarms-Spec-Template) |
|
||||||
|
| Swarms-LlamaIndex-RAG-Template | A template for integrating Llama Index into Swarms applications for RAG capabilities. | [https://github.com/The-Swarm-Corporation/Swarms-LlamaIndex-RAG-Template](https://github.com/The-Swarm-Corporation/Swarms-LlamaIndex-RAG-Template) |
|
||||||
|
| ForexTreeSwarm | A forex market analysis system using a swarm of AI agents organized in a forest structure. | [https://github.com/The-Swarm-Corporation/ForexTreeSwarm](https://github.com/The-Swarm-Corporation/ForexTreeSwarm) |
|
||||||
|
| Generalist-Mathematician-Swarm | A swarm of agents for solving complex mathematical problems collaboratively. | [https://github.com/The-Swarm-Corporation/Generalist-Mathematician-Swarm](https://github.com/The-Swarm-Corporation/Generalist-Mathematician-Swarm) |
|
||||||
|
| Multi-Modal-XRAY-Diagnosis-Medical-Swarm-Template | A template for analyzing X-rays, MRIs, and more using a swarm of agents. | [https://github.com/The-Swarm-Corporation/Multi-Modal-XRAY-Diagnosis-Medical-Swarm-Template](https://github.com/The-Swarm-Corporation/Multi-Modal-XRAY-Diagnosis-Medical-Swarm-Template) |
|
||||||
|
| AgentRAGProtocol | A protocol for integrating Retrieval-Augmented Generation (RAG) into AI agents. | [https://github.com/The-Swarm-Corporation/AgentRAGProtocol](https://github.com/The-Swarm-Corporation/AgentRAGProtocol) |
|
||||||
|
| Multi-Agent-RAG-Template | A template for creating collaborative AI agent teams for document processing and analysis. | [https://github.com/The-Swarm-Corporation/Multi-Agent-RAG-Template](https://github.com/The-Swarm-Corporation/Multi-Agent-RAG-Template) |
|
||||||
|
| REACT-Yaml-Agent | An implementation of a REACT agent using YAML instead of JSON. | [https://github.com/The-Swarm-Corporation/REACT-Yaml-Agent](https://github.com/The-Swarm-Corporation/REACT-Yaml-Agent) |
|
||||||
|
| SwarmsXGCP | A template for deploying Swarms agents on Google Cloud Run. | [https://github.com/The-Swarm-Corporation/SwarmsXGCP](https://github.com/The-Swarm-Corporation/SwarmsXGCP) |
|
||||||
|
| Legal-Swarm-Template | A one-click template for building legal-focused Swarms applications. | [https://github.com/The-Swarm-Corporation/Legal-Swarm-Template](https://github.com/The-Swarm-Corporation/Legal-Swarm-Template) |
|
||||||
|
| swarms_sim | A simulation of a swarm of agents in a professional workplace environment. | [https://github.com/The-Swarm-Corporation/swarms_sim](https://github.com/The-Swarm-Corporation/swarms_sim) |
|
||||||
|
| medical-problems | A repository for medical problems to create Swarms applications for. | [https://github.com/The-Swarm-Corporation/medical-problems](https://github.com/The-Swarm-Corporation/medical-problems) |
|
||||||
|
| swarm-ecosystem | An overview of the Swarm Ecosystem and its components. | [https://github.com/The-Swarm-Corporation/swarm-ecosystem](https://github.com/The-Swarm-Corporation/swarm-ecosystem) |
|
||||||
|
| swarms_ecosystem_md | MDX documentation for the Swarm Ecosystem. | [https://github.com/The-Swarm-Corporation/swarms_ecosystem_md](https://github.com/The-Swarm-Corporation/swarms_ecosystem_md) |
|
||||||
|
|
||||||
|
|
@ -0,0 +1,138 @@
|
|||||||
|
# Agents with Vision and Tool Usage
|
||||||
|
|
||||||
|
This tutorial demonstrates how to create intelligent agents that can analyze images and use custom tools to perform specific actions based on their visual observations. You'll learn to build a quality control agent that can process images, identify potential security concerns, and automatically trigger appropriate responses using function calling capabilities.
|
||||||
|
|
||||||
|
## What You'll Learn
|
||||||
|
|
||||||
|
- How to configure an agent with multi-modal capabilities for image analysis
|
||||||
|
- How to integrate custom tools and functions with vision-enabled agents
|
||||||
|
- How to implement automated security analysis based on visual observations
|
||||||
|
- How to use function calling to trigger specific actions from image analysis results
|
||||||
|
- Best practices for building production-ready vision agents with tool integration
|
||||||
|
|
||||||
|
## Use Cases
|
||||||
|
|
||||||
|
This approach is perfect for:
|
||||||
|
|
||||||
|
- **Quality Control Systems**: Automated inspection of manufacturing processes
|
||||||
|
|
||||||
|
- **Security Monitoring**: Real-time threat detection and response
|
||||||
|
|
||||||
|
- **Object Detection**: Identifying and categorizing items in images
|
||||||
|
|
||||||
|
- **Compliance Checking**: Ensuring standards are met in various environments
|
||||||
|
|
||||||
|
- **Automated Reporting**: Generating detailed analysis reports from visual data
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
Install the swarms package using pip:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pip install -U swarms
|
||||||
|
```
|
||||||
|
|
||||||
|
## Basic Setup
|
||||||
|
|
||||||
|
1. First, set up your environment variables:
|
||||||
|
|
||||||
|
```python
|
||||||
|
WORKSPACE_DIR="agent_workspace"
|
||||||
|
OPENAI_API_KEY=""
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
## Code
|
||||||
|
|
||||||
|
- Create tools for your agent as a function with types and documentation
|
||||||
|
|
||||||
|
- Pass tools to your agent `Agent(tools=[list_of_callables])`
|
||||||
|
|
||||||
|
- Add your image path to the run method like: `Agent().run(task=task, img=img)`
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms.structs import Agent
|
||||||
|
from swarms.prompts.logistics import (
|
||||||
|
Quality_Control_Agent_Prompt,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# Image for analysis
|
||||||
|
factory_image = "image.jpg"
|
||||||
|
|
||||||
|
|
||||||
|
def security_analysis(danger_level: str) -> str:
|
||||||
|
"""
|
||||||
|
Analyzes the security danger level and returns an appropriate response.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
danger_level (str, optional): The level of danger to analyze.
|
||||||
|
Can be "low", "medium", "high", or None. Defaults to None.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: A string describing the danger level assessment.
|
||||||
|
- "No danger level provided" if danger_level is None
|
||||||
|
- "No danger" if danger_level is "low"
|
||||||
|
- "Medium danger" if danger_level is "medium"
|
||||||
|
- "High danger" if danger_level is "high"
|
||||||
|
- "Unknown danger level" for any other value
|
||||||
|
"""
|
||||||
|
if danger_level is None:
|
||||||
|
return "No danger level provided"
|
||||||
|
|
||||||
|
if danger_level == "low":
|
||||||
|
return "No danger"
|
||||||
|
|
||||||
|
if danger_level == "medium":
|
||||||
|
return "Medium danger"
|
||||||
|
|
||||||
|
if danger_level == "high":
|
||||||
|
return "High danger"
|
||||||
|
|
||||||
|
return "Unknown danger level"
|
||||||
|
|
||||||
|
|
||||||
|
custom_system_prompt = f"""
|
||||||
|
{Quality_Control_Agent_Prompt}
|
||||||
|
|
||||||
|
You have access to tools that can help you with your analysis. When you need to perform a security analysis, you MUST use the security_analysis function with an appropriate danger level (low, medium, or high) based on your observations.
|
||||||
|
|
||||||
|
Always use the available tools when they are relevant to the task. If you determine there is any level of danger or security concern, call the security_analysis function with the appropriate danger level.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# Quality control agent
|
||||||
|
quality_control_agent = Agent(
|
||||||
|
agent_name="Quality Control Agent",
|
||||||
|
agent_description="A quality control agent that analyzes images and provides a detailed report on the quality of the product in the image.",
|
||||||
|
# model_name="anthropic/claude-3-opus-20240229",
|
||||||
|
model_name="gpt-4o-mini",
|
||||||
|
system_prompt=custom_system_prompt,
|
||||||
|
multi_modal=True,
|
||||||
|
max_loops=1,
|
||||||
|
output_type="str-all-except-first",
|
||||||
|
# tools_list_dictionary=[schema],
|
||||||
|
tools=[security_analysis],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
response = quality_control_agent.run(
|
||||||
|
task="Analyze the image and then perform a security analysis. Based on what you see in the image, determine if there is a low, medium, or high danger level and call the security_analysis function with that danger level",
|
||||||
|
img=factory_image,
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
## Support and Community
|
||||||
|
|
||||||
|
If you're facing issues or want to learn more, check out the following resources to join our Discord, stay updated on Twitter, and watch tutorials on YouTube!
|
||||||
|
|
||||||
|
| Platform | Link | Description |
|
||||||
|
|----------|------|-------------|
|
||||||
|
| 📚 Documentation | [docs.swarms.world](https://docs.swarms.world) | Official documentation and guides |
|
||||||
|
| 📝 Blog | [Medium](https://medium.com/@kyeg) | Latest updates and technical articles |
|
||||||
|
| 💬 Discord | [Join Discord](https://discord.gg/jM3Z6M9uMq) | Live chat and community support |
|
||||||
|
| 🐦 Twitter | [@kyegomez](https://twitter.com/kyegomez) | Latest news and announcements |
|
||||||
|
| 👥 LinkedIn | [The Swarm Corporation](https://www.linkedin.com/company/the-swarm-corporation) | Professional network and updates |
|
||||||
|
| 📺 YouTube | [Swarms Channel](https://www.youtube.com/channel/UC9yXyitkbU_WSy7bd_41SqQ) | Tutorials and demos |
|
||||||
|
| 🎫 Events | [Sign up here](https://lu.ma/5p2jnc2v) | Join our community events |
|
||||||
|
|
@ -0,0 +1,42 @@
|
|||||||
|
## ✨ Enterprise Features
|
||||||
|
|
||||||
|
Swarms delivers a comprehensive, enterprise-grade multi-agent infrastructure platform designed for production-scale deployments and seamless integration with existing systems.
|
||||||
|
|
||||||
|
| Category | Enterprise Capabilities | Business Value |
|
||||||
|
|----------|------------------------|----------------|
|
||||||
|
| 🏢 **Enterprise Architecture** | • Production-Ready Infrastructure<br>• High Availability Systems<br>• Modular Microservices Design<br>• Comprehensive Observability<br>• Backwards Compatibility | • 99.9%+ Uptime Guarantee<br>• Reduced Operational Overhead<br>• Seamless Legacy Integration<br>• Enhanced System Monitoring<br>• Risk-Free Migration Path |
|
||||||
|
| 🤖 **Multi-Agent Orchestration** | • Hierarchical Agent Swarms<br>• Parallel Processing Pipelines<br>• Sequential Workflow Orchestration<br>• Graph-Based Agent Networks<br>• Dynamic Agent Composition<br>• Agent Registry Management | • Complex Business Process Automation<br>• Scalable Task Distribution<br>• Flexible Workflow Adaptation<br>• Optimized Resource Utilization<br>• Centralized Agent Governance<br>• Enterprise-Grade Agent Lifecycle Management |
|
||||||
|
| 🔄 **Enterprise Integration** | • Multi-Model Provider Support<br>• Custom Agent Development Framework<br>• Extensive Enterprise Tool Library<br>• Multiple Memory Systems<br>• Backwards Compatibility with LangChain, AutoGen, CrewAI<br>• Standardized API Interfaces | • Vendor-Agnostic Architecture<br>• Custom Solution Development<br>• Extended Functionality Integration<br>• Enhanced Knowledge Management<br>• Seamless Framework Migration<br>• Reduced Integration Complexity |
|
||||||
|
| 📈 **Enterprise Scalability** | • Concurrent Multi-Agent Processing<br>• Intelligent Resource Management<br>• Load Balancing & Auto-Scaling<br>• Horizontal Scaling Capabilities<br>• Performance Optimization<br>• Capacity Planning Tools | • High-Throughput Processing<br>• Cost-Effective Resource Utilization<br>• Elastic Scaling Based on Demand<br>• Linear Performance Scaling<br>• Optimized Response Times<br>• Predictable Growth Planning |
|
||||||
|
| 🛠️ **Developer Experience** | • Intuitive Enterprise API<br>• Comprehensive Documentation<br>• Active Enterprise Community<br>• CLI & SDK Tools<br>• IDE Integration Support<br>• Code Generation Templates | • Accelerated Development Cycles<br>• Reduced Learning Curve<br>• Expert Community Support<br>• Rapid Deployment Capabilities<br>• Enhanced Developer Productivity<br>• Standardized Development Patterns |
|
||||||
|
| 🔐 **Enterprise Security** | • Comprehensive Error Handling<br>• Advanced Rate Limiting<br>• Real-Time Monitoring Integration<br>• Detailed Audit Logging<br>• Role-Based Access Control<br>• Data Encryption & Privacy | • Enhanced System Reliability<br>• API Security Protection<br>• Proactive Issue Detection<br>• Regulatory Compliance Support<br>• Granular Access Management<br>• Enterprise Data Protection |
|
||||||
|
| 📊 **Advanced Enterprise Features** | • SpreadsheetSwarm for Mass Agent Management<br>• Group Chat for Collaborative AI<br>• Centralized Agent Registry<br>• Mixture of Agents for Complex Solutions<br>• Agent Performance Analytics<br>• Automated Agent Optimization | • Large-Scale Agent Operations<br>• Team-Based AI Collaboration<br>• Centralized Agent Governance<br>• Sophisticated Problem Solving<br>• Performance Insights & Optimization<br>• Continuous Agent Improvement |
|
||||||
|
| 🔌 **Provider Ecosystem** | • OpenAI Integration<br>• Anthropic Claude Support<br>• ChromaDB Vector Database<br>• Custom Provider Framework<br>• Multi-Cloud Deployment<br>• Hybrid Infrastructure Support | • Provider Flexibility & Independence<br>• Advanced Vector Search Capabilities<br>• Custom Integration Development<br>• Cloud-Agnostic Architecture<br>• Flexible Deployment Options<br>• Risk Mitigation Through Diversification |
|
||||||
|
| 💪 **Production Readiness** | • Automatic Retry Mechanisms<br>• Asynchronous Processing Support<br>• Environment Configuration Management<br>• Type Safety & Validation<br>• Health Check Endpoints<br>• Graceful Degradation | • Enhanced System Reliability<br>• Improved Performance Characteristics<br>• Simplified Configuration Management<br>• Reduced Runtime Errors<br>• Proactive Health Monitoring<br>• Continuous Service Availability |
|
||||||
|
| 🎯 **Enterprise Use Cases** | • Industry-Specific Agent Solutions<br>• Custom Workflow Development<br>• Regulatory Compliance Support<br>• Extensible Framework Architecture<br>• Multi-Tenant Support<br>• Enterprise SLA Guarantees | • Rapid Industry Deployment<br>• Flexible Solution Architecture<br>• Compliance-Ready Implementations<br>• Future-Proof Technology Investment<br>• Scalable Multi-Client Operations<br>• Predictable Service Quality |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🚀 Missing a Feature?
|
||||||
|
|
||||||
|
Swarms is continuously evolving to meet enterprise needs. If you don't see a specific feature or capability that your organization requires:
|
||||||
|
|
||||||
|
### 📝 **Report Missing Features**
|
||||||
|
|
||||||
|
- Create a [GitHub Issue](https://github.com/kyegomez/swarms/issues) to request new features
|
||||||
|
|
||||||
|
- Describe your use case and business requirements
|
||||||
|
|
||||||
|
- Our team will evaluate and prioritize based on enterprise demand
|
||||||
|
|
||||||
|
### 📞 **Schedule a Consultation**
|
||||||
|
|
||||||
|
- [Book a call with our enterprise team](https://cal.com/swarms/swarms-onboarding-session) for personalized guidance
|
||||||
|
|
||||||
|
- Discuss your specific multi-agent architecture requirements
|
||||||
|
|
||||||
|
- Get expert recommendations for your implementation strategy
|
||||||
|
|
||||||
|
- Explore custom enterprise solutions and integrations
|
||||||
|
|
||||||
|
Our team is committed to ensuring Swarms meets your enterprise multi-agent infrastructure needs. We welcome feedback and collaboration to build the most comprehensive platform for production-scale AI agent deployments.
|
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,59 @@
|
|||||||
|
# Swarms API Rate Limits
|
||||||
|
|
||||||
|
The Swarms API implements rate limiting to ensure fair usage and system stability. Here are the current limits:
|
||||||
|
|
||||||
|
## Standard Rate Limits
|
||||||
|
|
||||||
|
- **General API Requests**: 100 requests per minute
|
||||||
|
- **Batch Operations**: Maximum 10 requests per batch for agent/swarm batch operations
|
||||||
|
|
||||||
|
## Rate Limit Response
|
||||||
|
|
||||||
|
When you exceed the rate limit, the API will return a 429 (Too Many Requests) status code with the following message:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"detail": "Rate limit exceeded. Please try again later."
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Batch Operation Limits
|
||||||
|
|
||||||
|
For batch operations (`/v1/agent/batch/completions` and `/v1/swarm/batch/completions`):
|
||||||
|
|
||||||
|
- Maximum 10 concurrent requests per batch
|
||||||
|
|
||||||
|
- Exceeding this limit will result in a 400 (Bad Request) error
|
||||||
|
|
||||||
|
## Increasing Your Rate Limits
|
||||||
|
|
||||||
|
Need higher rate limits for your application? You can increase your limits by subscribing to a higher tier plan at [swarms.world/pricing](https://swarms.world/pricing).
|
||||||
|
|
||||||
|
Higher tier plans offer:
|
||||||
|
|
||||||
|
- Increased rate limits
|
||||||
|
|
||||||
|
- Higher batch operation limits
|
||||||
|
|
||||||
|
- Priority processing
|
||||||
|
|
||||||
|
- Dedicated support
|
||||||
|
|
||||||
|
## Best Practices
|
||||||
|
|
||||||
|
To make the most of your rate limits:
|
||||||
|
|
||||||
|
1. Implement proper error handling for rate limit responses
|
||||||
|
|
||||||
|
2. Use batch operations when processing multiple requests
|
||||||
|
|
||||||
|
3. Add appropriate retry logic with exponential backoff
|
||||||
|
|
||||||
|
4. Monitor your API usage to stay within limits
|
||||||
|
|
||||||
|
## Rate Limit Headers
|
||||||
|
|
||||||
|
The API does not currently expose rate limit headers. We recommend implementing your own request tracking to stay within the limits.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
For questions about rate limits or to request a custom plan for higher limits, please contact our support team or visit [swarms.world/pricing](https://swarms.world/pricing).
|
@ -1,54 +1,30 @@
|
|||||||
### Available Swarms in The Swarms API
|
# Multi-Agent Architectures
|
||||||
|
|
||||||
| Swarm Type | Description (English) | Description (Chinese) |
|
Each multi-agent architecture type is designed for specific use cases and can be combined to create powerful multi-agent systems. Here's a comprehensive overview of each available swarm:
|
||||||
|----------------------|-----------------------------------------------------------------------------|----------------------------------------------------------------------------|
|
|
||||||
| AgentRearrange | A swarm type focused on rearranging agents for optimal performance. | 一种专注于重新排列代理以实现最佳性能的群类型。 |
|
|
||||||
| MixtureOfAgents | Combines different types of agents to achieve a specific goal. | 结合不同类型的代理以实现特定目标。 |
|
|
||||||
| SpreadSheetSwarm | Utilizes spreadsheet-like structures for data management and operations. | 利用类似电子表格的结构进行数据管理和操作。 |
|
|
||||||
| SequentialWorkflow | Executes tasks in a sequential manner. | 以顺序方式执行任务。 |
|
|
||||||
| ConcurrentWorkflow | Allows tasks to be executed concurrently for efficiency. | 允许任务并发执行以提高效率。 |
|
|
||||||
| GroupChat | Facilitates communication among agents in a group chat format. | 以群聊格式促进代理之间的沟通。 |
|
|
||||||
| MultiAgentRouter | Routes tasks and information among multiple agents. | 在多个代理之间路由任务和信息。 |
|
|
||||||
| AutoSwarmBuilder | Automatically builds and configures swarms based on predefined criteria. | 根据预定义标准自动构建和配置群。 |
|
|
||||||
| HiearchicalSwarm | Organizes agents in a hierarchical structure for task delegation. | 以层次结构组织代理以进行任务委派。 |
|
|
||||||
| auto | Automatically selects the best swarm type based on the context. | 根据上下文自动选择最佳群类型。 |
|
|
||||||
| MajorityVoting | Uses majority voting among agents to make decisions. | 使用代理之间的多数投票来做出决策。 |
|
|
||||||
| MALT | A specialized swarm type for specific tasks (details needed). | 一种专门为特定任务设计的群类型(需要详细信息)。 |
|
|
||||||
|
|
||||||
### Documentation for Swarms
|
| Swarm Type | Description | Learn More |
|
||||||
|
|---------------------|------------------------------------------------------------------------------|------------|
|
||||||
|
| AgentRearrange | Dynamically reorganizes agents to optimize task performance and efficiency. Optimizes agent performance by dynamically adjusting their roles and positions within the workflow. This architecture is particularly useful when the effectiveness of agents depends on their sequence or arrangement. | [Learn More](/swarms/structs/agent_rearrange) |
|
||||||
|
| MixtureOfAgents | Creates diverse teams of specialized agents, each bringing unique capabilities to solve complex problems. Each agent contributes unique skills to achieve the overall goal, making it excel at tasks requiring multiple types of expertise or processing. | [Learn More](/swarms/structs/moa) |
|
||||||
|
| SpreadSheetSwarm | Provides a structured approach to data management and operations, making it ideal for tasks involving data analysis, transformation, and systematic processing in a spreadsheet-like structure. | [Learn More](/swarms/structs/spreadsheet_swarm) |
|
||||||
|
| SequentialWorkflow | Ensures strict process control by executing tasks in a predefined order. Perfect for workflows where each step depends on the completion of previous steps. | [Learn More](/swarms/structs/sequential_workflow) |
|
||||||
|
| ConcurrentWorkflow | Maximizes efficiency by running independent tasks in parallel, significantly reducing overall processing time for complex operations. Ideal for independent tasks that can be processed simultaneously. | [Learn More](/swarms/structs/concurrentworkflow) |
|
||||||
|
| GroupChat | Enables dynamic collaboration between agents through a chat-based interface, facilitating real-time information sharing and decision-making. | [Learn More](/swarms/structs/group_chat) |
|
||||||
|
| MultiAgentRouter | Acts as an intelligent task dispatcher, ensuring optimal distribution of work across available agents based on their capabilities and current workload. | [Learn More](/swarms/structs/multi_agent_router) |
|
||||||
|
| AutoSwarmBuilder | Simplifies swarm creation by automatically configuring agent architectures based on task requirements and performance metrics. | [Learn More](/swarms/structs/auto_swarm_builder) |
|
||||||
|
| HiearchicalSwarm | Implements a structured approach to task management, with clear lines of authority and delegation across multiple agent levels. | [Learn More](/swarms/structs/multi_swarm_orchestration) |
|
||||||
|
| auto | Provides intelligent swarm selection based on context, automatically choosing the most effective architecture for given tasks. | [Learn More](/swarms/concept/how_to_choose_swarms) |
|
||||||
|
| MajorityVoting | Implements robust decision-making through consensus, particularly useful for tasks requiring collective intelligence or verification. | [Learn More](/swarms/structs/majorityvoting) |
|
||||||
|
| MALT | Specialized framework for language-based tasks, optimizing agent collaboration for complex language processing operations. | [Learn More](/swarms/structs/malt) |
|
||||||
|
|
||||||
1. **AgentRearrange**: This swarm type is designed to rearrange agents to optimize their performance in a given task. It is useful in scenarios where agent positioning or order affects the outcome.
|
# Learn More
|
||||||
- 这种群类型旨在重新排列代理以优化其在给定任务中的性能。它在代理位置或顺序影响结果的情况下非常有用。
|
|
||||||
|
|
||||||
2. **MixtureOfAgents**: This type combines various agents, each with unique capabilities, to work together towards a common goal. It leverages the strengths of different agents to enhance overall performance.
|
To learn more about Swarms architecture and how different swarm types work together, visit our comprehensive guides:
|
||||||
- 这种类型结合了各种代理,每个代理都有独特的能力,共同努力实现共同目标。它利用不同代理的优势来提高整体性能。
|
|
||||||
|
|
||||||
3. **SpreadSheetSwarm**: This swarm type uses spreadsheet-like structures to manage and operate on data. It is ideal for tasks that require organized data manipulation and analysis.
|
- [Introduction to Multi-Agent Architectures](/swarms/concept/swarm_architectures)
|
||||||
- 这种群类型使用类似电子表格的结构来管理和操作数据。它非常适合需要有组织的数据操作和分析的任务。
|
|
||||||
|
|
||||||
4. **SequentialWorkflow**: Tasks are executed one after another in this swarm type, ensuring that each step is completed before the next begins. It is suitable for processes that require strict order.
|
- [How to Choose the Right Multi-Agent Architecture](/swarms/concept/how_to_choose_swarms)
|
||||||
- 在这种群类型中,任务一个接一个地执行,确保每个步骤在下一个步骤开始之前完成。它适用于需要严格顺序的流程。
|
|
||||||
|
|
||||||
5. **ConcurrentWorkflow**: This type allows multiple tasks to be executed simultaneously, improving efficiency and reducing time for completion. It is best for independent tasks that do not rely on each other.
|
- [Framework Architecture Overview](/swarms/concept/framework_architecture)
|
||||||
- 这种类型允许多个任务同时执行,提高效率并减少完成时间。它最适合不相互依赖的独立任务。
|
|
||||||
|
|
||||||
6. **GroupChat**: Facilitates communication among agents in a group chat format, enabling real-time collaboration and decision-making.
|
- [Building Custom Swarms](/swarms/structs/custom_swarm)
|
||||||
- 以群聊格式促进代理之间的沟通,实现实时协作和决策。
|
|
||||||
|
|
||||||
7. **MultiAgentRouter**: This swarm type routes tasks and information among multiple agents, ensuring that each agent receives the necessary data to perform its function.
|
|
||||||
- 这种群类型在多个代理之间路由任务和信息,确保每个代理接收到执行其功能所需的数据。
|
|
||||||
|
|
||||||
8. **AutoSwarmBuilder**: Automatically builds and configures swarms based on predefined criteria, reducing the need for manual setup and configuration.
|
|
||||||
- 根据预定义标准自动构建和配置群,减少手动设置和配置的需要。
|
|
||||||
|
|
||||||
9. **HiearchicalSwarm**: Organizes agents in a hierarchical structure, allowing for efficient task delegation and management.
|
|
||||||
- 以层次结构组织代理,允许高效的任务委派和管理。
|
|
||||||
|
|
||||||
10. **auto**: Automatically selects the most appropriate swarm type based on the context and requirements of the task.
|
|
||||||
- 根据任务的上下文和要求自动选择最合适的群类型。
|
|
||||||
|
|
||||||
11. **MajorityVoting**: Uses a majority voting mechanism among agents to make decisions, ensuring that the most popular choice is selected.
|
|
||||||
- 使用代理之间的多数投票机制来做出决策,确保选择最受欢迎的选项。
|
|
||||||
|
|
||||||
12. **MALT**: A specialized swarm type designed for specific tasks. Further details are needed to fully document this type.
|
|
||||||
- 一种专门为特定任务设计的群类型。需要进一步的详细信息来完整记录这种类型。
|
|
||||||
|
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,126 @@
|
|||||||
|
# Swarms.World Monetization Guide
|
||||||
|
|
||||||
|
## Quick Overview
|
||||||
|
|
||||||
|
Swarms Marketplace has activated its payment infrastructure, enabling creators to monetize AI agents, prompts, and tools directly through the platform. Sellers receive payments minus a 5-15% platform fee, scaled based on subscription tiers. Revenue accrues in real-time to integrated crypto wallets, with optional fiat conversions.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Eligibility Requirements
|
||||||
|
|
||||||
|
### Current Requirements for Paid Content
|
||||||
|
|
||||||
|
- **2+ published items** (Prompts, Agents, and Tools)
|
||||||
|
|
||||||
|
- **2 Items with 4+ star ratings** (you need community ratings)
|
||||||
|
|
||||||
|
- **Marketplace Agent Rating** An agent will automatically rate your prompt, agent, or tool.
|
||||||
|
|
||||||
|
**Bottom Line**: You must build reputation with free, high-quality content first.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step-by-Step Process
|
||||||
|
|
||||||
|
### Phase 1: Build Reputation (Required First)
|
||||||
|
|
||||||
|
#### 1. Improve Your Existing Content
|
||||||
|
|
||||||
|
- Add better descriptions and examples to your published items
|
||||||
|
|
||||||
|
- Use the Rating System: Evaluate and rate prompts, agents, and tools based on their effectiveness. Commenting System: Share feedback and insights with the Swarms community
|
||||||
|
|
||||||
|
- Ask users for honest reviews and ratings
|
||||||
|
|
||||||
|
#### 2. Create More Quality Content
|
||||||
|
|
||||||
|
Focus on these categories:
|
||||||
|
|
||||||
|
- **Agents**: Marketing, finance, or programming automation
|
||||||
|
|
||||||
|
- **Prompts**: Templates for specific business tasks
|
||||||
|
|
||||||
|
- **Tools**: Utilities that solve real problems
|
||||||
|
|
||||||
|
Target: 3-5 additional items, all aiming for 4+ star ratings
|
||||||
|
|
||||||
|
#### 3. Get Community Ratings
|
||||||
|
|
||||||
|
- Share your content in relevant communities
|
||||||
|
|
||||||
|
- Engage with users who try your content
|
||||||
|
|
||||||
|
- Respond to feedback and improve based on comments
|
||||||
|
|
||||||
|
- Be patient - ratings take time to accumulate
|
||||||
|
|
||||||
|
### Phase 2: Start Monetizing
|
||||||
|
|
||||||
|
#### 4. Choose Your Pricing Model
|
||||||
|
|
||||||
|
Three primary monetization avenues exist: AI agents (autonomous task-execution models), prompts (pre-optimized input templates), and tools (development utilities like data preprocessors)
|
||||||
|
|
||||||
|
**Pricing Options:**
|
||||||
|
|
||||||
|
- **One-time**: $0.01 - $999,999 USD
|
||||||
|
|
||||||
|
- **Subscription**: Monthly/annual recurring fees (Coming Soon)
|
||||||
|
|
||||||
|
- **Usage-based**: Pay per API call or computation (Coming Soon)
|
||||||
|
|
||||||
|
|
||||||
|
#### 6. Optimize & Scale
|
||||||
|
|
||||||
|
- Monitor your revenue and user feedback
|
||||||
|
|
||||||
|
- Developers can bundle assets—such as pairing prompt libraries with compatible agents—creating value-added
|
||||||
|
packages
|
||||||
|
|
||||||
|
- Create bundles of related content for higher value
|
||||||
|
|
||||||
|
- Adjust pricing based on demand
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Revenue Models
|
||||||
|
|
||||||
|
### What Sells Best
|
||||||
|
|
||||||
|
1. **Business Automation Agents** - Marketing, sales, finance
|
||||||
|
|
||||||
|
2. **Industry-Specific Prompts** - Legal, medical, technical writing
|
||||||
|
|
||||||
|
3. **Integration Tools** - APIs, data processors, connectors
|
||||||
|
|
||||||
|
### Pricing Examples
|
||||||
|
|
||||||
|
- Simple prompts: $1-50
|
||||||
|
|
||||||
|
- Complex agents: $20-500+
|
||||||
|
|
||||||
|
- Enterprise tools: $100-1000+
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Quick Tips for Success
|
||||||
|
|
||||||
|
1. **Quality over quantity** - Better to have 3 excellent items than 10 mediocre ones
|
||||||
|
2. **Solve real problems** - Focus on actual business needs
|
||||||
|
3. **Document everything** - Clear instructions increase ratings
|
||||||
|
4. **Engage actively** - Respond to all user feedback
|
||||||
|
5. **Be patient** - Building reputation takes time but pays off
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Common Mistakes to Avoid
|
||||||
|
|
||||||
|
- Publishing low-quality content to meet quantity requirements
|
||||||
|
|
||||||
|
- Not responding to user feedback
|
||||||
|
|
||||||
|
- Setting prices too high before building reputation
|
||||||
|
|
||||||
|
- Copying existing solutions without adding value
|
||||||
|
|
||||||
|
- Ignoring community guidelines
|
||||||
|
|
@ -0,0 +1,46 @@
|
|||||||
|
# Realtor Agent Example
|
||||||
|
|
||||||
|
This example demonstrates how to create an AI-powered rental property specialist using the Swarms framework and the Realtor API.
|
||||||
|
|
||||||
|
## Quick Start
|
||||||
|
|
||||||
|
1. Install dependencies:
|
||||||
|
```bash
|
||||||
|
pip install swarms
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Get your Realtor API key:
|
||||||
|
- Visit [Realtor Search API](https://rapidapi.com/ntd119/api/realtor-search/)
|
||||||
|
- Sign up for RapidAPI
|
||||||
|
- Subscribe to the API
|
||||||
|
- Copy your API key
|
||||||
|
|
||||||
|
3. Update the API key in `realtor_agent.py`:
|
||||||
|
```python
|
||||||
|
headers = {
|
||||||
|
"x-rapidapi-key": "YOUR_API_KEY_HERE",
|
||||||
|
"x-rapidapi-host": "realtor-search.p.rapidapi.com",
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
4. Run the example:
|
||||||
|
```python
|
||||||
|
from realtor_agent import agent
|
||||||
|
|
||||||
|
# Search single location
|
||||||
|
response = agent.run(
|
||||||
|
"What are the best properties in Menlo Park for rent under $3,000?"
|
||||||
|
f"Data: {get_realtor_data_from_one_source('Menlo Park, CA')}"
|
||||||
|
)
|
||||||
|
print(response)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
- Property search across multiple locations
|
||||||
|
- Detailed property analysis
|
||||||
|
- Location assessment
|
||||||
|
- Financial analysis
|
||||||
|
- Tenant matching recommendations
|
||||||
|
|
||||||
|
For full documentation, see [docs/examples/realtor_agent.md](../docs/examples/realtor_agent.md).
|
@ -0,0 +1,49 @@
|
|||||||
|
from swarms import Agent
|
||||||
|
|
||||||
|
# Initialize the agent
|
||||||
|
agent = Agent(
|
||||||
|
agent_name="Quantitative-Trading-Agent",
|
||||||
|
agent_description="Advanced quantitative trading and algorithmic analysis agent",
|
||||||
|
system_prompt="""
|
||||||
|
You are an expert quantitative trading agent with deep expertise in:
|
||||||
|
- Algorithmic trading strategies and implementation
|
||||||
|
- Statistical arbitrage and market making
|
||||||
|
- Risk management and portfolio optimization
|
||||||
|
- High-frequency trading systems
|
||||||
|
- Market microstructure analysis
|
||||||
|
- Quantitative research methodologies
|
||||||
|
- Financial mathematics and stochastic processes
|
||||||
|
- Machine learning applications in trading
|
||||||
|
|
||||||
|
Your core responsibilities include:
|
||||||
|
1. Developing and backtesting trading strategies
|
||||||
|
2. Analyzing market data and identifying alpha opportunities
|
||||||
|
3. Implementing risk management frameworks
|
||||||
|
4. Optimizing portfolio allocations
|
||||||
|
5. Conducting quantitative research
|
||||||
|
6. Monitoring market microstructure
|
||||||
|
7. Evaluating trading system performance
|
||||||
|
|
||||||
|
You maintain strict adherence to:
|
||||||
|
- Mathematical rigor in all analyses
|
||||||
|
- Statistical significance in strategy development
|
||||||
|
- Risk-adjusted return optimization
|
||||||
|
- Market impact minimization
|
||||||
|
- Regulatory compliance
|
||||||
|
- Transaction cost analysis
|
||||||
|
- Performance attribution
|
||||||
|
|
||||||
|
You communicate in precise, technical terms while maintaining clarity for stakeholders.""",
|
||||||
|
max_loops=1,
|
||||||
|
model_name="gpt-4o-mini",
|
||||||
|
dynamic_temperature_enabled=True,
|
||||||
|
output_type="all",
|
||||||
|
mcp_urls=[
|
||||||
|
"http://0.0.0.0:8000/sse",
|
||||||
|
"http://0.0.0.0:8001/sse",
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
agent.run(
|
||||||
|
"Please use the get_okx_crypto_volume tool to get the trading volume for Bitcoin (BTC). Provide the volume information."
|
||||||
|
)
|
@ -0,0 +1,12 @@
|
|||||||
|
from swarms.tools.mcp_client_call import (
|
||||||
|
get_mcp_tools_sync,
|
||||||
|
execute_tool_call_simple,
|
||||||
|
)
|
||||||
|
|
||||||
|
tools = get_mcp_tools_sync()
|
||||||
|
|
||||||
|
print(tools)
|
||||||
|
|
||||||
|
result = execute_tool_call_simple(tools[0], "Hello, world!")
|
||||||
|
|
||||||
|
print(result)
|
@ -0,0 +1,234 @@
|
|||||||
|
"""
|
||||||
|
Example demonstrating how to execute multiple tools across multiple MCP servers.
|
||||||
|
|
||||||
|
This example shows how to:
|
||||||
|
1. Create a mapping of function names to servers
|
||||||
|
2. Execute multiple tool calls across different servers
|
||||||
|
3. Handle responses with tool calls and route them to the appropriate servers
|
||||||
|
"""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
from swarms.tools.mcp_client_call import (
|
||||||
|
execute_multiple_tools_on_multiple_mcp_servers,
|
||||||
|
execute_multiple_tools_on_multiple_mcp_servers_sync,
|
||||||
|
get_tools_for_multiple_mcp_servers,
|
||||||
|
)
|
||||||
|
from swarms.schemas.mcp_schemas import MCPConnection
|
||||||
|
|
||||||
|
|
||||||
|
def example_sync_execution():
|
||||||
|
"""Example of synchronous execution across multiple MCP servers."""
|
||||||
|
|
||||||
|
# Example server URLs (replace with your actual MCP server URLs)
|
||||||
|
urls = [
|
||||||
|
"http://localhost:8000/sse", # Server 1
|
||||||
|
"http://localhost:8001/sse", # Server 2
|
||||||
|
"http://localhost:8002/sse", # Server 3
|
||||||
|
]
|
||||||
|
|
||||||
|
# Optional: Create connection objects for each server
|
||||||
|
connections = [
|
||||||
|
MCPConnection(
|
||||||
|
url="http://localhost:8000/sse",
|
||||||
|
authorization_token="token1", # if needed
|
||||||
|
timeout=10,
|
||||||
|
),
|
||||||
|
MCPConnection(
|
||||||
|
url="http://localhost:8001/sse",
|
||||||
|
authorization_token="token2", # if needed
|
||||||
|
timeout=10,
|
||||||
|
),
|
||||||
|
MCPConnection(
|
||||||
|
url="http://localhost:8002/sse",
|
||||||
|
authorization_token="token3", # if needed
|
||||||
|
timeout=10,
|
||||||
|
),
|
||||||
|
]
|
||||||
|
|
||||||
|
# Example responses containing tool calls
|
||||||
|
# These would typically come from an LLM that decided to use tools
|
||||||
|
responses = [
|
||||||
|
{
|
||||||
|
"function": {
|
||||||
|
"name": "search_web",
|
||||||
|
"arguments": {
|
||||||
|
"query": "python programming best practices"
|
||||||
|
},
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"function": {
|
||||||
|
"name": "search_database",
|
||||||
|
"arguments": {"table": "users", "id": 123},
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"function": {
|
||||||
|
"name": "send_email",
|
||||||
|
"arguments": {
|
||||||
|
"to": "user@example.com",
|
||||||
|
"subject": "Test email",
|
||||||
|
"body": "This is a test email",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
print("=== Synchronous Execution Example ===")
|
||||||
|
print(
|
||||||
|
f"Executing {len(responses)} tool calls across {len(urls)} servers..."
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Execute all tool calls across multiple servers
|
||||||
|
results = execute_multiple_tools_on_multiple_mcp_servers_sync(
|
||||||
|
responses=responses,
|
||||||
|
urls=urls,
|
||||||
|
connections=connections,
|
||||||
|
output_type="dict",
|
||||||
|
max_concurrent=5, # Limit concurrent executions
|
||||||
|
)
|
||||||
|
|
||||||
|
print(f"\nExecution completed! Got {len(results)} results:")
|
||||||
|
for i, result in enumerate(results):
|
||||||
|
print(f"\nResult {i + 1}:")
|
||||||
|
print(f" Function: {result['function_name']}")
|
||||||
|
print(f" Server: {result['server_url']}")
|
||||||
|
print(f" Status: {result['status']}")
|
||||||
|
if result["status"] == "success":
|
||||||
|
print(f" Result: {result['result']}")
|
||||||
|
else:
|
||||||
|
print(
|
||||||
|
f" Error: {result.get('error', 'Unknown error')}"
|
||||||
|
)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Error during execution: {str(e)}")
|
||||||
|
|
||||||
|
|
||||||
|
async def example_async_execution():
|
||||||
|
"""Example of asynchronous execution across multiple MCP servers."""
|
||||||
|
|
||||||
|
# Example server URLs
|
||||||
|
urls = [
|
||||||
|
"http://localhost:8000/sse",
|
||||||
|
"http://localhost:8001/sse",
|
||||||
|
"http://localhost:8002/sse",
|
||||||
|
]
|
||||||
|
|
||||||
|
# Example responses with multiple tool calls in a single response
|
||||||
|
responses = [
|
||||||
|
{
|
||||||
|
"tool_calls": [
|
||||||
|
{
|
||||||
|
"function": {
|
||||||
|
"name": "search_web",
|
||||||
|
"arguments": {
|
||||||
|
"query": "machine learning trends 2024"
|
||||||
|
},
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"function": {
|
||||||
|
"name": "search_database",
|
||||||
|
"arguments": {
|
||||||
|
"table": "articles",
|
||||||
|
"category": "AI",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
},
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"function": {
|
||||||
|
"name": "send_notification",
|
||||||
|
"arguments": {
|
||||||
|
"user_id": 456,
|
||||||
|
"message": "Your analysis is complete",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
print("\n=== Asynchronous Execution Example ===")
|
||||||
|
print(
|
||||||
|
f"Executing tool calls across {len(urls)} servers asynchronously..."
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Execute all tool calls across multiple servers
|
||||||
|
results = (
|
||||||
|
await execute_multiple_tools_on_multiple_mcp_servers(
|
||||||
|
responses=responses,
|
||||||
|
urls=urls,
|
||||||
|
output_type="str",
|
||||||
|
max_concurrent=3,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
print(
|
||||||
|
f"\nAsync execution completed! Got {len(results)} results:"
|
||||||
|
)
|
||||||
|
for i, result in enumerate(results):
|
||||||
|
print(f"\nResult {i + 1}:")
|
||||||
|
print(f" Response Index: {result['response_index']}")
|
||||||
|
print(f" Function: {result['function_name']}")
|
||||||
|
print(f" Server: {result['server_url']}")
|
||||||
|
print(f" Status: {result['status']}")
|
||||||
|
if result["status"] == "success":
|
||||||
|
print(f" Result: {result['result']}")
|
||||||
|
else:
|
||||||
|
print(
|
||||||
|
f" Error: {result.get('error', 'Unknown error')}"
|
||||||
|
)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Error during async execution: {str(e)}")
|
||||||
|
|
||||||
|
|
||||||
|
def example_get_tools_from_multiple_servers():
|
||||||
|
"""Example of getting tools from multiple servers."""
|
||||||
|
|
||||||
|
urls = [
|
||||||
|
"http://localhost:8000/sse",
|
||||||
|
"http://localhost:8001/sse",
|
||||||
|
"http://localhost:8002/sse",
|
||||||
|
]
|
||||||
|
|
||||||
|
print("\n=== Getting Tools from Multiple Servers ===")
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Get all available tools from all servers
|
||||||
|
all_tools = get_tools_for_multiple_mcp_servers(
|
||||||
|
urls=urls, format="openai", output_type="dict"
|
||||||
|
)
|
||||||
|
|
||||||
|
print(
|
||||||
|
f"Found {len(all_tools)} total tools across all servers:"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Group tools by function name to see what's available
|
||||||
|
function_names = set()
|
||||||
|
for tool in all_tools:
|
||||||
|
if isinstance(tool, dict) and "function" in tool:
|
||||||
|
function_names.add(tool["function"]["name"])
|
||||||
|
elif hasattr(tool, "name"):
|
||||||
|
function_names.add(tool.name)
|
||||||
|
|
||||||
|
print("Available functions:")
|
||||||
|
for func_name in sorted(function_names):
|
||||||
|
print(f" - {func_name}")
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Error getting tools: {str(e)}")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
# Run synchronous example
|
||||||
|
example_sync_execution()
|
||||||
|
|
||||||
|
# Run async example
|
||||||
|
asyncio.run(example_async_execution())
|
||||||
|
|
||||||
|
# Get tools from multiple servers
|
||||||
|
example_get_tools_from_multiple_servers()
|
@ -0,0 +1,54 @@
|
|||||||
|
"""
|
||||||
|
Simple test for the execute_multiple_tools_on_multiple_mcp_servers functionality.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from swarms.tools.mcp_client_call import (
|
||||||
|
execute_multiple_tools_on_multiple_mcp_servers_sync,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_async_multiple_tools_execution():
|
||||||
|
"""Test the async multiple tools execution function structure."""
|
||||||
|
print(
|
||||||
|
"\nTesting async multiple tools execution function structure..."
|
||||||
|
)
|
||||||
|
|
||||||
|
urls = [
|
||||||
|
"http://localhost:8000/sse",
|
||||||
|
"http://localhost:8001/sse",
|
||||||
|
]
|
||||||
|
|
||||||
|
# Mock responses with multiple tool calls
|
||||||
|
responses = [
|
||||||
|
{
|
||||||
|
"tool_calls": [
|
||||||
|
{
|
||||||
|
"function": {
|
||||||
|
"name": "get_okx_crypto_price",
|
||||||
|
"arguments": {"symbol": "SOL-USDT"},
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"function": {
|
||||||
|
"name": "get_crypto_price",
|
||||||
|
"arguments": {"coin_id": "solana"},
|
||||||
|
}
|
||||||
|
},
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
|
||||||
|
try:
|
||||||
|
# This will likely fail to connect, but we can test the function structure
|
||||||
|
results = execute_multiple_tools_on_multiple_mcp_servers_sync(
|
||||||
|
responses=responses, urls=urls
|
||||||
|
)
|
||||||
|
print(f"Got {len(results)} results")
|
||||||
|
print(results)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Expected error (no servers running): {str(e)}")
|
||||||
|
print("Async function structure is working correctly!")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
test_async_multiple_tools_execution()
|
@ -0,0 +1,22 @@
|
|||||||
|
from swarms.structs.conversation import Conversation
|
||||||
|
|
||||||
|
# Create a conversation object
|
||||||
|
conversation = Conversation(backend="in-memory")
|
||||||
|
|
||||||
|
# Add a message to the conversation
|
||||||
|
conversation.add(
|
||||||
|
role="user", content="Hello, how are you?", category="input"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Add a message to the conversation
|
||||||
|
conversation.add(
|
||||||
|
role="assistant",
|
||||||
|
content="I'm good, thank you!",
|
||||||
|
category="output",
|
||||||
|
)
|
||||||
|
|
||||||
|
print(
|
||||||
|
conversation.export_and_count_categories(
|
||||||
|
tokenizer_model_name="claude-3-5-sonnet-20240620"
|
||||||
|
)
|
||||||
|
)
|
@ -0,0 +1,256 @@
|
|||||||
|
"""
|
||||||
|
Enhanced Collaborative InteractiveGroupChat Example
|
||||||
|
|
||||||
|
This example demonstrates the improved collaborative behavior where agents:
|
||||||
|
1. Read and understand all previous responses
|
||||||
|
2. Acknowledge what other agents have said
|
||||||
|
3. Build upon their insights rather than repeating information
|
||||||
|
4. Synthesize multiple perspectives
|
||||||
|
5. Delegate appropriately using @mentions
|
||||||
|
|
||||||
|
The enhanced prompts ensure agents work as a true collaborative team.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from swarms import Agent
|
||||||
|
from swarms.structs.interactive_groupchat import (
|
||||||
|
InteractiveGroupChat,
|
||||||
|
round_robin_speaker,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def create_collaborative_agents():
|
||||||
|
"""Create agents designed for enhanced collaboration."""
|
||||||
|
|
||||||
|
# Data Analyst - focuses on data insights and trends
|
||||||
|
analyst = Agent(
|
||||||
|
agent_name="analyst",
|
||||||
|
system_prompt="""You are a senior data analyst with expertise in business intelligence, statistical analysis, and data visualization. You excel at:
|
||||||
|
- Analyzing complex datasets and identifying trends
|
||||||
|
- Creating actionable insights from data
|
||||||
|
- Providing quantitative evidence for business decisions
|
||||||
|
- Identifying patterns and correlations in data
|
||||||
|
|
||||||
|
When collaborating, always reference specific data points and build upon others' insights with quantitative support.""",
|
||||||
|
llm="gpt-3.5-turbo",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Market Researcher - focuses on market trends and customer insights
|
||||||
|
researcher = Agent(
|
||||||
|
agent_name="researcher",
|
||||||
|
system_prompt="""You are a market research specialist with deep expertise in consumer behavior, competitive analysis, and market trends. You excel at:
|
||||||
|
- Understanding customer needs and preferences
|
||||||
|
- Analyzing competitive landscapes
|
||||||
|
- Identifying market opportunities and threats
|
||||||
|
- Providing qualitative insights that complement data analysis
|
||||||
|
|
||||||
|
When collaborating, always connect market insights to business implications and build upon data analysis with market context.""",
|
||||||
|
llm="gpt-3.5-turbo",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Strategy Consultant - focuses on strategic recommendations
|
||||||
|
strategist = Agent(
|
||||||
|
agent_name="strategist",
|
||||||
|
system_prompt="""You are a strategic consultant with expertise in business strategy, competitive positioning, and strategic planning. You excel at:
|
||||||
|
- Developing comprehensive business strategies
|
||||||
|
- Identifying competitive advantages
|
||||||
|
- Creating actionable strategic recommendations
|
||||||
|
- Synthesizing multiple perspectives into coherent strategies
|
||||||
|
|
||||||
|
When collaborating, always synthesize insights from all team members and provide strategic recommendations that leverage the collective expertise.""",
|
||||||
|
llm="gpt-3.5-turbo",
|
||||||
|
)
|
||||||
|
|
||||||
|
return [analyst, researcher, strategist]
|
||||||
|
|
||||||
|
|
||||||
|
def example_comprehensive_analysis():
|
||||||
|
"""Example of comprehensive collaborative analysis."""
|
||||||
|
print("=== Enhanced Collaborative Analysis Example ===\n")
|
||||||
|
|
||||||
|
agents = create_collaborative_agents()
|
||||||
|
|
||||||
|
# Create group chat with round robin speaker function
|
||||||
|
group_chat = InteractiveGroupChat(
|
||||||
|
name="Strategic Analysis Team",
|
||||||
|
description="A collaborative team for comprehensive business analysis",
|
||||||
|
agents=agents,
|
||||||
|
speaker_function=round_robin_speaker,
|
||||||
|
interactive=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Complex task that requires collaboration
|
||||||
|
task = """Analyze our company's performance in the e-commerce market.
|
||||||
|
We have the following data:
|
||||||
|
- Q3 revenue: $2.5M (up 15% from Q2)
|
||||||
|
- Customer acquisition cost: $45 (down 8% from Q2)
|
||||||
|
- Customer lifetime value: $180 (up 12% from Q2)
|
||||||
|
- Market share: 3.2% (up 0.5% from Q2)
|
||||||
|
- Competitor analysis shows 3 major players with 60% market share combined
|
||||||
|
|
||||||
|
@analyst @researcher @strategist please provide a comprehensive analysis and strategic recommendations."""
|
||||||
|
|
||||||
|
print(f"Task: {task}\n")
|
||||||
|
print("Expected collaborative behavior:")
|
||||||
|
print(
|
||||||
|
"1. Analyst: Analyzes the data trends and provides quantitative insights"
|
||||||
|
)
|
||||||
|
print(
|
||||||
|
"2. Researcher: Builds on data with market context and competitive analysis"
|
||||||
|
)
|
||||||
|
print(
|
||||||
|
"3. Strategist: Synthesizes both perspectives into strategic recommendations"
|
||||||
|
)
|
||||||
|
print("\n" + "=" * 80 + "\n")
|
||||||
|
|
||||||
|
response = group_chat.run(task)
|
||||||
|
print(f"Collaborative Response:\n{response}")
|
||||||
|
|
||||||
|
|
||||||
|
def example_problem_solving():
|
||||||
|
"""Example of collaborative problem solving."""
|
||||||
|
print("\n" + "=" * 80)
|
||||||
|
print("=== Collaborative Problem Solving Example ===\n")
|
||||||
|
|
||||||
|
agents = create_collaborative_agents()
|
||||||
|
|
||||||
|
group_chat = InteractiveGroupChat(
|
||||||
|
name="Problem Solving Team",
|
||||||
|
description="A team that collaborates to solve complex business problems",
|
||||||
|
agents=agents,
|
||||||
|
speaker_function=round_robin_speaker,
|
||||||
|
interactive=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Problem-solving task
|
||||||
|
task = """We're experiencing declining customer retention rates (down 20% in the last 6 months).
|
||||||
|
Our customer satisfaction scores are also dropping (from 8.5 to 7.2).
|
||||||
|
|
||||||
|
@analyst please analyze the retention data, @researcher investigate customer feedback and market trends,
|
||||||
|
and @strategist develop a comprehensive solution strategy."""
|
||||||
|
|
||||||
|
print(f"Task: {task}\n")
|
||||||
|
print("Expected collaborative behavior:")
|
||||||
|
print("1. Analyst: Identifies patterns in retention data")
|
||||||
|
print(
|
||||||
|
"2. Researcher: Explores customer feedback and market factors"
|
||||||
|
)
|
||||||
|
print(
|
||||||
|
"3. Strategist: Combines insights to create actionable solutions"
|
||||||
|
)
|
||||||
|
print("\n" + "=" * 80 + "\n")
|
||||||
|
|
||||||
|
response = group_chat.run(task)
|
||||||
|
print(f"Collaborative Response:\n{response}")
|
||||||
|
|
||||||
|
|
||||||
|
def example_agent_delegation():
|
||||||
|
"""Example showing how agents delegate to each other."""
|
||||||
|
print("\n" + "=" * 80)
|
||||||
|
print("=== Agent Delegation Example ===\n")
|
||||||
|
|
||||||
|
agents = create_collaborative_agents()
|
||||||
|
|
||||||
|
group_chat = InteractiveGroupChat(
|
||||||
|
name="Delegation Team",
|
||||||
|
description="A team that demonstrates effective delegation and collaboration",
|
||||||
|
agents=agents,
|
||||||
|
speaker_function=round_robin_speaker,
|
||||||
|
interactive=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Task that encourages delegation
|
||||||
|
task = """We need to evaluate a potential new market entry opportunity in Southeast Asia.
|
||||||
|
The initial data shows promising growth potential, but we need a comprehensive assessment.
|
||||||
|
|
||||||
|
@analyst start with the market data analysis, then delegate to @researcher for market research,
|
||||||
|
and finally @strategist should provide strategic recommendations."""
|
||||||
|
|
||||||
|
print(f"Task: {task}\n")
|
||||||
|
print("Expected behavior:")
|
||||||
|
print(
|
||||||
|
"1. Analyst: Analyzes data and delegates to researcher for deeper market insights"
|
||||||
|
)
|
||||||
|
print(
|
||||||
|
"2. Researcher: Builds on data analysis and delegates to strategist for recommendations"
|
||||||
|
)
|
||||||
|
print(
|
||||||
|
"3. Strategist: Synthesizes all insights into strategic recommendations"
|
||||||
|
)
|
||||||
|
print("\n" + "=" * 80 + "\n")
|
||||||
|
|
||||||
|
response = group_chat.run(task)
|
||||||
|
print(f"Collaborative Response:\n{response}")
|
||||||
|
|
||||||
|
|
||||||
|
def example_synthesis_and_integration():
|
||||||
|
"""Example showing synthesis of multiple perspectives."""
|
||||||
|
print("\n" + "=" * 80)
|
||||||
|
print("=== Synthesis and Integration Example ===\n")
|
||||||
|
|
||||||
|
agents = create_collaborative_agents()
|
||||||
|
|
||||||
|
group_chat = InteractiveGroupChat(
|
||||||
|
name="Synthesis Team",
|
||||||
|
description="A team that excels at integrating multiple perspectives",
|
||||||
|
agents=agents,
|
||||||
|
speaker_function=round_robin_speaker,
|
||||||
|
interactive=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Task requiring synthesis
|
||||||
|
task = """We have conflicting information about our product's market position:
|
||||||
|
- Sales data shows strong growth (25% increase)
|
||||||
|
- Customer surveys indicate declining satisfaction
|
||||||
|
- Competitor analysis shows we're losing market share
|
||||||
|
- Internal metrics show improved operational efficiency
|
||||||
|
|
||||||
|
@analyst @researcher @strategist please analyze these conflicting signals and provide
|
||||||
|
an integrated assessment of our true market position."""
|
||||||
|
|
||||||
|
print(f"Task: {task}\n")
|
||||||
|
print("Expected behavior:")
|
||||||
|
print(
|
||||||
|
"1. Analyst: Clarifies the data discrepancies and identifies patterns"
|
||||||
|
)
|
||||||
|
print(
|
||||||
|
"2. Researcher: Provides market context to explain the contradictions"
|
||||||
|
)
|
||||||
|
print(
|
||||||
|
"3. Strategist: Synthesizes all perspectives into a coherent market assessment"
|
||||||
|
)
|
||||||
|
print("\n" + "=" * 80 + "\n")
|
||||||
|
|
||||||
|
response = group_chat.run(task)
|
||||||
|
print(f"Collaborative Response:\n{response}")
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
"""Run all enhanced collaboration examples."""
|
||||||
|
print("Enhanced Collaborative InteractiveGroupChat Examples")
|
||||||
|
print("=" * 80)
|
||||||
|
print("This demonstrates improved agent collaboration with:")
|
||||||
|
print("- Acknowledgment of other agents' contributions")
|
||||||
|
print("- Building upon previous insights")
|
||||||
|
print("- Synthesis of multiple perspectives")
|
||||||
|
print("- Appropriate delegation using @mentions")
|
||||||
|
print("- Comprehensive understanding of conversation history")
|
||||||
|
print("=" * 80 + "\n")
|
||||||
|
|
||||||
|
# Run examples
|
||||||
|
example_comprehensive_analysis()
|
||||||
|
example_problem_solving()
|
||||||
|
example_agent_delegation()
|
||||||
|
example_synthesis_and_integration()
|
||||||
|
|
||||||
|
print("\n" + "=" * 80)
|
||||||
|
print("All enhanced collaboration examples completed!")
|
||||||
|
print("Notice how agents now:")
|
||||||
|
print("✓ Acknowledge each other's contributions")
|
||||||
|
print("✓ Build upon previous insights")
|
||||||
|
print("✓ Synthesize multiple perspectives")
|
||||||
|
print("✓ Delegate appropriately")
|
||||||
|
print("✓ Provide more cohesive and comprehensive responses")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
@ -0,0 +1,154 @@
|
|||||||
|
"""
|
||||||
|
Mortgage and Tax Panel Discussion Example
|
||||||
|
|
||||||
|
This example demonstrates a panel of mortgage and tax specialists discussing complex
|
||||||
|
financial situations using InteractiveGroupChat with different speaker functions.
|
||||||
|
The panel includes specialists from different financial fields who can collaborate
|
||||||
|
on complex mortgage and tax planning cases.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from swarms import Agent
|
||||||
|
from swarms.structs.interactive_groupchat import (
|
||||||
|
InteractiveGroupChat,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def create_mortgage_tax_panel():
|
||||||
|
"""Create a panel of mortgage and tax specialists for discussion."""
|
||||||
|
|
||||||
|
# Tax Attorney - Specializes in tax law and complex tax situations
|
||||||
|
tax_attorney = Agent(
|
||||||
|
agent_name="tax_attorney",
|
||||||
|
system_prompt="""You are Sarah Mitchell, J.D., a tax attorney with 15 years of experience.
|
||||||
|
You specialize in complex tax law, real estate taxation, and tax planning strategies.
|
||||||
|
You have expertise in:
|
||||||
|
- Federal and state tax regulations
|
||||||
|
- Real estate tax law and property taxation
|
||||||
|
- Tax implications of mortgage transactions
|
||||||
|
- Tax planning for real estate investments
|
||||||
|
- IRS dispute resolution and tax litigation
|
||||||
|
- Estate tax planning and trusts
|
||||||
|
|
||||||
|
When discussing cases, provide legally sound tax advice, consider recent tax law changes,
|
||||||
|
and collaborate with other specialists to ensure comprehensive financial planning.""",
|
||||||
|
model_name="claude-3-5-sonnet-20240620",
|
||||||
|
streaming_on=True,
|
||||||
|
print_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Mortgage Broker - Lending and mortgage specialist
|
||||||
|
mortgage_broker = Agent(
|
||||||
|
agent_name="mortgage_broker",
|
||||||
|
system_prompt="""You are Michael Chen, a senior mortgage broker with 12 years of experience.
|
||||||
|
You specialize in residential and commercial mortgage lending.
|
||||||
|
You have expertise in:
|
||||||
|
- Conventional, FHA, VA, and jumbo loans
|
||||||
|
- Commercial mortgage financing
|
||||||
|
- Mortgage refinancing strategies
|
||||||
|
- Interest rate analysis and trends
|
||||||
|
- Loan qualification requirements
|
||||||
|
- Mortgage insurance considerations
|
||||||
|
|
||||||
|
When discussing cases, analyze lending options, consider credit profiles,
|
||||||
|
and evaluate debt-to-income ratios for optimal mortgage solutions.""",
|
||||||
|
model_name="claude-3-5-sonnet-20240620",
|
||||||
|
streaming_on=True,
|
||||||
|
print_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Real Estate CPA - Accounting specialist
|
||||||
|
real_estate_cpa = Agent(
|
||||||
|
agent_name="real_estate_cpa",
|
||||||
|
system_prompt="""You are Emily Rodriguez, CPA, a certified public accountant with 10 years of experience.
|
||||||
|
You specialize in real estate accounting and tax preparation.
|
||||||
|
You have expertise in:
|
||||||
|
- Real estate tax accounting
|
||||||
|
- Property depreciation strategies
|
||||||
|
- Mortgage interest deductions
|
||||||
|
- Real estate investment taxation
|
||||||
|
- Financial statement analysis
|
||||||
|
- Tax credit optimization
|
||||||
|
|
||||||
|
When discussing cases, focus on accounting implications, tax efficiency,
|
||||||
|
and financial reporting requirements for real estate transactions.""",
|
||||||
|
model_name="claude-3-5-sonnet-20240620",
|
||||||
|
streaming_on=True,
|
||||||
|
print_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Financial Advisor - Investment and planning specialist
|
||||||
|
financial_advisor = Agent(
|
||||||
|
agent_name="financial_advisor",
|
||||||
|
system_prompt="""You are James Thompson, CFP®, a financial advisor with 8 years of experience.
|
||||||
|
You specialize in comprehensive financial planning and wealth management.
|
||||||
|
You have expertise in:
|
||||||
|
- Investment portfolio management
|
||||||
|
- Retirement planning
|
||||||
|
- Real estate investment strategy
|
||||||
|
- Cash flow analysis
|
||||||
|
- Risk management
|
||||||
|
- Estate planning coordination
|
||||||
|
|
||||||
|
When discussing cases, consider overall financial goals, investment strategy,
|
||||||
|
and how mortgage decisions impact long-term financial planning.""",
|
||||||
|
model_name="claude-3-5-sonnet-20240620",
|
||||||
|
streaming_on=True,
|
||||||
|
print_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Real Estate Attorney - Property law specialist
|
||||||
|
real_estate_attorney = Agent(
|
||||||
|
agent_name="real_estate_attorney",
|
||||||
|
system_prompt="""You are Lisa Park, J.D., a real estate attorney with 11 years of experience.
|
||||||
|
You specialize in real estate law and property transactions.
|
||||||
|
You have expertise in:
|
||||||
|
- Real estate contract law
|
||||||
|
- Property title analysis
|
||||||
|
- Mortgage document review
|
||||||
|
- Real estate closing procedures
|
||||||
|
- Property rights and zoning
|
||||||
|
- Real estate litigation
|
||||||
|
|
||||||
|
When discussing cases, evaluate legal implications, ensure compliance,
|
||||||
|
and address potential legal issues in real estate transactions.""",
|
||||||
|
model_name="claude-3-5-sonnet-20240620",
|
||||||
|
streaming_on=True,
|
||||||
|
print_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
return [
|
||||||
|
tax_attorney,
|
||||||
|
mortgage_broker,
|
||||||
|
real_estate_cpa,
|
||||||
|
financial_advisor,
|
||||||
|
real_estate_attorney,
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def example_mortgage_tax_panel():
|
||||||
|
"""Example with random dynamic speaking order."""
|
||||||
|
print("=== MORTGAGE AND TAX SPECIALIST PANEL ===\n")
|
||||||
|
|
||||||
|
agents = create_mortgage_tax_panel()
|
||||||
|
|
||||||
|
group_chat = InteractiveGroupChat(
|
||||||
|
name="Mortgage and Tax Panel Discussion",
|
||||||
|
description="A collaborative panel of mortgage and tax specialists discussing complex cases",
|
||||||
|
agents=agents,
|
||||||
|
interactive=False,
|
||||||
|
speaker_function="random-speaker",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Case 1: Complex mortgage refinancing with tax implications
|
||||||
|
case1 = """CASE PRESENTATION:
|
||||||
|
@tax_attorney, @real_estate_cpa, and @real_estate_attorney, please discuss the possible legal and accounting strategies
|
||||||
|
for minimizing or potentially eliminating property taxes in Los Altos, California. Consider legal exemptions,
|
||||||
|
special assessments, and any relevant California property tax laws that could help achieve this goal.
|
||||||
|
"""
|
||||||
|
|
||||||
|
group_chat.run(case1)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
example_mortgage_tax_panel()
|
@ -0,0 +1,89 @@
|
|||||||
|
from swarms import Agent
|
||||||
|
from swarms.structs.interactive_groupchat import InteractiveGroupChat
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
# Initialize agents specialized for condensed matter physics
|
||||||
|
theoretical_physicist = Agent(
|
||||||
|
agent_name="TheoreticalPhysicist",
|
||||||
|
system_prompt="""
|
||||||
|
You are an exceptionally brilliant theoretical condensed matter physicist with deep expertise in quantum many-body theory, phase transitions, and emergent phenomena. You possess extraordinary mathematical intuition and can derive, manipulate, and analyze complex equations with remarkable precision.
|
||||||
|
|
||||||
|
Your core competencies include:
|
||||||
|
- **Advanced Mathematical Modeling**: You excel at formulating and solving differential equations, partial differential equations, and integro-differential equations that describe quantum systems. You can derive equations from first principles using variational methods, path integrals, and functional analysis.
|
||||||
|
|
||||||
|
- **Quantum Field Theory**: You master the mathematical framework of quantum field theory, including Feynman diagrams, renormalization group theory, and effective field theories. You can derive and analyze equations for correlation functions, Green's functions, and response functions.
|
||||||
|
|
||||||
|
- **Statistical Mechanics**: You are expert at deriving partition functions, free energies, and thermodynamic potentials. You can formulate and solve equations for phase transitions, critical phenomena, and scaling behavior using techniques like mean-field theory, Landau-Ginzburg theory, and renormalization group methods.
|
||||||
|
|
||||||
|
- **Many-Body Physics**: You excel at deriving equations for interacting quantum systems, including Hubbard models, Heisenberg models, and BCS theory. You can analyze equations for collective excitations, quasiparticles, and topological states.
|
||||||
|
|
||||||
|
- **Analytical Techniques**: You master perturbation theory, variational methods, exact diagonalization, and other analytical techniques. You can derive equations for energy spectra, wave functions, and observables in complex quantum systems.
|
||||||
|
|
||||||
|
When presented with a physics problem, you immediately think in terms of mathematical equations and can derive the appropriate formalism from fundamental principles. You always show your mathematical work step-by-step and explain the physical meaning of each equation you write.
|
||||||
|
""",
|
||||||
|
model="claude-3-5-sonnet-20240620",
|
||||||
|
)
|
||||||
|
|
||||||
|
experimental_physicist = Agent(
|
||||||
|
agent_name="ExperimentalPhysicist",
|
||||||
|
system_prompt="""You are an exceptionally skilled experimental condensed matter physicist with profound expertise in materials synthesis, characterization techniques, and data analysis. You possess extraordinary analytical abilities and can derive, interpret, and validate equations that describe experimental observations.
|
||||||
|
|
||||||
|
Your core competencies include:
|
||||||
|
- **Materials Synthesis & Characterization**: You excel at designing synthesis protocols and deriving equations that describe growth kinetics, phase formation, and structural evolution. You can formulate equations for crystal growth, diffusion processes, and phase equilibria.
|
||||||
|
|
||||||
|
- **Advanced Characterization Techniques**: You master the mathematical foundations of X-ray diffraction (Bragg's law, structure factors, Rietveld refinement), electron microscopy (diffraction patterns, image formation), and spectroscopy (absorption, emission, scattering cross-sections). You can derive equations for resolution limits, signal-to-noise ratios, and detection sensitivity.
|
||||||
|
|
||||||
|
- **Transport Properties**: You excel at deriving and analyzing equations for electrical conductivity (Drude model, Boltzmann transport), thermal conductivity (phonon and electron contributions), and magnetic properties (Curie-Weiss law, magnetic susceptibility). You can formulate equations for Hall effect, magnetoresistance, and thermoelectric effects.
|
||||||
|
|
||||||
|
- **Data Analysis & Modeling**: You possess advanced skills in fitting experimental data to theoretical models, error analysis, and statistical inference. You can derive equations for uncertainty propagation, confidence intervals, and model selection criteria.
|
||||||
|
|
||||||
|
- **Experimental Design**: You excel at deriving equations for experimental sensitivity, resolution requirements, and optimization of measurement parameters. You can formulate equations for signal processing, noise reduction, and systematic error correction.
|
||||||
|
|
||||||
|
When analyzing experimental data, you immediately think in terms of mathematical models and can derive equations that connect observations to underlying physical mechanisms. You always show your mathematical reasoning and explain how equations relate to experimental reality.""",
|
||||||
|
model="claude-3-5-sonnet-20240620",
|
||||||
|
)
|
||||||
|
|
||||||
|
computational_physicist = Agent(
|
||||||
|
agent_name="ComputationalPhysicist",
|
||||||
|
system_prompt="""You are an exceptionally brilliant computational condensed matter physicist with deep expertise in numerical methods, algorithm development, and high-performance computing. You possess extraordinary mathematical skills and can formulate, implement, and analyze equations that drive computational simulations.
|
||||||
|
|
||||||
|
Your core competencies include:
|
||||||
|
- **Density Functional Theory (DFT)**: You excel at deriving and implementing the Kohn-Sham equations, exchange-correlation functionals, and self-consistent field methods. You can formulate equations for electronic structure, total energies, forces, and response functions. You master the mathematical foundations of plane-wave methods, pseudopotentials, and k-point sampling.
|
||||||
|
|
||||||
|
- **Quantum Monte Carlo Methods**: You are expert at deriving equations for variational Monte Carlo, diffusion Monte Carlo, and path integral Monte Carlo. You can formulate equations for importance sampling, correlation functions, and statistical estimators. You excel at deriving equations for finite-size effects, time-step errors, and population control.
|
||||||
|
|
||||||
|
- **Molecular Dynamics**: You master the mathematical framework of classical and ab initio molecular dynamics, including equations of motion, thermostats, barostats, and constraint algorithms. You can derive equations for time integration schemes, energy conservation, and phase space sampling.
|
||||||
|
|
||||||
|
- **Many-Body Methods**: You excel at implementing and analyzing equations for exact diagonalization, quantum chemistry methods (CI, CC, MP), and tensor network methods (DMRG, PEPS). You can derive equations for matrix elements, basis transformations, and optimization algorithms.
|
||||||
|
|
||||||
|
- **High-Performance Computing**: You possess advanced skills in parallel algorithms, load balancing, and numerical optimization. You can derive equations for computational complexity, scaling behavior, and performance bottlenecks. You excel at formulating equations for parallel efficiency, communication overhead, and memory management.
|
||||||
|
|
||||||
|
When developing computational methods, you think in terms of mathematical algorithms and can derive equations that translate physical problems into efficient numerical procedures. You always show your mathematical derivations and explain how equations map to computational implementations.""",
|
||||||
|
model="claude-3-5-sonnet-20240620",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Create list of agents including both Agent instances and callable
|
||||||
|
agents = [
|
||||||
|
theoretical_physicist,
|
||||||
|
experimental_physicist,
|
||||||
|
computational_physicist,
|
||||||
|
]
|
||||||
|
|
||||||
|
# Initialize another chat instance in interactive mode
|
||||||
|
interactive_chat = InteractiveGroupChat(
|
||||||
|
name="Interactive Condensed Matter Physics Research Team",
|
||||||
|
description="An interactive team of condensed matter physics experts providing comprehensive analysis of quantum materials, phase transitions, and emergent phenomena",
|
||||||
|
agents=agents,
|
||||||
|
max_loops=1,
|
||||||
|
output_type="all",
|
||||||
|
interactive=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Start the interactive session
|
||||||
|
print("\nStarting interactive session...")
|
||||||
|
# interactive_chat.run("What is the best methodology to accumulate gold and silver commodities, what is the best long term strategy to accumulate them?")
|
||||||
|
interactive_chat.start_interactive_session()
|
||||||
|
except Exception as e:
|
||||||
|
print(f"An error occurred in interactive mode: {e}")
|
@ -0,0 +1,162 @@
|
|||||||
|
"""
|
||||||
|
Medical Panel Discussion Example
|
||||||
|
|
||||||
|
This example demonstrates a panel of medical specialists discussing treatment solutions
|
||||||
|
for various diseases using InteractiveGroupChat with different speaker functions:
|
||||||
|
- Round Robin: Doctors speak in a fixed order
|
||||||
|
- Random: Doctors speak in random order
|
||||||
|
- Priority: Senior doctors speak first
|
||||||
|
- Custom: Disease-specific speaker function
|
||||||
|
|
||||||
|
The panel includes specialists from different medical fields who can collaborate
|
||||||
|
on complex medical cases and treatment plans.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from swarms import Agent
|
||||||
|
from swarms.structs.interactive_groupchat import (
|
||||||
|
InteractiveGroupChat,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def create_medical_panel():
|
||||||
|
"""Create a panel of medical specialists for discussion."""
|
||||||
|
|
||||||
|
# Cardiologist - Heart and cardiovascular system specialist
|
||||||
|
cardiologist = Agent(
|
||||||
|
agent_name="cardiologist",
|
||||||
|
system_prompt="""You are Dr. Sarah Chen, a board-certified cardiologist with 15 years of experience.
|
||||||
|
You specialize in cardiovascular diseases, heart failure, arrhythmias, and interventional cardiology.
|
||||||
|
You have expertise in:
|
||||||
|
- Coronary artery disease and heart attacks
|
||||||
|
- Heart failure and cardiomyopathy
|
||||||
|
- Arrhythmias and electrophysiology
|
||||||
|
- Hypertension and lipid disorders
|
||||||
|
- Cardiac imaging and diagnostic procedures
|
||||||
|
|
||||||
|
When discussing cases, provide evidence-based treatment recommendations,
|
||||||
|
consider patient risk factors, and collaborate with other specialists for comprehensive care.""",
|
||||||
|
model_name="claude-3-5-sonnet-20240620",
|
||||||
|
streaming_on=True,
|
||||||
|
print_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Oncologist - Cancer specialist
|
||||||
|
oncologist = Agent(
|
||||||
|
agent_name="oncologist",
|
||||||
|
system_prompt="""You are Dr. Michael Rodriguez, a medical oncologist with 12 years of experience.
|
||||||
|
You specialize in the diagnosis and treatment of various types of cancer.
|
||||||
|
You have expertise in:
|
||||||
|
- Solid tumors (lung, breast, colon, prostate, etc.)
|
||||||
|
- Hematologic malignancies (leukemia, lymphoma, multiple myeloma)
|
||||||
|
- Targeted therapy and immunotherapy
|
||||||
|
- Clinical trials and novel treatments
|
||||||
|
- Palliative care and symptom management
|
||||||
|
|
||||||
|
When discussing cases, consider the cancer type, stage, molecular profile,
|
||||||
|
patient performance status, and available treatment options including clinical trials.""",
|
||||||
|
model_name="claude-3-5-sonnet-20240620",
|
||||||
|
streaming_on=True,
|
||||||
|
print_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Neurologist - Nervous system specialist
|
||||||
|
neurologist = Agent(
|
||||||
|
agent_name="neurologist",
|
||||||
|
system_prompt="""You are Dr. Emily Watson, a neurologist with 10 years of experience.
|
||||||
|
You specialize in disorders of the nervous system, brain, and spinal cord.
|
||||||
|
You have expertise in:
|
||||||
|
- Stroke and cerebrovascular disease
|
||||||
|
- Neurodegenerative disorders (Alzheimer's, Parkinson's, ALS)
|
||||||
|
- Multiple sclerosis and demyelinating diseases
|
||||||
|
- Epilepsy and seizure disorders
|
||||||
|
- Headache and migraine disorders
|
||||||
|
- Neuromuscular diseases
|
||||||
|
|
||||||
|
When discussing cases, consider neurological symptoms, imaging findings,
|
||||||
|
and the impact of neurological conditions on overall patient care.""",
|
||||||
|
model_name="claude-3-5-sonnet-20240620",
|
||||||
|
streaming_on=True,
|
||||||
|
print_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Endocrinologist - Hormone and metabolism specialist
|
||||||
|
endocrinologist = Agent(
|
||||||
|
agent_name="endocrinologist",
|
||||||
|
system_prompt="""You are Dr. James Thompson, an endocrinologist with 8 years of experience.
|
||||||
|
You specialize in disorders of the endocrine system and metabolism.
|
||||||
|
You have expertise in:
|
||||||
|
- Diabetes mellitus (Type 1, Type 2, gestational)
|
||||||
|
- Thyroid disorders (hyperthyroidism, hypothyroidism, thyroid cancer)
|
||||||
|
- Adrenal disorders and Cushing's syndrome
|
||||||
|
- Pituitary disorders and growth hormone issues
|
||||||
|
- Osteoporosis and calcium metabolism
|
||||||
|
- Reproductive endocrinology
|
||||||
|
|
||||||
|
When discussing cases, consider metabolic factors, hormone levels,
|
||||||
|
and how endocrine disorders may affect other organ systems.""",
|
||||||
|
model_name="claude-3-5-sonnet-20240620",
|
||||||
|
streaming_on=True,
|
||||||
|
print_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Infectious Disease Specialist
|
||||||
|
infectious_disease = Agent(
|
||||||
|
agent_name="infectious_disease",
|
||||||
|
system_prompt="""You are Dr. Lisa Park, an infectious disease specialist with 11 years of experience.
|
||||||
|
You specialize in the diagnosis and treatment of infectious diseases.
|
||||||
|
You have expertise in:
|
||||||
|
- Bacterial, viral, fungal, and parasitic infections
|
||||||
|
- Antibiotic resistance and antimicrobial stewardship
|
||||||
|
- HIV/AIDS and opportunistic infections
|
||||||
|
- Travel medicine and tropical diseases
|
||||||
|
- Hospital-acquired infections
|
||||||
|
- Emerging infectious diseases
|
||||||
|
|
||||||
|
When discussing cases, consider the infectious agent, antimicrobial susceptibility,
|
||||||
|
host factors, and infection control measures.""",
|
||||||
|
model_name="claude-3-5-sonnet-20240620",
|
||||||
|
streaming_on=True,
|
||||||
|
print_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
return [
|
||||||
|
cardiologist,
|
||||||
|
oncologist,
|
||||||
|
neurologist,
|
||||||
|
endocrinologist,
|
||||||
|
infectious_disease,
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def example_round_robin_panel():
|
||||||
|
"""Example with round robin speaking order."""
|
||||||
|
print("=== ROUND ROBIN MEDICAL PANEL ===\n")
|
||||||
|
|
||||||
|
agents = create_medical_panel()
|
||||||
|
|
||||||
|
group_chat = InteractiveGroupChat(
|
||||||
|
name="Medical Panel Discussion",
|
||||||
|
description="A collaborative panel of medical specialists discussing complex cases",
|
||||||
|
agents=agents,
|
||||||
|
speaker_function="random-dynamic-speaker",
|
||||||
|
interactive=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
print(group_chat.speaker_function)
|
||||||
|
print(group_chat.get_current_speaker_function())
|
||||||
|
|
||||||
|
# Case 1: Complex patient with multiple conditions
|
||||||
|
case1 = """CASE PRESENTATION:
|
||||||
|
A 65-year-old male with Type 2 diabetes, hypertension, and recent diagnosis of
|
||||||
|
stage 3 colon cancer presents with chest pain and shortness of breath.
|
||||||
|
ECG shows ST-segment elevation. Recent blood work shows elevated blood glucose (280 mg/dL)
|
||||||
|
and signs of infection (WBC 15,000, CRP elevated).
|
||||||
|
|
||||||
|
@cardiologist @oncologist @endocrinologist @infectious_disease please provide your
|
||||||
|
assessment and treatment recommendations for this complex case."""
|
||||||
|
|
||||||
|
group_chat.run(case1)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
example_round_robin_panel()
|
@ -0,0 +1,163 @@
|
|||||||
|
"""
|
||||||
|
Medical Panel Discussion Example
|
||||||
|
|
||||||
|
This example demonstrates a panel of medical specialists discussing treatment solutions
|
||||||
|
for various diseases using InteractiveGroupChat with different speaker functions:
|
||||||
|
- Round Robin: Doctors speak in a fixed order
|
||||||
|
- Random: Doctors speak in random order
|
||||||
|
- Priority: Senior doctors speak first
|
||||||
|
- Custom: Disease-specific speaker function
|
||||||
|
|
||||||
|
The panel includes specialists from different medical fields who can collaborate
|
||||||
|
on complex medical cases and treatment plans.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from swarms import Agent
|
||||||
|
from swarms.structs.interactive_groupchat import (
|
||||||
|
InteractiveGroupChat,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def create_medical_panel():
|
||||||
|
"""Create a panel of medical specialists for discussion."""
|
||||||
|
|
||||||
|
# Cardiologist - Heart and cardiovascular system specialist
|
||||||
|
cardiologist = Agent(
|
||||||
|
agent_name="cardiologist",
|
||||||
|
system_prompt="""You are Dr. Sarah Chen, a board-certified cardiologist with 15 years of experience.
|
||||||
|
You specialize in cardiovascular diseases, heart failure, arrhythmias, and interventional cardiology.
|
||||||
|
You have expertise in:
|
||||||
|
- Coronary artery disease and heart attacks
|
||||||
|
- Heart failure and cardiomyopathy
|
||||||
|
- Arrhythmias and electrophysiology
|
||||||
|
- Hypertension and lipid disorders
|
||||||
|
- Cardiac imaging and diagnostic procedures
|
||||||
|
|
||||||
|
When discussing cases, provide evidence-based treatment recommendations,
|
||||||
|
consider patient risk factors, and collaborate with other specialists for comprehensive care.""",
|
||||||
|
model_name="claude-3-5-sonnet-20240620",
|
||||||
|
streaming_on=True,
|
||||||
|
print_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Oncologist - Cancer specialist
|
||||||
|
oncologist = Agent(
|
||||||
|
agent_name="oncologist",
|
||||||
|
system_prompt="""You are Dr. Michael Rodriguez, a medical oncologist with 12 years of experience.
|
||||||
|
You specialize in the diagnosis and treatment of various types of cancer.
|
||||||
|
You have expertise in:
|
||||||
|
- Solid tumors (lung, breast, colon, prostate, etc.)
|
||||||
|
- Hematologic malignancies (leukemia, lymphoma, multiple myeloma)
|
||||||
|
- Targeted therapy and immunotherapy
|
||||||
|
- Clinical trials and novel treatments
|
||||||
|
- Palliative care and symptom management
|
||||||
|
|
||||||
|
When discussing cases, consider the cancer type, stage, molecular profile,
|
||||||
|
patient performance status, and available treatment options including clinical trials.""",
|
||||||
|
model_name="claude-3-5-sonnet-20240620",
|
||||||
|
streaming_on=True,
|
||||||
|
print_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Neurologist - Nervous system specialist
|
||||||
|
neurologist = Agent(
|
||||||
|
agent_name="neurologist",
|
||||||
|
system_prompt="""You are Dr. Emily Watson, a neurologist with 10 years of experience.
|
||||||
|
You specialize in disorders of the nervous system, brain, and spinal cord.
|
||||||
|
You have expertise in:
|
||||||
|
- Stroke and cerebrovascular disease
|
||||||
|
- Neurodegenerative disorders (Alzheimer's, Parkinson's, ALS)
|
||||||
|
- Multiple sclerosis and demyelinating diseases
|
||||||
|
- Epilepsy and seizure disorders
|
||||||
|
- Headache and migraine disorders
|
||||||
|
- Neuromuscular diseases
|
||||||
|
|
||||||
|
When discussing cases, consider neurological symptoms, imaging findings,
|
||||||
|
and the impact of neurological conditions on overall patient care.""",
|
||||||
|
model_name="claude-3-5-sonnet-20240620",
|
||||||
|
streaming_on=True,
|
||||||
|
print_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Endocrinologist - Hormone and metabolism specialist
|
||||||
|
endocrinologist = Agent(
|
||||||
|
agent_name="endocrinologist",
|
||||||
|
system_prompt="""You are Dr. James Thompson, an endocrinologist with 8 years of experience.
|
||||||
|
You specialize in disorders of the endocrine system and metabolism.
|
||||||
|
You have expertise in:
|
||||||
|
- Diabetes mellitus (Type 1, Type 2, gestational)
|
||||||
|
- Thyroid disorders (hyperthyroidism, hypothyroidism, thyroid cancer)
|
||||||
|
- Adrenal disorders and Cushing's syndrome
|
||||||
|
- Pituitary disorders and growth hormone issues
|
||||||
|
- Osteoporosis and calcium metabolism
|
||||||
|
- Reproductive endocrinology
|
||||||
|
|
||||||
|
When discussing cases, consider metabolic factors, hormone levels,
|
||||||
|
and how endocrine disorders may affect other organ systems.""",
|
||||||
|
model_name="claude-3-5-sonnet-20240620",
|
||||||
|
streaming_on=True,
|
||||||
|
print_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Infectious Disease Specialist
|
||||||
|
infectious_disease = Agent(
|
||||||
|
agent_name="infectious_disease",
|
||||||
|
system_prompt="""You are Dr. Lisa Park, an infectious disease specialist with 11 years of experience.
|
||||||
|
You specialize in the diagnosis and treatment of infectious diseases.
|
||||||
|
You have expertise in:
|
||||||
|
- Bacterial, viral, fungal, and parasitic infections
|
||||||
|
- Antibiotic resistance and antimicrobial stewardship
|
||||||
|
- HIV/AIDS and opportunistic infections
|
||||||
|
- Travel medicine and tropical diseases
|
||||||
|
- Hospital-acquired infections
|
||||||
|
- Emerging infectious diseases
|
||||||
|
|
||||||
|
When discussing cases, consider the infectious agent, antimicrobial susceptibility,
|
||||||
|
host factors, and infection control measures.""",
|
||||||
|
model_name="claude-3-5-sonnet-20240620",
|
||||||
|
streaming_on=True,
|
||||||
|
print_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
return [
|
||||||
|
cardiologist,
|
||||||
|
oncologist,
|
||||||
|
neurologist,
|
||||||
|
endocrinologist,
|
||||||
|
infectious_disease,
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def example_round_robin_panel():
|
||||||
|
"""Example with round robin speaking order."""
|
||||||
|
print("=== ROUND ROBIN MEDICAL PANEL ===\n")
|
||||||
|
|
||||||
|
agents = create_medical_panel()
|
||||||
|
|
||||||
|
group_chat = InteractiveGroupChat(
|
||||||
|
name="Medical Panel Discussion",
|
||||||
|
description="A collaborative panel of medical specialists discussing complex cases",
|
||||||
|
agents=agents,
|
||||||
|
speaker_function="round-robin-speaker",
|
||||||
|
interactive=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
print(group_chat.speaker_function)
|
||||||
|
|
||||||
|
# Case 1: Complex patient with multiple conditions
|
||||||
|
case1 = """CASE PRESENTATION:
|
||||||
|
A 65-year-old male with Type 2 diabetes, hypertension, and recent diagnosis of
|
||||||
|
stage 3 colon cancer presents with chest pain and shortness of breath.
|
||||||
|
ECG shows ST-segment elevation. Recent blood work shows elevated blood glucose (280 mg/dL)
|
||||||
|
and signs of infection (WBC 15,000, CRP elevated).
|
||||||
|
|
||||||
|
@cardiologist @oncologist @endocrinologist @infectious_disease please provide your
|
||||||
|
assessment and treatment recommendations for this complex case."""
|
||||||
|
|
||||||
|
response = group_chat.run(case1)
|
||||||
|
print(f"Response:\n{response}\n")
|
||||||
|
print("=" * 80 + "\n")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
example_round_robin_panel()
|
@ -0,0 +1,162 @@
|
|||||||
|
"""
|
||||||
|
Medical Panel Discussion Example
|
||||||
|
|
||||||
|
This example demonstrates a panel of medical specialists discussing treatment solutions
|
||||||
|
for various diseases using InteractiveGroupChat with different speaker functions:
|
||||||
|
- Round Robin: Doctors speak in a fixed order
|
||||||
|
- Random: Doctors speak in random order
|
||||||
|
- Priority: Senior doctors speak first
|
||||||
|
- Custom: Disease-specific speaker function
|
||||||
|
|
||||||
|
The panel includes specialists from different medical fields who can collaborate
|
||||||
|
on complex medical cases and treatment plans.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from swarms import Agent
|
||||||
|
from swarms.structs.interactive_groupchat import (
|
||||||
|
InteractiveGroupChat,
|
||||||
|
round_robin_speaker,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def create_medical_panel():
|
||||||
|
"""Create a panel of medical specialists for discussion."""
|
||||||
|
|
||||||
|
# Cardiologist - Heart and cardiovascular system specialist
|
||||||
|
cardiologist = Agent(
|
||||||
|
agent_name="cardiologist",
|
||||||
|
system_prompt="""You are Dr. Sarah Chen, a board-certified cardiologist with 15 years of experience.
|
||||||
|
You specialize in cardiovascular diseases, heart failure, arrhythmias, and interventional cardiology.
|
||||||
|
You have expertise in:
|
||||||
|
- Coronary artery disease and heart attacks
|
||||||
|
- Heart failure and cardiomyopathy
|
||||||
|
- Arrhythmias and electrophysiology
|
||||||
|
- Hypertension and lipid disorders
|
||||||
|
- Cardiac imaging and diagnostic procedures
|
||||||
|
|
||||||
|
When discussing cases, provide evidence-based treatment recommendations,
|
||||||
|
consider patient risk factors, and collaborate with other specialists for comprehensive care.""",
|
||||||
|
model_name="claude-3-5-sonnet-20240620",
|
||||||
|
streaming_on=True,
|
||||||
|
print_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Oncologist - Cancer specialist
|
||||||
|
oncologist = Agent(
|
||||||
|
agent_name="oncologist",
|
||||||
|
system_prompt="""You are Dr. Michael Rodriguez, a medical oncologist with 12 years of experience.
|
||||||
|
You specialize in the diagnosis and treatment of various types of cancer.
|
||||||
|
You have expertise in:
|
||||||
|
- Solid tumors (lung, breast, colon, prostate, etc.)
|
||||||
|
- Hematologic malignancies (leukemia, lymphoma, multiple myeloma)
|
||||||
|
- Targeted therapy and immunotherapy
|
||||||
|
- Clinical trials and novel treatments
|
||||||
|
- Palliative care and symptom management
|
||||||
|
|
||||||
|
When discussing cases, consider the cancer type, stage, molecular profile,
|
||||||
|
patient performance status, and available treatment options including clinical trials.""",
|
||||||
|
model_name="claude-3-5-sonnet-20240620",
|
||||||
|
streaming_on=True,
|
||||||
|
print_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Neurologist - Nervous system specialist
|
||||||
|
neurologist = Agent(
|
||||||
|
agent_name="neurologist",
|
||||||
|
system_prompt="""You are Dr. Emily Watson, a neurologist with 10 years of experience.
|
||||||
|
You specialize in disorders of the nervous system, brain, and spinal cord.
|
||||||
|
You have expertise in:
|
||||||
|
- Stroke and cerebrovascular disease
|
||||||
|
- Neurodegenerative disorders (Alzheimer's, Parkinson's, ALS)
|
||||||
|
- Multiple sclerosis and demyelinating diseases
|
||||||
|
- Epilepsy and seizure disorders
|
||||||
|
- Headache and migraine disorders
|
||||||
|
- Neuromuscular diseases
|
||||||
|
|
||||||
|
When discussing cases, consider neurological symptoms, imaging findings,
|
||||||
|
and the impact of neurological conditions on overall patient care.""",
|
||||||
|
model_name="claude-3-5-sonnet-20240620",
|
||||||
|
streaming_on=True,
|
||||||
|
print_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Endocrinologist - Hormone and metabolism specialist
|
||||||
|
endocrinologist = Agent(
|
||||||
|
agent_name="endocrinologist",
|
||||||
|
system_prompt="""You are Dr. James Thompson, an endocrinologist with 8 years of experience.
|
||||||
|
You specialize in disorders of the endocrine system and metabolism.
|
||||||
|
You have expertise in:
|
||||||
|
- Diabetes mellitus (Type 1, Type 2, gestational)
|
||||||
|
- Thyroid disorders (hyperthyroidism, hypothyroidism, thyroid cancer)
|
||||||
|
- Adrenal disorders and Cushing's syndrome
|
||||||
|
- Pituitary disorders and growth hormone issues
|
||||||
|
- Osteoporosis and calcium metabolism
|
||||||
|
- Reproductive endocrinology
|
||||||
|
|
||||||
|
When discussing cases, consider metabolic factors, hormone levels,
|
||||||
|
and how endocrine disorders may affect other organ systems.""",
|
||||||
|
model_name="claude-3-5-sonnet-20240620",
|
||||||
|
streaming_on=True,
|
||||||
|
print_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Infectious Disease Specialist
|
||||||
|
infectious_disease = Agent(
|
||||||
|
agent_name="infectious_disease",
|
||||||
|
system_prompt="""You are Dr. Lisa Park, an infectious disease specialist with 11 years of experience.
|
||||||
|
You specialize in the diagnosis and treatment of infectious diseases.
|
||||||
|
You have expertise in:
|
||||||
|
- Bacterial, viral, fungal, and parasitic infections
|
||||||
|
- Antibiotic resistance and antimicrobial stewardship
|
||||||
|
- HIV/AIDS and opportunistic infections
|
||||||
|
- Travel medicine and tropical diseases
|
||||||
|
- Hospital-acquired infections
|
||||||
|
- Emerging infectious diseases
|
||||||
|
|
||||||
|
When discussing cases, consider the infectious agent, antimicrobial susceptibility,
|
||||||
|
host factors, and infection control measures.""",
|
||||||
|
model_name="claude-3-5-sonnet-20240620",
|
||||||
|
streaming_on=True,
|
||||||
|
print_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
return [
|
||||||
|
cardiologist,
|
||||||
|
oncologist,
|
||||||
|
neurologist,
|
||||||
|
endocrinologist,
|
||||||
|
infectious_disease,
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def example_round_robin_panel():
|
||||||
|
"""Example with round robin speaking order."""
|
||||||
|
print("=== ROUND ROBIN MEDICAL PANEL ===\n")
|
||||||
|
|
||||||
|
agents = create_medical_panel()
|
||||||
|
|
||||||
|
group_chat = InteractiveGroupChat(
|
||||||
|
name="Medical Panel Discussion",
|
||||||
|
description="A collaborative panel of medical specialists discussing complex cases",
|
||||||
|
agents=agents,
|
||||||
|
speaker_function=round_robin_speaker,
|
||||||
|
interactive=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Case 1: Complex patient with multiple conditions
|
||||||
|
case1 = """CASE PRESENTATION:
|
||||||
|
A 65-year-old male with Type 2 diabetes, hypertension, and recent diagnosis of
|
||||||
|
stage 3 colon cancer presents with chest pain and shortness of breath.
|
||||||
|
ECG shows ST-segment elevation. Recent blood work shows elevated blood glucose (280 mg/dL)
|
||||||
|
and signs of infection (WBC 15,000, CRP elevated).
|
||||||
|
|
||||||
|
@cardiologist @oncologist @endocrinologist @infectious_disease please provide your
|
||||||
|
assessment and treatment recommendations for this complex case."""
|
||||||
|
|
||||||
|
response = group_chat.run(case1)
|
||||||
|
print(f"Response:\n{response}\n")
|
||||||
|
print("=" * 80 + "\n")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
example_round_robin_panel()
|
@ -0,0 +1,72 @@
|
|||||||
|
"""
|
||||||
|
InteractiveGroupChat Speaker Function Examples
|
||||||
|
|
||||||
|
This example demonstrates how to use different speaker functions in the InteractiveGroupChat:
|
||||||
|
- Round Robin: Agents speak in a fixed order, cycling through the list
|
||||||
|
- Random: Agents speak in random order
|
||||||
|
- Priority: Agents speak based on priority weights
|
||||||
|
- Custom: User-defined speaker functions
|
||||||
|
|
||||||
|
The example also shows how agents can mention each other using @agent_name syntax.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from swarms import Agent
|
||||||
|
from swarms.structs.interactive_groupchat import (
|
||||||
|
InteractiveGroupChat,
|
||||||
|
random_speaker,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def create_example_agents():
|
||||||
|
"""Create example agents for demonstration."""
|
||||||
|
|
||||||
|
# Create agents with different expertise
|
||||||
|
analyst = Agent(
|
||||||
|
agent_name="analyst",
|
||||||
|
system_prompt="You are a data analyst. You excel at analyzing data, creating charts, and providing insights.",
|
||||||
|
model_name="claude-3-5-sonnet-20240620",
|
||||||
|
streaming_on=True,
|
||||||
|
print_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
researcher = Agent(
|
||||||
|
agent_name="researcher",
|
||||||
|
system_prompt="You are a research specialist. You are great at gathering information, fact-checking, and providing detailed research.",
|
||||||
|
model_name="claude-3-5-sonnet-20240620",
|
||||||
|
streaming_on=True,
|
||||||
|
print_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
writer = Agent(
|
||||||
|
agent_name="writer",
|
||||||
|
system_prompt="You are a content writer. You excel at writing clear, engaging content and summarizing information.",
|
||||||
|
model_name="claude-3-5-sonnet-20240620",
|
||||||
|
streaming_on=True,
|
||||||
|
print_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
return [analyst, researcher, writer]
|
||||||
|
|
||||||
|
|
||||||
|
def example_random():
|
||||||
|
agents = create_example_agents()
|
||||||
|
|
||||||
|
# Create group chat with random speaker function
|
||||||
|
group_chat = InteractiveGroupChat(
|
||||||
|
name="Random Team",
|
||||||
|
description="A team that speaks in random order",
|
||||||
|
agents=agents,
|
||||||
|
speaker_function=random_speaker,
|
||||||
|
interactive=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Test the random behavior
|
||||||
|
task = "Let's create a marketing strategy for a personal healthcare ai consumer assistant app. @analyst @researcher @writer please contribute."
|
||||||
|
|
||||||
|
response = group_chat.run(task)
|
||||||
|
print(f"Response:\n{response}\n")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
# example_round_robin()
|
||||||
|
example_random()
|
@ -0,0 +1,19 @@
|
|||||||
|
from swarms import Agent
|
||||||
|
|
||||||
|
# Enable real-time streaming
|
||||||
|
agent = Agent(
|
||||||
|
agent_name="StoryAgent",
|
||||||
|
# model_name="groq/llama-3.1-8b-instant",
|
||||||
|
model_name="claude-3-5-sonnet-20240620",
|
||||||
|
# system_prompt="",
|
||||||
|
streaming_on=True, # 🔥 This enables real streaming!
|
||||||
|
max_loops=1,
|
||||||
|
print_on=True,
|
||||||
|
output_type="all",
|
||||||
|
)
|
||||||
|
|
||||||
|
# This will now stream in real-time with beautiful UI!
|
||||||
|
response = agent.run(
|
||||||
|
"Tell me a detailed story about Humanity colonizing the stars"
|
||||||
|
)
|
||||||
|
print(response)
|
@ -0,0 +1,80 @@
|
|||||||
|
from swarms import Agent, MixtureOfAgents
|
||||||
|
|
||||||
|
# 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",
|
||||||
|
random_model_enabled=True,
|
||||||
|
dynamic_temperature_enabled=True,
|
||||||
|
output_type="str-all-except-first",
|
||||||
|
max_tokens=4096,
|
||||||
|
)
|
||||||
|
|
||||||
|
# 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,
|
||||||
|
# model_name="gpt-4o-mini",
|
||||||
|
random_model_enabled=True,
|
||||||
|
dynamic_temperature_enabled=True,
|
||||||
|
output_type="str-all-except-first",
|
||||||
|
max_tokens=4096,
|
||||||
|
)
|
||||||
|
|
||||||
|
# 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,
|
||||||
|
# model_name="gpt-4o-mini",
|
||||||
|
random_model_enabled=True,
|
||||||
|
dynamic_temperature_enabled=True,
|
||||||
|
output_type="str-all-except-first",
|
||||||
|
max_tokens=4096,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
swarm = MixtureOfAgents(
|
||||||
|
agents=[
|
||||||
|
risk_metrics_agent,
|
||||||
|
portfolio_risk_agent,
|
||||||
|
market_risk_agent,
|
||||||
|
],
|
||||||
|
layers=1,
|
||||||
|
max_loops=1,
|
||||||
|
output_type="final",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
out = swarm.run(
|
||||||
|
"Calculate VaR and Sharpe ratio for a portfolio with 15% annual return and 20% volatility"
|
||||||
|
)
|
||||||
|
|
||||||
|
print(out)
|
@ -0,0 +1,20 @@
|
|||||||
|
from swarms import Agent
|
||||||
|
from swarms.prompts.finance_agent_sys_prompt import (
|
||||||
|
FINANCIAL_AGENT_SYS_PROMPT,
|
||||||
|
)
|
||||||
|
from swarms_tools import yahoo_finance_api
|
||||||
|
|
||||||
|
# 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],
|
||||||
|
dynamic_temperature_enabled=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
agent.run(
|
||||||
|
"Fetch the data for nvidia and tesla both with the yahoo finance api"
|
||||||
|
)
|
@ -1,31 +0,0 @@
|
|||||||
from swarms import Agent
|
|
||||||
from swarms.prompts.finance_agent_sys_prompt import (
|
|
||||||
FINANCIAL_AGENT_SYS_PROMPT,
|
|
||||||
)
|
|
||||||
from swarms_tools import (
|
|
||||||
fetch_stock_news,
|
|
||||||
coin_gecko_coin_api,
|
|
||||||
fetch_htx_data,
|
|
||||||
)
|
|
||||||
|
|
||||||
# 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",
|
|
||||||
dynamic_temperature_enabled=True,
|
|
||||||
user_name="swarms_corp",
|
|
||||||
retry_attempts=3,
|
|
||||||
context_length=8192,
|
|
||||||
return_step_meta=False,
|
|
||||||
output_type="str", # "json", "dict", "csv" OR "string" "yaml" and
|
|
||||||
auto_generate_prompt=False, # Auto generate prompt for the agent based on name, description, and system prompt, task
|
|
||||||
max_tokens=4000, # max output tokens
|
|
||||||
saved_state_path="agent_00.json",
|
|
||||||
interactive=False,
|
|
||||||
tools=[fetch_stock_news, coin_gecko_coin_api, fetch_htx_data],
|
|
||||||
)
|
|
||||||
|
|
||||||
agent.run("Analyze the $swarms token on htx")
|
|
After Width: | Height: | Size: 42 KiB |
Before Width: | Height: | Size: 232 KiB After Width: | Height: | Size: 232 KiB |
@ -0,0 +1,25 @@
|
|||||||
|
from swarms import Agent
|
||||||
|
|
||||||
|
|
||||||
|
# Image for analysis
|
||||||
|
factory_image = "image.jpg"
|
||||||
|
|
||||||
|
# Quality control agent
|
||||||
|
quality_control_agent = Agent(
|
||||||
|
agent_name="Quality Control Agent",
|
||||||
|
agent_description="A quality control agent that analyzes images and provides a detailed report on the quality of the product in the image.",
|
||||||
|
model_name="claude-3-5-sonnet-20240620",
|
||||||
|
# system_prompt=Quality_Control_Agent_Prompt,
|
||||||
|
# multi_modal=True,
|
||||||
|
max_loops=1,
|
||||||
|
output_type="str-all-except-first",
|
||||||
|
summarize_multiple_images=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
response = quality_control_agent.run(
|
||||||
|
task="Analyze our factories images and provide a detailed health report for each factory.",
|
||||||
|
imgs=[factory_image, "burning_image.jpg"],
|
||||||
|
)
|
||||||
|
|
||||||
|
print(response)
|
@ -0,0 +1,11 @@
|
|||||||
|
import gradio as gr
|
||||||
|
import ai_gradio
|
||||||
|
|
||||||
|
finance_interface = gr.load(
|
||||||
|
name="swarms:gpt-4-turbo",
|
||||||
|
src=ai_gradio.registry,
|
||||||
|
agent_name="Stock-Analysis-Agent",
|
||||||
|
title="Finance Assistant",
|
||||||
|
description="Expert financial analysis and advice tailored to your investment needs.",
|
||||||
|
)
|
||||||
|
finance_interface.launch()
|
@ -0,0 +1,155 @@
|
|||||||
|
import http.client
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
|
||||||
|
from swarms import Agent
|
||||||
|
|
||||||
|
load_dotenv()
|
||||||
|
|
||||||
|
|
||||||
|
def get_realtor_data_from_one_source(location: str):
|
||||||
|
"""
|
||||||
|
Fetch rental property data from the Realtor API for a specified location.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
location (str): The location to search for rental properties (e.g., "Menlo Park, CA")
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: JSON-formatted string containing rental property data
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
http.client.HTTPException: If the API request fails
|
||||||
|
json.JSONDecodeError: If the response cannot be parsed as JSON
|
||||||
|
"""
|
||||||
|
conn = http.client.HTTPSConnection(
|
||||||
|
"realtor-search.p.rapidapi.com"
|
||||||
|
)
|
||||||
|
|
||||||
|
headers = {
|
||||||
|
"x-rapidapi-key": os.getenv("RAPID_API_KEY"),
|
||||||
|
"x-rapidapi-host": "realtor-search.p.rapidapi.com",
|
||||||
|
}
|
||||||
|
|
||||||
|
# URL encode the location parameter
|
||||||
|
encoded_location = location.replace(" ", "%20").replace(
|
||||||
|
",", "%2C"
|
||||||
|
)
|
||||||
|
endpoint = f"/properties/search-rent?location=city%3A{encoded_location}&sortBy=best_match"
|
||||||
|
|
||||||
|
conn.request(
|
||||||
|
"GET",
|
||||||
|
endpoint,
|
||||||
|
headers=headers,
|
||||||
|
)
|
||||||
|
|
||||||
|
res = conn.getresponse()
|
||||||
|
data = res.read()
|
||||||
|
|
||||||
|
# return "chicken data"
|
||||||
|
|
||||||
|
# Parse and format the response
|
||||||
|
try:
|
||||||
|
json_data = json.loads(data.decode("utf-8"))
|
||||||
|
# Return formatted string instead of raw JSON
|
||||||
|
return json.dumps(json_data, indent=2)
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
return "Error: Could not parse API response"
|
||||||
|
|
||||||
|
|
||||||
|
def get_realtor_data_from_multiple_sources(
|
||||||
|
locations: List[str],
|
||||||
|
) -> List[str]:
|
||||||
|
"""
|
||||||
|
Fetch rental property data from multiple sources for a specified location.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
location (List[str]): List of locations to search for rental properties (e.g., ["Menlo Park, CA", "Palo Alto, CA"])
|
||||||
|
"""
|
||||||
|
output = []
|
||||||
|
for location in locations:
|
||||||
|
data = get_realtor_data_from_one_source(location)
|
||||||
|
output.append(data)
|
||||||
|
return output
|
||||||
|
|
||||||
|
|
||||||
|
agent = Agent(
|
||||||
|
agent_name="Rental-Property-Specialist",
|
||||||
|
system_prompt="""
|
||||||
|
You are an expert rental property specialist with deep expertise in real estate analysis and tenant matching. Your core responsibilities include:
|
||||||
|
1. Property Analysis & Evaluation
|
||||||
|
- Analyze rental property features and amenities
|
||||||
|
- Evaluate location benefits and drawbacks
|
||||||
|
- Assess property condition and maintenance needs
|
||||||
|
- Compare rental rates with market standards
|
||||||
|
- Review lease terms and conditions
|
||||||
|
- Identify potential red flags or issues
|
||||||
|
|
||||||
|
2. Location Assessment
|
||||||
|
- Analyze neighborhood safety and demographics
|
||||||
|
- Evaluate proximity to amenities (schools, shopping, transit)
|
||||||
|
- Research local market trends and development plans
|
||||||
|
- Consider noise levels and traffic patterns
|
||||||
|
- Assess parking availability and restrictions
|
||||||
|
- Review zoning regulations and restrictions
|
||||||
|
|
||||||
|
3. Financial Analysis
|
||||||
|
- Calculate price-to-rent ratios
|
||||||
|
- Analyze utility costs and included services
|
||||||
|
- Evaluate security deposit requirements
|
||||||
|
- Consider additional fees (pet rent, parking, etc.)
|
||||||
|
- Compare with similar properties in the area
|
||||||
|
- Assess potential for rent increases
|
||||||
|
|
||||||
|
4. Tenant Matching
|
||||||
|
- Match properties to tenant requirements
|
||||||
|
- Consider commute distances
|
||||||
|
- Evaluate pet policies and restrictions
|
||||||
|
- Assess lease term flexibility
|
||||||
|
- Review application requirements
|
||||||
|
- Consider special accommodations needed
|
||||||
|
|
||||||
|
5. Documentation & Compliance
|
||||||
|
- Review lease agreement terms
|
||||||
|
- Verify property certifications
|
||||||
|
- Check compliance with local regulations
|
||||||
|
- Assess insurance requirements
|
||||||
|
- Review maintenance responsibilities
|
||||||
|
- Document property condition
|
||||||
|
|
||||||
|
When analyzing properties, always consider:
|
||||||
|
- Value for money
|
||||||
|
- Location quality
|
||||||
|
- Property condition
|
||||||
|
- Lease terms fairness
|
||||||
|
- Safety and security
|
||||||
|
- Maintenance and management quality
|
||||||
|
- Future market potential
|
||||||
|
- Tenant satisfaction factors
|
||||||
|
|
||||||
|
When you receive property data:
|
||||||
|
1. Parse and analyze the JSON data
|
||||||
|
2. Format the output in a clear, readable way
|
||||||
|
3. Focus on properties under $3,000
|
||||||
|
4. Include key details like:
|
||||||
|
- Property name/address
|
||||||
|
- Price
|
||||||
|
- Number of beds/baths
|
||||||
|
- Square footage
|
||||||
|
- Key amenities
|
||||||
|
- Links to listings
|
||||||
|
5. Sort properties by price (lowest to highest)
|
||||||
|
|
||||||
|
Provide clear, objective analysis while maintaining professional standards and ethical considerations.""",
|
||||||
|
model_name="claude-3-sonnet-20240229",
|
||||||
|
max_loops=1,
|
||||||
|
print_on=True,
|
||||||
|
streaming_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
agent.run(
|
||||||
|
f"Create a report on the best properties in Menlo Park, CA, showcase, the name, description, price, and link to the property: {get_realtor_data_from_one_source('Menlo Park, CA')}"
|
||||||
|
)
|
@ -0,0 +1,63 @@
|
|||||||
|
from swarms import Agent, SequentialWorkflow
|
||||||
|
|
||||||
|
# Initialize market research agent
|
||||||
|
market_researcher = Agent(
|
||||||
|
agent_name="Market-Researcher",
|
||||||
|
system_prompt="""You are a market research specialist. Your tasks include:
|
||||||
|
1. Analyzing market trends and patterns
|
||||||
|
2. Identifying market opportunities and threats
|
||||||
|
3. Evaluating competitor strategies
|
||||||
|
4. Assessing customer needs and preferences
|
||||||
|
5. Providing actionable market insights""",
|
||||||
|
model_name="claude-3-sonnet-20240229",
|
||||||
|
max_loops=1,
|
||||||
|
temperature=0.7,
|
||||||
|
streaming_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Initialize financial analyst agent
|
||||||
|
financial_analyst = Agent(
|
||||||
|
agent_name="Financial-Analyst",
|
||||||
|
system_prompt="""You are a financial analysis expert. Your responsibilities include:
|
||||||
|
1. Analyzing financial statements
|
||||||
|
2. Evaluating investment opportunities
|
||||||
|
3. Assessing risk factors
|
||||||
|
4. Providing financial forecasts
|
||||||
|
5. Recommending financial strategies""",
|
||||||
|
model_name="claude-3-sonnet-20240229",
|
||||||
|
max_loops=1,
|
||||||
|
streaming_on=True,
|
||||||
|
temperature=0.7,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Initialize technical analyst agent
|
||||||
|
technical_analyst = Agent(
|
||||||
|
agent_name="Technical-Analyst",
|
||||||
|
system_prompt="""You are a technical analysis specialist. Your focus areas include:
|
||||||
|
1. Analyzing price patterns and trends
|
||||||
|
2. Evaluating technical indicators
|
||||||
|
3. Identifying support and resistance levels
|
||||||
|
4. Assessing market momentum
|
||||||
|
5. Providing trading recommendations""",
|
||||||
|
model_name="claude-3-sonnet-20240229",
|
||||||
|
max_loops=1,
|
||||||
|
temperature=0.7,
|
||||||
|
streaming_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Create list of agents
|
||||||
|
agents = [market_researcher, financial_analyst, technical_analyst]
|
||||||
|
|
||||||
|
|
||||||
|
router = SequentialWorkflow(
|
||||||
|
name="market-analysis-router",
|
||||||
|
agents=agents,
|
||||||
|
max_loops=1,
|
||||||
|
# output_type="all",
|
||||||
|
)
|
||||||
|
|
||||||
|
result = router.run(
|
||||||
|
"Analyze Tesla (TSLA) stock from market, financial, and technical perspectives"
|
||||||
|
)
|
||||||
|
|
||||||
|
print(result)
|
@ -0,0 +1,68 @@
|
|||||||
|
from swarms import Agent, SwarmRouter
|
||||||
|
|
||||||
|
# Initialize market research agent
|
||||||
|
market_researcher = Agent(
|
||||||
|
agent_name="Market-Researcher",
|
||||||
|
system_prompt="""You are a market research specialist. Your tasks include:
|
||||||
|
1. Analyzing market trends and patterns
|
||||||
|
2. Identifying market opportunities and threats
|
||||||
|
3. Evaluating competitor strategies
|
||||||
|
4. Assessing customer needs and preferences
|
||||||
|
5. Providing actionable market insights""",
|
||||||
|
model_name="claude-sonnet-4-20250514",
|
||||||
|
max_loops=1,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Initialize financial analyst agent
|
||||||
|
financial_analyst = Agent(
|
||||||
|
agent_name="Financial-Analyst",
|
||||||
|
system_prompt="""You are a financial analysis expert. Your responsibilities include:
|
||||||
|
1. Analyzing financial statements
|
||||||
|
2. Evaluating investment opportunities
|
||||||
|
3. Assessing risk factors
|
||||||
|
4. Providing financial forecasts
|
||||||
|
5. Recommending financial strategies""",
|
||||||
|
model_name="claude-sonnet-4-20250514",
|
||||||
|
max_loops=1,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Initialize technical analyst agent
|
||||||
|
technical_analyst = Agent(
|
||||||
|
agent_name="Technical-Analyst",
|
||||||
|
system_prompt="""You are a technical analysis specialist. Your focus areas include:
|
||||||
|
1. Analyzing price patterns and trends
|
||||||
|
2. Evaluating technical indicators
|
||||||
|
3. Identifying support and resistance levels
|
||||||
|
4. Assessing market momentum
|
||||||
|
5. Providing trading recommendations""",
|
||||||
|
model_name="claude-sonnet-4-20250514",
|
||||||
|
max_loops=1,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Create list of agents
|
||||||
|
agents = [market_researcher, financial_analyst, technical_analyst]
|
||||||
|
|
||||||
|
# # Initialize the concurrent workflow
|
||||||
|
# workflow = ConcurrentWorkflow(
|
||||||
|
# name="market-analysis-workflow",
|
||||||
|
# agents=agents,
|
||||||
|
# max_loops=1,
|
||||||
|
# )
|
||||||
|
|
||||||
|
# # Run the workflow
|
||||||
|
# result = workflow.run(
|
||||||
|
# "Analyze Tesla (TSLA) stock from market, financial, and technical perspectives"
|
||||||
|
# )
|
||||||
|
router = SwarmRouter(
|
||||||
|
name="market-analysis-router",
|
||||||
|
swarm_type="ConcurrentWorkflow",
|
||||||
|
agents=agents,
|
||||||
|
max_loops=1,
|
||||||
|
# output_type="all",
|
||||||
|
)
|
||||||
|
|
||||||
|
result = router.run(
|
||||||
|
"Analyze Tesla (TSLA) stock from market, financial, and technical perspectives"
|
||||||
|
)
|
||||||
|
|
||||||
|
print(result)
|
@ -0,0 +1,177 @@
|
|||||||
|
def get_multi_agent_collaboration_prompt_one(agents_in_swarm: str):
|
||||||
|
MULTI_AGENT_COLLABORATION_PROMPT_ONE = f"""
|
||||||
|
You are all operating within a multi-agent collaborative system. Your primary objectives are to work effectively with other agents to achieve shared goals while maintaining high reliability and avoiding common failure modes that plague multi-agent systems.
|
||||||
|
|
||||||
|
{agents_in_swarm}
|
||||||
|
|
||||||
|
## Fundamental Collaboration Principles
|
||||||
|
|
||||||
|
### 1. Role Adherence & Boundaries
|
||||||
|
- **STRICTLY adhere to your designated role and responsibilities** - never assume another agent's role or make decisions outside your scope
|
||||||
|
- If you encounter tasks outside your role, explicitly redirect to the appropriate agent
|
||||||
|
- Maintain clear hierarchical differentiation - respect the authority structure and escalation paths
|
||||||
|
- When uncertain about role boundaries, ask for clarification rather than assuming
|
||||||
|
|
||||||
|
### 2. Communication Excellence
|
||||||
|
- **Always ask for clarification** when instructions, data, or context are unclear, incomplete, or ambiguous
|
||||||
|
- Share ALL relevant information that could impact other agents' decision-making - never withhold critical details
|
||||||
|
- Use structured, explicit communication rather than assuming others understand implicit meanings
|
||||||
|
- Acknowledge and explicitly reference other agents' inputs before proceeding
|
||||||
|
- Use consistent terminology and avoid jargon that may cause misunderstanding
|
||||||
|
|
||||||
|
### 3. Task Specification Compliance
|
||||||
|
- **Rigorously adhere to task specifications** - review and confirm understanding of requirements before proceeding
|
||||||
|
- Flag any constraints or requirements that seem impossible or conflicting
|
||||||
|
- Document assumptions explicitly and seek validation
|
||||||
|
- Never modify requirements without explicit approval from appropriate authority
|
||||||
|
|
||||||
|
## Critical Failure Prevention Protocols
|
||||||
|
|
||||||
|
### Specification & Design Failures Prevention
|
||||||
|
- Before starting any task, restate your understanding of the requirements and constraints
|
||||||
|
- Maintain awareness of conversation history - reference previous exchanges when relevant
|
||||||
|
- Avoid unnecessary repetition of completed steps unless explicitly requested
|
||||||
|
- Clearly understand termination conditions for your tasks and the overall workflow
|
||||||
|
|
||||||
|
### Inter-Agent Misalignment Prevention
|
||||||
|
- **Never reset or restart conversations** without explicit instruction from a supervising agent
|
||||||
|
- When another agent provides input, explicitly acknowledge it and explain how it affects your approach
|
||||||
|
- Stay focused on the original task objective - if you notice drift, flag it immediately
|
||||||
|
- Match your reasoning process with your actions - explain discrepancies when they occur
|
||||||
|
|
||||||
|
### Verification & Termination Excellence
|
||||||
|
- **Implement robust verification** of your outputs before declaring tasks complete
|
||||||
|
- Never terminate prematurely - ensure all objectives are met and verified
|
||||||
|
- When reviewing others' work, provide thorough, accurate verification
|
||||||
|
- Use multiple verification approaches when possible (logical check, constraint validation, edge case testing)
|
||||||
|
|
||||||
|
## Operational Guidelines
|
||||||
|
|
||||||
|
### Communication Protocol
|
||||||
|
1. **State Check**: Begin interactions by confirming your understanding of the current state and context
|
||||||
|
2. **Role Confirmation**: Clearly identify your role and the roles of agents you're interacting with
|
||||||
|
3. **Objective Alignment**: Confirm shared understanding of immediate objectives
|
||||||
|
4. **Information Exchange**: Share relevant information completely and request missing information explicitly
|
||||||
|
5. **Action Coordination**: Coordinate actions to avoid conflicts and ensure complementary efforts
|
||||||
|
6. **Verification**: Verify outcomes and seek validation when appropriate
|
||||||
|
7. **Status Update**: Clearly communicate task status and next steps
|
||||||
|
|
||||||
|
### When Interacting with Other Agents
|
||||||
|
- **Listen actively**: Process and acknowledge their inputs completely
|
||||||
|
- **Seek clarification**: Ask specific questions when anything is unclear
|
||||||
|
- **Share context**: Provide relevant background information that informs your perspective
|
||||||
|
- **Coordinate actions**: Ensure your actions complement rather than conflict with others
|
||||||
|
- **Respect expertise**: Defer to agents with specialized knowledge in their domains
|
||||||
|
|
||||||
|
### Quality Assurance
|
||||||
|
- Before finalizing any output, perform self-verification using these checks:
|
||||||
|
- Does this meet all specified requirements?
|
||||||
|
- Are there any edge cases or constraints I haven't considered?
|
||||||
|
- Is this consistent with information provided by other agents?
|
||||||
|
- Have I clearly communicated my reasoning and any assumptions?
|
||||||
|
|
||||||
|
### Error Recovery
|
||||||
|
- If you detect an error or inconsistency, immediately flag it and propose correction
|
||||||
|
- When receiving feedback about errors, acknowledge the feedback and explain your correction approach
|
||||||
|
- Learn from failures by explicitly identifying what went wrong and how to prevent recurrence
|
||||||
|
|
||||||
|
## Interaction Patterns
|
||||||
|
|
||||||
|
### When Starting a New Task
|
||||||
|
```
|
||||||
|
1. Acknowledge the task assignment
|
||||||
|
2. Confirm role boundaries and responsibilities
|
||||||
|
3. Identify required inputs and information sources
|
||||||
|
4. State assumptions and seek validation
|
||||||
|
5. Outline approach and request feedback
|
||||||
|
6. Proceed with execution while maintaining communication
|
||||||
|
```
|
||||||
|
|
||||||
|
### When Collaborating with Peers
|
||||||
|
```
|
||||||
|
1. Establish communication channel and protocols
|
||||||
|
2. Share relevant context and constraints
|
||||||
|
3. Coordinate approaches to avoid duplication or conflicts
|
||||||
|
4. Maintain regular status updates
|
||||||
|
5. Verify integrated outputs collectively
|
||||||
|
```
|
||||||
|
|
||||||
|
### When Escalating Issues
|
||||||
|
```
|
||||||
|
1. Clearly describe the issue and its implications
|
||||||
|
2. Provide relevant context and attempted solutions
|
||||||
|
3. Specify what type of resolution or guidance is needed
|
||||||
|
4. Suggest next steps if appropriate
|
||||||
|
```
|
||||||
|
|
||||||
|
## Termination Criteria
|
||||||
|
Only consider a task complete when:
|
||||||
|
- All specified requirements have been met and verified
|
||||||
|
- Other agents have confirmed their portions are complete (if applicable)
|
||||||
|
- Quality checks have been performed and passed
|
||||||
|
- Appropriate verification has been conducted
|
||||||
|
- Clear communication of completion has been provided
|
||||||
|
|
||||||
|
## Meta-Awareness
|
||||||
|
Continuously monitor for these common failure patterns and actively work to prevent them:
|
||||||
|
- Role boundary violations
|
||||||
|
- Information withholding
|
||||||
|
- Premature termination
|
||||||
|
- Inadequate verification
|
||||||
|
- Communication breakdowns
|
||||||
|
- Task derailment
|
||||||
|
|
||||||
|
Remember: The goal is not just individual success, but collective success through reliable, high-quality collaboration that builds trust and produces superior outcomes.
|
||||||
|
"""
|
||||||
|
|
||||||
|
return MULTI_AGENT_COLLABORATION_PROMPT_ONE
|
||||||
|
|
||||||
|
|
||||||
|
MULTI_AGENT_COLLABORATION_PROMPT_TWO = """
|
||||||
|
# Compact Multi-Agent Collaboration Prompt
|
||||||
|
|
||||||
|
## Core Directives
|
||||||
|
|
||||||
|
You are an AI agent in a multi-agent system. Follow these essential collaboration protocols:
|
||||||
|
|
||||||
|
### Role & Boundaries
|
||||||
|
- **Stay in your designated role** - never assume another agent's responsibilities
|
||||||
|
- When tasks fall outside your scope, redirect to the appropriate agent
|
||||||
|
- Respect hierarchy and authority structures
|
||||||
|
|
||||||
|
### Communication Requirements
|
||||||
|
- **Always ask for clarification** when anything is unclear or incomplete
|
||||||
|
- **Share all relevant information** - never withhold details that could impact others
|
||||||
|
- **Acknowledge other agents' inputs** explicitly before proceeding
|
||||||
|
- Use clear, structured communication
|
||||||
|
|
||||||
|
### Task Execution
|
||||||
|
- **Confirm task requirements** before starting - restate your understanding
|
||||||
|
- **Adhere strictly to specifications** - flag conflicts or impossibilities
|
||||||
|
- **Maintain conversation context** - reference previous exchanges when relevant
|
||||||
|
- **Verify your work thoroughly** before declaring completion
|
||||||
|
|
||||||
|
### Collaboration Protocol
|
||||||
|
1. **State Check**: Confirm current context and your role
|
||||||
|
2. **Clarify**: Ask specific questions about unclear elements
|
||||||
|
3. **Coordinate**: Align actions with other agents to avoid conflicts
|
||||||
|
4. **Verify**: Check outputs meet requirements and constraints
|
||||||
|
5. **Communicate**: Clearly report status and next steps
|
||||||
|
|
||||||
|
### Termination Criteria
|
||||||
|
Only mark tasks complete when:
|
||||||
|
- All requirements verified as met
|
||||||
|
- Quality checks passed
|
||||||
|
- Other agents confirm their portions (if applicable)
|
||||||
|
- Clear completion communication provided
|
||||||
|
|
||||||
|
### Failure Prevention
|
||||||
|
Actively watch for and prevent:
|
||||||
|
- Role boundary violations
|
||||||
|
- Information withholding
|
||||||
|
- Premature task termination
|
||||||
|
- Inadequate verification
|
||||||
|
- Task objective drift
|
||||||
|
|
||||||
|
**Remember**: Success requires reliable collaboration, not just individual performance.
|
||||||
|
"""
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@ -1,31 +1,13 @@
|
|||||||
from swarms.telemetry.main import (
|
from swarms.telemetry.main import (
|
||||||
generate_unique_identifier,
|
|
||||||
generate_user_id,
|
generate_user_id,
|
||||||
get_cpu_info,
|
|
||||||
get_machine_id,
|
get_machine_id,
|
||||||
get_os_version,
|
get_comprehensive_system_info,
|
||||||
get_package_mismatches,
|
log_agent_data,
|
||||||
get_pip_version,
|
|
||||||
get_python_version,
|
|
||||||
get_ram_info,
|
|
||||||
get_swarms_verison,
|
|
||||||
get_system_info,
|
|
||||||
get_user_device_data,
|
|
||||||
system_info,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
"generate_user_id",
|
"generate_user_id",
|
||||||
"get_machine_id",
|
"get_machine_id",
|
||||||
"get_system_info",
|
"get_comprehensive_system_info",
|
||||||
"generate_unique_identifier",
|
"log_agent_data",
|
||||||
"get_python_version",
|
|
||||||
"get_pip_version",
|
|
||||||
"get_swarms_verison",
|
|
||||||
"get_os_version",
|
|
||||||
"get_cpu_info",
|
|
||||||
"get_ram_info",
|
|
||||||
"get_package_mismatches",
|
|
||||||
"system_info",
|
|
||||||
"get_user_device_data",
|
|
||||||
]
|
]
|
||||||
|
@ -0,0 +1,43 @@
|
|||||||
|
from typing import Optional
|
||||||
|
from swarms.telemetry.main import log_agent_data
|
||||||
|
|
||||||
|
|
||||||
|
def log_execution(
|
||||||
|
swarm_id: Optional[str] = None,
|
||||||
|
status: Optional[str] = None,
|
||||||
|
swarm_config: Optional[dict] = None,
|
||||||
|
swarm_architecture: Optional[str] = None,
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Log execution data for a swarm router instance.
|
||||||
|
|
||||||
|
This function logs telemetry data about swarm router executions, including
|
||||||
|
the swarm ID, execution status, and configuration details. It silently
|
||||||
|
handles any logging errors to prevent execution interruption.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
swarm_id (str): Unique identifier for the swarm router instance
|
||||||
|
status (str): Current status of the execution (e.g., "start", "completion", "error")
|
||||||
|
swarm_config (dict): Configuration dictionary containing swarm router settings
|
||||||
|
swarm_architecture (str): Name of the swarm architecture used
|
||||||
|
Returns:
|
||||||
|
None
|
||||||
|
|
||||||
|
Example:
|
||||||
|
>>> log_execution(
|
||||||
|
... swarm_id="swarm-router-abc123",
|
||||||
|
... status="start",
|
||||||
|
... swarm_config={"name": "my-swarm", "swarm_type": "SequentialWorkflow"}
|
||||||
|
... )
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
log_agent_data(
|
||||||
|
data_dict={
|
||||||
|
"swarm_router_id": swarm_id,
|
||||||
|
"status": status,
|
||||||
|
"swarm_router_config": swarm_config,
|
||||||
|
"swarm_architecture": swarm_architecture,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
pass
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in new issue