parent
57eca9b6a2
commit
5af454020a
@ -1,105 +0,0 @@
|
||||
## Usage Documentation: Discord Bot with Advanced Features
|
||||
|
||||
---
|
||||
|
||||
### Overview:
|
||||
|
||||
This code provides a structure for a Discord bot with advanced features such as voice channel interactions, image generation, and text-based interactions using OpenAI models.
|
||||
|
||||
---
|
||||
|
||||
### Setup:
|
||||
|
||||
1. Ensure that the necessary libraries are installed:
|
||||
```bash
|
||||
pip install discord.py python-dotenv dalle3 invoke openai
|
||||
```
|
||||
|
||||
2. Create a `.env` file in the same directory as your bot script and add the following:
|
||||
```
|
||||
DISCORD_TOKEN=your_discord_bot_token
|
||||
STORAGE_SERVICE=your_storage_service_endpoint
|
||||
SAVE_DIRECTORY=path_to_save_generated_images
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Bot Class and its Methods:
|
||||
|
||||
#### `__init__(self, agent, llm, command_prefix="!")`:
|
||||
|
||||
Initializes the bot with the given agent, language model (`llm`), and a command prefix (default is `!`).
|
||||
|
||||
#### `add_command(self, name, func)`:
|
||||
|
||||
Allows you to dynamically add new commands to the bot. The `name` is the command's name and `func` is the function to execute when the command is called.
|
||||
|
||||
#### `run(self)`:
|
||||
|
||||
Starts the bot using the `DISCORD_TOKEN` from the `.env` file.
|
||||
|
||||
---
|
||||
|
||||
### Commands:
|
||||
|
||||
1. **!greet**: Greets the user.
|
||||
|
||||
2. **!help_me**: Provides a list of commands and their descriptions.
|
||||
|
||||
3. **!join**: Joins the voice channel the user is in.
|
||||
|
||||
4. **!leave**: Leaves the voice channel the bot is currently in.
|
||||
|
||||
5. **!listen**: Starts listening to voice in the current voice channel and records the audio.
|
||||
|
||||
6. **!generate_image [prompt]**: Generates images based on the provided prompt using the DALL-E3 model.
|
||||
|
||||
7. **!send_text [text] [use_agent=True]**: Sends the provided text to the worker (either the agent or the LLM) and returns the response.
|
||||
|
||||
---
|
||||
|
||||
### Usage:
|
||||
|
||||
Initialize the `llm` (Language Learning Model) with your OpenAI API key:
|
||||
|
||||
```python
|
||||
from swarm_models import OpenAIChat
|
||||
|
||||
llm = OpenAIChat(
|
||||
openai_api_key="Your_OpenAI_API_Key",
|
||||
temperature=0.5,
|
||||
)
|
||||
```
|
||||
|
||||
Initialize the bot with the `llm`:
|
||||
|
||||
```python
|
||||
from apps.discord import Bot
|
||||
|
||||
bot = Bot(llm=llm)
|
||||
```
|
||||
|
||||
Send a task to the bot:
|
||||
|
||||
```python
|
||||
task = "What were the winning Boston Marathon times for the past 5 years (ending in 2022)? Generate a table of the year, name, country of origin, and times."
|
||||
bot.send_text(task)
|
||||
```
|
||||
|
||||
Start the bot:
|
||||
|
||||
```python
|
||||
bot.run()
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Additional Notes:
|
||||
|
||||
- The bot makes use of the `dalle3` library for image generation. Ensure you have the model and necessary setup for it.
|
||||
|
||||
- For the storage service, you might want to integrate with a cloud service like Google Cloud Storage or AWS S3 to store and retrieve generated images. The given code assumes a method `.upload()` for the storage service to upload files.
|
||||
|
||||
- Ensure that you've granted the bot necessary permissions on Discord, especially if you want to use voice channel features.
|
||||
|
||||
- Handle API keys and tokens securely. Avoid hardcoding them directly into your code. Use environment variables or secure secret management tools.
|
@ -0,0 +1,765 @@
|
||||
# Swarms API: Orchestrating the Future of AI Agent Collaboration
|
||||
|
||||
In today's rapidly evolving AI landscape, we're witnessing a fundamental shift from single-agent AI systems to complex, collaborative multi-agent architectures. While individual AI models like GPT-4 and Claude have demonstrated remarkable capabilities, they often struggle with complex tasks requiring diverse expertise, nuanced decision-making, and specialized domain knowledge. Enter the Swarms API, an enterprise-grade solution designed to orchestrate collaborative intelligence through coordinated AI agent swarms.
|
||||
|
||||
## The Problem: The Limitations of Single-Agent AI
|
||||
|
||||
Despite significant advances in large language models and AI systems, single-agent architectures face inherent limitations when tackling complex real-world problems:
|
||||
|
||||
### Expertise Boundaries
|
||||
Even the most advanced AI models have knowledge boundaries. No single model can possess expert-level knowledge across all domains simultaneously. When a task requires deep expertise in multiple areas (finance, law, medicine, and technical analysis, for example), a single agent quickly reaches its limits.
|
||||
|
||||
### Complex Reasoning Chains
|
||||
Many real-world problems demand multistep reasoning with multiple feedback loops and verification processes. Single agents often struggle to maintain reasoning coherence through extended problem-solving journeys, leading to errors that compound over time.
|
||||
|
||||
### Workflow Orchestration
|
||||
Enterprise applications frequently require sophisticated workflows with multiple handoffs, approvals, and specialized processing steps. Managing this orchestration with individual AI instances is inefficient and error-prone.
|
||||
|
||||
### Resource Optimization
|
||||
Deploying high-powered AI models for every task is expensive and inefficient. Organizations need right-sized solutions that match computing resources to task requirements.
|
||||
|
||||
### Collaboration Mechanisms
|
||||
The most sophisticated human problem-solving happens in teams, where specialists collaborate, debate, and refine solutions together. This collaborative intelligence is difficult to replicate with isolated AI agents.
|
||||
|
||||
## The Solution: Swarms API
|
||||
|
||||
The Swarms API addresses these challenges through a revolutionary approach to AI orchestration. By enabling multiple specialized agents to collaborate in coordinated swarms, it unlocks new capabilities previously unattainable with single-agent architectures.
|
||||
|
||||
### What is the Swarms API?
|
||||
|
||||
The Swarms API is an enterprise-grade platform that enables organizations to deploy and manage intelligent agent swarms in the cloud. Rather than relying on a single AI agent to handle complex tasks, the Swarms API orchestrates teams of specialized AI agents that work together, each handling specific aspects of a larger problem.
|
||||
|
||||
The platform provides a robust infrastructure for creating, executing, and managing sophisticated AI agent workflows without the burden of maintaining the underlying infrastructure. With its cloud-native architecture, the Swarms API offers scalability, reliability, and security essential for enterprise deployments.
|
||||
|
||||
## Core Capabilities
|
||||
|
||||
The Swarms API delivers a comprehensive suite of capabilities designed for production-grade AI orchestration:
|
||||
|
||||
### Intelligent Swarm Management
|
||||
|
||||
At its core, the Swarms API enables the creation and execution of collaborative agent swarms. These swarms consist of specialized AI agents designed to work together on complex tasks. Unlike traditional AI approaches where a single model handles the entire workload, swarms distribute tasks among specialized agents, each contributing its expertise to the collective solution.
|
||||
|
||||
For example, a financial analysis swarm might include:
|
||||
- A data preprocessing agent that cleans and normalizes financial data
|
||||
- A market analyst agent that identifies trends and patterns
|
||||
- An economic forecasting agent that predicts future market conditions
|
||||
- A report generation agent that compiles insights into a comprehensive analysis
|
||||
|
||||
By coordinating these specialized agents, the swarm can deliver more accurate, nuanced, and valuable results than any single agent could produce alone.
|
||||
|
||||
### Automatic Agent Generation
|
||||
|
||||
One of the most powerful features of the Swarms API is its ability to dynamically create optimized agents based on task requirements. Rather than manually configuring each agent in a swarm, users can specify the overall task and let the platform automatically generate appropriate agents with optimized prompts and configurations.
|
||||
|
||||
This automatic agent generation significantly reduces the expertise and effort required to deploy effective AI solutions. The system analyzes the task requirements and creates a set of agents specifically designed to address different aspects of the problem. This approach not only saves time but also improves the quality of results by ensuring each agent is properly configured for its specific role.
|
||||
|
||||
### Multiple Swarm Architectures
|
||||
|
||||
Different problems require different collaboration patterns. The Swarms API supports various swarm architectures to match specific workflow needs:
|
||||
|
||||
- **SequentialWorkflow**: Agents work in a predefined sequence, with each agent handling specific subtasks in order
|
||||
- **ConcurrentWorkflow**: Multiple agents work simultaneously on different aspects of a task
|
||||
- **GroupChat**: Agents collaborate in a discussion format to solve problems collectively
|
||||
- **HierarchicalSwarm**: Organizes agents in a structured hierarchy with managers and workers
|
||||
- **MajorityVoting**: Uses a consensus mechanism where multiple agents vote on the best solution
|
||||
- **AutoSwarmBuilder**: Automatically designs and builds an optimal swarm architecture based on the task
|
||||
- **MixtureOfAgents**: Combines multiple agent types to tackle diverse aspects of a problem
|
||||
- **MultiAgentRouter**: Routes subtasks to specialized agents based on their capabilities
|
||||
- **AgentRearrange**: Dynamically reorganizes the workflow between agents based on evolving task requirements
|
||||
|
||||
This flexibility allows organizations to select the most appropriate collaboration pattern for each specific use case, optimizing the balance between efficiency, thoroughness, and creativity.
|
||||
|
||||
### Scheduled Execution
|
||||
|
||||
The Swarms API enables automated, scheduled swarm executions, allowing organizations to set up recurring tasks that run automatically at specified times. This feature is particularly valuable for regular reporting, monitoring, and analysis tasks that need to be performed on a consistent schedule.
|
||||
|
||||
For example, a financial services company could schedule a daily market analysis swarm to run before trading hours, providing updated insights based on overnight market movements. Similarly, a cybersecurity team might schedule hourly security assessment swarms to continuously monitor potential threats.
|
||||
|
||||
### Comprehensive Logging
|
||||
|
||||
Transparency and auditability are essential for enterprise AI applications. The Swarms API provides comprehensive logging capabilities that track all API interactions, agent communications, and decision processes. This detailed logging enables:
|
||||
|
||||
- Debugging and troubleshooting swarm behaviors
|
||||
- Auditing decision trails for compliance and quality assurance
|
||||
- Analyzing performance patterns to identify optimization opportunities
|
||||
- Documenting the rationale behind AI-generated recommendations
|
||||
|
||||
These logs provide valuable insights into how swarms operate and make decisions, increasing trust and enabling continuous improvement of AI workflows.
|
||||
|
||||
### Cost Management
|
||||
|
||||
AI deployment costs can quickly escalate without proper oversight. The Swarms API addresses this challenge through:
|
||||
|
||||
- **Predictable, transparent pricing**: Clear cost structures that make budgeting straightforward
|
||||
- **Optimized resource utilization**: Intelligent allocation of computing resources based on task requirements
|
||||
- **Detailed cost breakdowns**: Comprehensive reporting on token usage, agent costs, and total expenditures
|
||||
- **Model flexibility**: Freedom to choose the most cost-effective models for each agent based on task complexity
|
||||
|
||||
This approach ensures organizations get maximum value from their AI investments without unexpected cost overruns.
|
||||
|
||||
### Enterprise Security
|
||||
|
||||
Security is paramount for enterprise AI deployments. The Swarms API implements robust security measures including:
|
||||
|
||||
- **Full API key authentication**: Secure access control for all API interactions
|
||||
- **Comprehensive key management**: Tools for creating, rotating, and revoking API keys
|
||||
- **Usage monitoring**: Tracking and alerting for suspicious activity patterns
|
||||
- **Secure data handling**: Appropriate data protection throughout the swarm execution lifecycle
|
||||
|
||||
These security features ensure that sensitive data and AI workflows remain protected in accordance with enterprise security requirements.
|
||||
|
||||
## How It Works: Behind the Scenes
|
||||
|
||||
The Swarms API operates on a sophisticated architecture designed for reliability, scalability, and performance. Here's a look at what happens when you submit a task to the Swarms API:
|
||||
|
||||
1. **Task Submission**: You send a request to the API with your task description and desired swarm configuration.
|
||||
|
||||
2. **Swarm Configuration**: The system either uses your specified agent configuration or automatically generates an optimal swarm structure based on the task requirements.
|
||||
|
||||
3. **Agent Initialization**: Each agent in the swarm is initialized with its specific instructions, model parameters, and role definitions.
|
||||
|
||||
4. **Orchestration Setup**: The system establishes the communication and workflow patterns between agents based on the selected swarm architecture.
|
||||
|
||||
5. **Execution**: The swarm begins working on the task, with agents collaborating according to their defined roles and relationships.
|
||||
|
||||
6. **Monitoring and Adjustment**: Throughout execution, the system monitors agent performance and makes adjustments as needed.
|
||||
|
||||
7. **Result Compilation**: Once the task is complete, the system compiles the results into the requested format.
|
||||
|
||||
8. **Response Delivery**: The final output is returned to you, along with metadata about the execution process.
|
||||
|
||||
This entire process happens seamlessly in the cloud, with the Swarms API handling all the complexities of agent coordination, resource allocation, and workflow management.
|
||||
|
||||
## Real-World Applications
|
||||
|
||||
The Swarms API enables a wide range of applications across industries. Here are some compelling use cases that demonstrate its versatility:
|
||||
|
||||
### Financial Services
|
||||
|
||||
#### Investment Research
|
||||
Financial institutions can deploy research swarms that combine market analysis, economic forecasting, company evaluation, and risk assessment. These swarms can evaluate investment opportunities much more comprehensively than single-agent systems, considering multiple factors simultaneously:
|
||||
|
||||
- Macroeconomic indicators
|
||||
- Company fundamentals
|
||||
- Market sentiment
|
||||
- Technical analysis patterns
|
||||
- Regulatory considerations
|
||||
|
||||
For example, an investment research swarm analyzing a potential stock purchase might include specialists in the company's industry, financial statement analysis, market trend identification, and risk assessment. This collaborative approach delivers more nuanced insights than any single analyst or model could produce independently.
|
||||
|
||||
#### Regulatory Compliance
|
||||
Financial regulations are complex and constantly evolving. Compliance swarms can monitor regulatory changes, assess their impact on existing policies, and recommend appropriate adjustments. These swarms might include:
|
||||
|
||||
- Regulatory monitoring agents that track new rules and guidelines
|
||||
- Policy analysis agents that evaluate existing compliance frameworks
|
||||
- Gap assessment agents that identify discrepancies
|
||||
- Documentation agents that update compliance materials
|
||||
|
||||
This approach ensures comprehensive coverage of regulatory requirements while minimizing compliance risks.
|
||||
|
||||
### Healthcare
|
||||
|
||||
#### Medical Research Analysis
|
||||
The medical literature grows at an overwhelming pace, making it difficult for researchers and clinicians to stay current. Research analysis swarms can continuously scan new publications, identify relevant findings, and synthesize insights for specific research questions or clinical scenarios.
|
||||
|
||||
A medical research swarm might include:
|
||||
- Literature scanning agents that identify relevant publications
|
||||
- Methodology assessment agents that evaluate research quality
|
||||
- Clinical relevance agents that determine practical applications
|
||||
- Summary agents that compile key findings into accessible reports
|
||||
|
||||
This collaborative approach enables more thorough literature reviews and helps bridge the gap between research and clinical practice.
|
||||
|
||||
#### Treatment Planning
|
||||
Complex medical cases often benefit from multidisciplinary input. Treatment planning swarms can integrate perspectives from different medical specialties, consider patient-specific factors, and recommend comprehensive care approaches.
|
||||
|
||||
For example, an oncology treatment planning swarm might include specialists in:
|
||||
- Diagnostic interpretation
|
||||
- Treatment protocol evaluation
|
||||
- Drug interaction assessment
|
||||
- Patient history analysis
|
||||
- Evidence-based outcome prediction
|
||||
|
||||
By combining these specialized perspectives, the swarm can develop more personalized and effective treatment recommendations.
|
||||
|
||||
### Legal Services
|
||||
|
||||
#### Contract Analysis
|
||||
Legal contracts contain numerous interconnected provisions that must be evaluated holistically. Contract analysis swarms can review complex agreements more thoroughly by assigning different sections to specialized agents:
|
||||
|
||||
- Definition analysis agents that ensure consistent terminology
|
||||
- Risk assessment agents that identify potential liabilities
|
||||
- Compliance agents that check regulatory requirements
|
||||
- Precedent comparison agents that evaluate terms against standards
|
||||
- Conflict detection agents that identify internal inconsistencies
|
||||
|
||||
This distributed approach enables more comprehensive contract reviews while reducing the risk of overlooking critical details.
|
||||
|
||||
#### Legal Research
|
||||
Legal research requires examining statutes, case law, regulations, and scholarly commentary. Research swarms can conduct multi-faceted legal research by coordinating specialized agents focusing on different aspects of the legal landscape.
|
||||
|
||||
A legal research swarm might include:
|
||||
- Statutory analysis agents that examine relevant laws
|
||||
- Case law agents that review judicial precedents
|
||||
- Regulatory agents that assess administrative rules
|
||||
- Scholarly analysis agents that evaluate academic perspectives
|
||||
- Synthesis agents that integrate findings into cohesive arguments
|
||||
|
||||
This collaborative approach produces more comprehensive legal analyses that consider multiple sources of authority.
|
||||
|
||||
### Research and Development
|
||||
|
||||
#### Scientific Literature Review
|
||||
Scientific research increasingly spans multiple disciplines, making comprehensive literature reviews challenging. Literature review swarms can analyze publications across relevant fields, identify methodological approaches, and synthesize findings from diverse sources.
|
||||
|
||||
For example, a biomedical engineering literature review swarm might include specialists in:
|
||||
- Materials science
|
||||
- Cellular biology
|
||||
- Clinical applications
|
||||
- Regulatory requirements
|
||||
- Statistical methods
|
||||
|
||||
By integrating insights from these different perspectives, the swarm can produce more comprehensive and valuable literature reviews.
|
||||
|
||||
#### Experimental Design
|
||||
Designing robust experiments requires considering multiple factors simultaneously. Experimental design swarms can develop sophisticated research protocols by integrating methodological expertise, statistical considerations, practical constraints, and ethical requirements.
|
||||
|
||||
An experimental design swarm might coordinate:
|
||||
- Methodology agents that design experimental procedures
|
||||
- Statistical agents that determine appropriate sample sizes and analyses
|
||||
- Logistics agents that assess practical feasibility
|
||||
- Ethics agents that evaluate potential concerns
|
||||
- Documentation agents that prepare formal protocols
|
||||
|
||||
This collaborative approach leads to more rigorous experimental designs while addressing potential issues preemptively.
|
||||
|
||||
### Software Development
|
||||
|
||||
#### Code Review and Optimization
|
||||
Code review requires evaluating multiple aspects simultaneously: functionality, security, performance, maintainability, and adherence to standards. Code review swarms can distribute these concerns among specialized agents:
|
||||
|
||||
- Functionality agents that evaluate whether code meets requirements
|
||||
- Security agents that identify potential vulnerabilities
|
||||
- Performance agents that assess computational efficiency
|
||||
- Style agents that check adherence to coding standards
|
||||
- Documentation agents that review comments and documentation
|
||||
|
||||
By addressing these different aspects in parallel, code review swarms can provide more comprehensive feedback to development teams.
|
||||
|
||||
#### System Architecture Design
|
||||
Designing complex software systems requires balancing numerous considerations. Architecture design swarms can develop more robust system designs by coordinating specialists in different architectural concerns:
|
||||
|
||||
- Scalability agents that evaluate growth potential
|
||||
- Security agents that assess protective measures
|
||||
- Performance agents that analyze efficiency
|
||||
- Maintainability agents that consider long-term management
|
||||
- Integration agents that evaluate external system connections
|
||||
|
||||
This collaborative approach leads to more balanced architectural decisions that address multiple requirements simultaneously.
|
||||
|
||||
## Getting Started with the Swarms API
|
||||
|
||||
The Swarms API is designed for straightforward integration into existing workflows. Let's walk through the setup process and explore some practical code examples for different industries.
|
||||
|
||||
### 1. Setting Up Your Environment
|
||||
|
||||
First, create an account on [swarms.world](https://swarms.world). After registration, navigate to the API key management interface at [https://swarms.world/platform/api-keys](https://swarms.world/platform/api-keys) to generate your API key.
|
||||
|
||||
Once you have your API key, set up your Python environment:
|
||||
|
||||
```python
|
||||
# Install required packages
|
||||
pip install requests python-dotenv
|
||||
```
|
||||
|
||||
Create a basic project structure:
|
||||
|
||||
```
|
||||
swarms-project/
|
||||
├── .env # Store your API key securely
|
||||
├── swarms_client.py # Helper functions for API interaction
|
||||
└── examples/ # Industry-specific examples
|
||||
```
|
||||
|
||||
In your `.env` file, add your API key:
|
||||
|
||||
```
|
||||
SWARMS_API_KEY=your_api_key_here
|
||||
```
|
||||
|
||||
### 2. Creating a Basic Swarms Client
|
||||
|
||||
Let's create a simple client to interact with the Swarms API:
|
||||
|
||||
```python
|
||||
# swarms_client.py
|
||||
import os
|
||||
import requests
|
||||
from dotenv import load_dotenv
|
||||
import json
|
||||
|
||||
# Load environment variables
|
||||
load_dotenv()
|
||||
|
||||
# Configuration
|
||||
API_KEY = os.getenv("SWARMS_API_KEY")
|
||||
BASE_URL = "https://api.swarms.world"
|
||||
|
||||
# Standard headers for all requests
|
||||
headers = {
|
||||
"x-api-key": API_KEY,
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
|
||||
def check_api_health():
|
||||
"""Simple health check to verify API connectivity."""
|
||||
response = requests.get(f"{BASE_URL}/health", headers=headers)
|
||||
return response.json()
|
||||
|
||||
def run_swarm(swarm_config):
|
||||
"""Execute a swarm with the provided configuration."""
|
||||
response = requests.post(
|
||||
f"{BASE_URL}/v1/swarm/completions",
|
||||
headers=headers,
|
||||
json=swarm_config
|
||||
)
|
||||
return response.json()
|
||||
|
||||
def get_available_swarms():
|
||||
"""Retrieve list of available swarm types."""
|
||||
response = requests.get(f"{BASE_URL}/v1/swarms/available", headers=headers)
|
||||
return response.json()
|
||||
|
||||
def get_available_models():
|
||||
"""Retrieve list of available AI models."""
|
||||
response = requests.get(f"{BASE_URL}/v1/models/available", headers=headers)
|
||||
return response.json()
|
||||
|
||||
def get_swarm_logs():
|
||||
"""Retrieve logs of previous swarm executions."""
|
||||
response = requests.get(f"{BASE_URL}/v1/swarm/logs", headers=headers)
|
||||
return response.json()
|
||||
```
|
||||
|
||||
### 3. Industry-Specific Examples
|
||||
|
||||
Let's explore practical applications of the Swarms API across different industries.
|
||||
|
||||
#### Healthcare: Clinical Research Assistant
|
||||
|
||||
This example creates a swarm that analyzes clinical trial data and summarizes findings:
|
||||
|
||||
```python
|
||||
# healthcare_example.py
|
||||
from swarms_client import run_swarm
|
||||
import json
|
||||
|
||||
def clinical_research_assistant():
|
||||
"""
|
||||
Create a swarm that analyzes clinical trial data, identifies patterns,
|
||||
and generates comprehensive research summaries.
|
||||
"""
|
||||
swarm_config = {
|
||||
"name": "Clinical Research Assistant",
|
||||
"description": "Analyzes medical research data and synthesizes findings",
|
||||
"agents": [
|
||||
{
|
||||
"agent_name": "Data Preprocessor",
|
||||
"description": "Cleans and organizes clinical trial data",
|
||||
"system_prompt": "You are a data preprocessing specialist focused on clinical trials. "
|
||||
"Your task is to organize, clean, and structure raw clinical data for analysis. "
|
||||
"Identify and handle missing values, outliers, and inconsistencies in the data.",
|
||||
"model_name": "gpt-4o",
|
||||
"role": "worker",
|
||||
"max_loops": 1
|
||||
},
|
||||
{
|
||||
"agent_name": "Clinical Analyst",
|
||||
"description": "Analyzes preprocessed data to identify patterns and insights",
|
||||
"system_prompt": "You are a clinical research analyst with expertise in interpreting medical data. "
|
||||
"Your job is to examine preprocessed clinical trial data, identify significant patterns, "
|
||||
"and determine the clinical relevance of these findings. Consider factors such as "
|
||||
"efficacy, safety profiles, and patient subgroups.",
|
||||
"model_name": "gpt-4o",
|
||||
"role": "worker",
|
||||
"max_loops": 1
|
||||
},
|
||||
{
|
||||
"agent_name": "Medical Writer",
|
||||
"description": "Synthesizes analysis into comprehensive reports",
|
||||
"system_prompt": "You are a medical writer specializing in clinical research. "
|
||||
"Your task is to take the analyses provided and create comprehensive, "
|
||||
"well-structured reports that effectively communicate findings to both "
|
||||
"medical professionals and regulatory authorities. Follow standard "
|
||||
"medical publication guidelines.",
|
||||
"model_name": "gpt-4o",
|
||||
"role": "worker",
|
||||
"max_loops": 1
|
||||
}
|
||||
],
|
||||
"max_loops": 1,
|
||||
"swarm_type": "SequentialWorkflow",
|
||||
"task": "Analyze the provided Phase III clinical trial data for Drug XYZ, "
|
||||
"a novel treatment for type 2 diabetes. Identify efficacy patterns across "
|
||||
"different patient demographics, note any safety concerns, and prepare "
|
||||
"a comprehensive summary suitable for submission to regulatory authorities."
|
||||
}
|
||||
|
||||
# Execute the swarm
|
||||
result = run_swarm(swarm_config)
|
||||
|
||||
# Print formatted results
|
||||
print(json.dumps(result, indent=4))
|
||||
return result
|
||||
|
||||
if __name__ == "__main__":
|
||||
clinical_research_assistant()
|
||||
```
|
||||
|
||||
#### Legal: Contract Analysis System
|
||||
|
||||
This example demonstrates a swarm designed to analyze complex legal contracts:
|
||||
|
||||
```python
|
||||
# legal_example.py
|
||||
from swarms_client import run_swarm
|
||||
import json
|
||||
|
||||
def contract_analysis_system():
|
||||
"""
|
||||
Create a swarm that thoroughly analyzes legal contracts,
|
||||
identifies potential risks, and suggests improvements.
|
||||
"""
|
||||
swarm_config = {
|
||||
"name": "Contract Analysis System",
|
||||
"description": "Analyzes legal contracts for risks and improvement opportunities",
|
||||
"agents": [
|
||||
{
|
||||
"agent_name": "Clause Extractor",
|
||||
"description": "Identifies and categorizes key clauses in contracts",
|
||||
"system_prompt": "You are a legal document specialist. Your task is to "
|
||||
"carefully review legal contracts and identify all key clauses, "
|
||||
"categorizing them by type (liability, indemnification, termination, etc.). "
|
||||
"Extract each clause with its context and prepare them for detailed analysis.",
|
||||
"model_name": "gpt-4o",
|
||||
"role": "worker",
|
||||
"max_loops": 1
|
||||
},
|
||||
{
|
||||
"agent_name": "Risk Assessor",
|
||||
"description": "Evaluates clauses for potential legal risks",
|
||||
"system_prompt": "You are a legal risk assessment expert. Your job is to "
|
||||
"analyze contract clauses and identify potential legal risks, "
|
||||
"exposure points, and unfavorable terms. Rate each risk on a "
|
||||
"scale of 1-5 and provide justification for your assessment.",
|
||||
"model_name": "gpt-4o",
|
||||
"role": "worker",
|
||||
"max_loops": 1
|
||||
},
|
||||
{
|
||||
"agent_name": "Improvement Recommender",
|
||||
"description": "Suggests alternative language to mitigate risks",
|
||||
"system_prompt": "You are a contract drafting expert. Based on the risk "
|
||||
"assessment provided, suggest alternative language for "
|
||||
"problematic clauses to better protect the client's interests. "
|
||||
"Ensure suggestions are legally sound and professionally worded.",
|
||||
"model_name": "gpt-4o",
|
||||
"role": "worker",
|
||||
"max_loops": 1
|
||||
},
|
||||
{
|
||||
"agent_name": "Summary Creator",
|
||||
"description": "Creates executive summary of findings and recommendations",
|
||||
"system_prompt": "You are a legal communication specialist. Create a clear, "
|
||||
"concise executive summary of the contract analysis, highlighting "
|
||||
"key risks and recommendations. Your summary should be understandable "
|
||||
"to non-legal executives while maintaining accuracy.",
|
||||
"model_name": "gpt-4o",
|
||||
"role": "worker",
|
||||
"max_loops": 1
|
||||
}
|
||||
],
|
||||
"max_loops": 1,
|
||||
"swarm_type": "SequentialWorkflow",
|
||||
"task": "Analyze the attached software licensing agreement between TechCorp and ClientInc. "
|
||||
"Identify all key clauses, assess potential risks to ClientInc, suggest improvements "
|
||||
"to better protect ClientInc's interests, and create an executive summary of findings."
|
||||
}
|
||||
|
||||
# Execute the swarm
|
||||
result = run_swarm(swarm_config)
|
||||
|
||||
# Print formatted results
|
||||
print(json.dumps(result, indent=4))
|
||||
return result
|
||||
|
||||
if __name__ == "__main__":
|
||||
contract_analysis_system()
|
||||
```
|
||||
|
||||
#### Private Equity: Investment Opportunity Analysis
|
||||
|
||||
This example shows a swarm that performs comprehensive due diligence on potential investments:
|
||||
|
||||
```python
|
||||
# private_equity_example.py
|
||||
from swarms_client import run_swarm, schedule_swarm
|
||||
import json
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
def investment_opportunity_analysis():
|
||||
"""
|
||||
Create a swarm that performs comprehensive due diligence
|
||||
on potential private equity investment opportunities.
|
||||
"""
|
||||
swarm_config = {
|
||||
"name": "PE Investment Analyzer",
|
||||
"description": "Performs comprehensive analysis of private equity investment opportunities",
|
||||
"agents": [
|
||||
{
|
||||
"agent_name": "Financial Analyst",
|
||||
"description": "Analyzes financial statements and projections",
|
||||
"system_prompt": "You are a private equity financial analyst with expertise in "
|
||||
"evaluating company financials. Review the target company's financial "
|
||||
"statements, analyze growth trajectories, profit margins, cash flow patterns, "
|
||||
"and debt structure. Identify financial red flags and growth opportunities.",
|
||||
"model_name": "gpt-4o",
|
||||
"role": "worker",
|
||||
"max_loops": 1
|
||||
},
|
||||
{
|
||||
"agent_name": "Market Researcher",
|
||||
"description": "Assesses market conditions and competitive landscape",
|
||||
"system_prompt": "You are a market research specialist in the private equity sector. "
|
||||
"Analyze the target company's market position, industry trends, competitive "
|
||||
"landscape, and growth potential. Identify market-related risks and opportunities "
|
||||
"that could impact investment returns.",
|
||||
"model_name": "gpt-4o",
|
||||
"role": "worker",
|
||||
"max_loops": 1
|
||||
},
|
||||
{
|
||||
"agent_name": "Operational Due Diligence",
|
||||
"description": "Evaluates operational efficiency and improvement opportunities",
|
||||
"system_prompt": "You are an operational due diligence expert. Analyze the target "
|
||||
"company's operational structure, efficiency metrics, supply chain, "
|
||||
"technology infrastructure, and management capabilities. Identify "
|
||||
"operational improvement opportunities that could increase company value.",
|
||||
"model_name": "gpt-4o",
|
||||
"role": "worker",
|
||||
"max_loops": 1
|
||||
},
|
||||
{
|
||||
"agent_name": "Risk Assessor",
|
||||
"description": "Identifies regulatory, legal, and business risks",
|
||||
"system_prompt": "You are a risk assessment specialist in private equity. "
|
||||
"Evaluate potential regulatory challenges, legal liabilities, "
|
||||
"compliance issues, and business model vulnerabilities. Rate "
|
||||
"each risk based on likelihood and potential impact.",
|
||||
"model_name": "gpt-4o",
|
||||
"role": "worker",
|
||||
"max_loops": 1
|
||||
},
|
||||
{
|
||||
"agent_name": "Investment Thesis Creator",
|
||||
"description": "Synthesizes analysis into comprehensive investment thesis",
|
||||
"system_prompt": "You are a private equity investment strategist. Based on the "
|
||||
"analyses provided, develop a comprehensive investment thesis "
|
||||
"that includes valuation assessment, potential returns, value "
|
||||
"creation opportunities, exit strategies, and investment recommendations.",
|
||||
"model_name": "gpt-4o",
|
||||
"role": "worker",
|
||||
"max_loops": 1
|
||||
}
|
||||
],
|
||||
"max_loops": 1,
|
||||
"swarm_type": "SequentialWorkflow",
|
||||
"task": "Perform comprehensive due diligence on HealthTech Inc., a potential acquisition "
|
||||
"target in the healthcare technology sector. The company develops remote patient "
|
||||
"monitoring solutions and has shown 35% year-over-year growth for the past three years. "
|
||||
"Analyze financials, market position, operational structure, potential risks, and "
|
||||
"develop an investment thesis with a recommended valuation range."
|
||||
}
|
||||
|
||||
# Option 1: Execute the swarm immediately
|
||||
result = run_swarm(swarm_config)
|
||||
|
||||
# Option 2: Schedule the swarm for tomorrow morning
|
||||
tomorrow = (datetime.now() + timedelta(days=1)).replace(hour=8, minute=0, second=0).isoformat()
|
||||
# scheduled_result = schedule_swarm(swarm_config, tomorrow, "America/New_York")
|
||||
|
||||
# Print formatted results from immediate execution
|
||||
print(json.dumps(result, indent=4))
|
||||
return result
|
||||
|
||||
if __name__ == "__main__":
|
||||
investment_opportunity_analysis()
|
||||
```
|
||||
|
||||
|
||||
#### Education: Curriculum Development Assistant
|
||||
|
||||
This example shows how to use the Concurrent Workflow swarm type:
|
||||
|
||||
```python
|
||||
# education_example.py
|
||||
from swarms_client import run_swarm
|
||||
import json
|
||||
|
||||
def curriculum_development_assistant():
|
||||
"""
|
||||
Create a swarm that assists in developing educational curriculum
|
||||
with concurrent subject matter experts.
|
||||
"""
|
||||
swarm_config = {
|
||||
"name": "Curriculum Development Assistant",
|
||||
"description": "Develops comprehensive educational curriculum",
|
||||
"agents": [
|
||||
{
|
||||
"agent_name": "Subject Matter Expert",
|
||||
"description": "Provides domain expertise on the subject",
|
||||
"system_prompt": "You are a subject matter expert in data science. "
|
||||
"Your role is to identify the essential concepts, skills, "
|
||||
"and knowledge that students need to master in a comprehensive "
|
||||
"data science curriculum. Focus on both theoretical foundations "
|
||||
"and practical applications, ensuring the content reflects current "
|
||||
"industry standards and practices.",
|
||||
"model_name": "gpt-4o",
|
||||
"role": "worker",
|
||||
"max_loops": 1
|
||||
},
|
||||
{
|
||||
"agent_name": "Instructional Designer",
|
||||
"description": "Structures learning objectives and activities",
|
||||
"system_prompt": "You are an instructional designer specializing in technical education. "
|
||||
"Your task is to transform subject matter content into structured learning "
|
||||
"modules with clear objectives, engaging activities, and appropriate assessments. "
|
||||
"Design the learning experience to accommodate different learning styles and "
|
||||
"knowledge levels.",
|
||||
"model_name": "gpt-4o",
|
||||
"role": "worker",
|
||||
"max_loops": 1
|
||||
},
|
||||
{
|
||||
"agent_name": "Assessment Specialist",
|
||||
"description": "Develops evaluation methods and assessments",
|
||||
"system_prompt": "You are an educational assessment specialist. "
|
||||
"Design comprehensive assessment strategies to evaluate student "
|
||||
"learning throughout the curriculum. Create formative and summative "
|
||||
"assessments, rubrics, and feedback mechanisms that align with learning "
|
||||
"objectives and provide meaningful insights into student progress.",
|
||||
"model_name": "gpt-4o",
|
||||
"role": "worker",
|
||||
"max_loops": 1
|
||||
},
|
||||
{
|
||||
"agent_name": "Curriculum Integrator",
|
||||
"description": "Synthesizes input from all specialists into a cohesive curriculum",
|
||||
"system_prompt": "You are a curriculum development coordinator. "
|
||||
"Your role is to synthesize the input from subject matter experts, "
|
||||
"instructional designers, and assessment specialists into a cohesive, "
|
||||
"comprehensive curriculum. Ensure logical progression of topics, "
|
||||
"integration of theory and practice, and alignment between content, "
|
||||
"activities, and assessments.",
|
||||
"model_name": "gpt-4o",
|
||||
"role": "worker",
|
||||
"max_loops": 1
|
||||
}
|
||||
],
|
||||
"max_loops": 1,
|
||||
"swarm_type": "ConcurrentWorkflow", # Experts work simultaneously before integration
|
||||
"task": "Develop a comprehensive 12-week data science curriculum for advanced undergraduate "
|
||||
"students with programming experience. The curriculum should cover data analysis, "
|
||||
"machine learning, data visualization, and ethics in AI. Include weekly learning "
|
||||
"objectives, teaching materials, hands-on activities, and assessment methods. "
|
||||
"The curriculum should prepare students for entry-level data science positions."
|
||||
}
|
||||
|
||||
# Execute the swarm
|
||||
result = run_swarm(swarm_config)
|
||||
|
||||
# Print formatted results
|
||||
print(json.dumps(result, indent=4))
|
||||
return result
|
||||
|
||||
if __name__ == "__main__":
|
||||
curriculum_development_assistant()
|
||||
```
|
||||
|
||||
|
||||
### 5. Monitoring and Optimization
|
||||
|
||||
To optimize your swarm configurations and track usage patterns, you can retrieve and analyze logs:
|
||||
|
||||
```python
|
||||
# analytics_example.py
|
||||
from swarms_client import get_swarm_logs
|
||||
import json
|
||||
|
||||
def analyze_swarm_usage():
|
||||
"""
|
||||
Analyze swarm usage patterns to optimize configurations and costs.
|
||||
"""
|
||||
# Retrieve logs
|
||||
logs = get_swarm_logs()
|
||||
|
||||
return logs
|
||||
if __name__ == "__main__":
|
||||
analyze_swarm_usage()
|
||||
```
|
||||
|
||||
### 6. Next Steps
|
||||
|
||||
Once you've implemented and tested these examples, you can further optimize your swarm configurations by:
|
||||
|
||||
1. Experimenting with different swarm architectures for the same task to compare results
|
||||
2. Adjusting agent prompts to improve specialization and collaboration
|
||||
3. Fine-tuning model parameters like temperature and max_tokens
|
||||
4. Combining swarms into larger workflows through scheduled execution
|
||||
|
||||
The Swarms API's flexibility allows for continuous refinement of your AI orchestration strategies, enabling increasingly sophisticated solutions to complex problems.
|
||||
|
||||
## The Future of AI Agent Orchestration
|
||||
|
||||
The Swarms API represents a significant evolution in how we deploy AI for complex tasks. As we look to the future, several trends are emerging in the field of agent orchestration:
|
||||
|
||||
### Specialized Agent Ecosystems
|
||||
|
||||
We're moving toward rich ecosystems of highly specialized agents designed for specific tasks and domains. These specialized agents will have deep expertise in narrow areas, enabling more sophisticated collaboration when combined in swarms.
|
||||
|
||||
### Dynamic Swarm Formation
|
||||
|
||||
Future swarm platforms will likely feature even more advanced capabilities for dynamic swarm formation, where the system automatically determines not only which agents to include but also how they should collaborate based on real-time task analysis.
|
||||
|
||||
### Cross-Modal Collaboration
|
||||
|
||||
As AI capabilities expand across modalities (text, image, audio, video), we'll see increasing collaboration between agents specialized in different data types. This cross-modal collaboration will enable more comprehensive analysis and content creation spanning multiple formats.
|
||||
|
||||
### Human-Swarm Collaboration
|
||||
|
||||
The next frontier in agent orchestration will be seamless collaboration between human teams and AI swarms, where human specialists and AI agents work together, each contributing their unique strengths to complex problems.
|
||||
|
||||
### Continuous Learning Swarms
|
||||
|
||||
Future swarms will likely incorporate more sophisticated mechanisms for continuous improvement, with agent capabilities evolving based on past performance and feedback.
|
||||
|
||||
## Conclusion
|
||||
|
||||
The Swarms API represents a significant leap forward in AI orchestration, moving beyond the limitations of single-agent systems to unlock the power of collaborative intelligence. By enabling specialized agents to work together in coordinated swarms, this enterprise-grade platform opens new possibilities for solving complex problems across industries.
|
||||
|
||||
From financial analysis to healthcare research, legal services to software development, the applications for agent swarms are as diverse as they are powerful. The Swarms API provides the infrastructure, tools, and flexibility needed to deploy these collaborative AI systems at scale, with the security, reliability, and cost management features essential for enterprise adoption.
|
||||
|
||||
As we continue to push the boundaries of what AI can accomplish, the ability to orchestrate collaborative intelligence will become increasingly crucial. The Swarms API is at the forefront of this evolution, providing a glimpse into the future of AI—a future where the most powerful AI systems aren't individual models but coordinated teams of specialized agents working together to solve our most challenging problems.
|
||||
|
||||
For organizations looking to harness the full potential of AI, the Swarms API offers a compelling path forward—one that leverages the power of collaboration to achieve results beyond what any single AI agent could accomplish alone.
|
||||
|
||||
To explore the Swarms API and begin building your own intelligent agent swarms, visit [swarms.world](https://swarms.world) today.
|
||||
|
||||
---
|
||||
|
||||
## Resources
|
||||
|
||||
* Website: [swarms.ai](https://swarms.ai)
|
||||
* Marketplace: [swarms.world](https://swarms.world)
|
||||
* Cloud Platform: [cloud.swarms.ai](https://cloud.swarms.ai)
|
||||
* Documentation: [docs.swarms.world](https://docs.swarms.world/en/latest/swarms_cloud/swarms_api/)
|
@ -1,7 +1,7 @@
|
||||
from swarms.agents.agent_judge import AgentJudge
|
||||
|
||||
|
||||
judge = AgentJudge(model_name="gpt-4o", max_loops=1)
|
||||
judge = AgentJudge(model_name="gpt-4o-mini", max_loops=1)
|
||||
|
||||
|
||||
outputs = [
|
@ -0,0 +1,21 @@
|
||||
from swarms.agents.gkp_agent import GKPAgent
|
||||
|
||||
# Initialize the GKP Agent
|
||||
agent = GKPAgent(
|
||||
agent_name="gkp-agent",
|
||||
model_name="gpt-4o-mini", # Using OpenAI's model
|
||||
num_knowledge_items=6, # Generate 6 knowledge items per query
|
||||
)
|
||||
|
||||
# Example queries
|
||||
queries = [
|
||||
"What are the implications of quantum entanglement on information theory?",
|
||||
]
|
||||
|
||||
# Run the agent
|
||||
results = agent.run(queries)
|
||||
|
||||
# Print results
|
||||
for i, result in enumerate(results):
|
||||
print(f"\nQuery {i+1}: {queries[i]}")
|
||||
print(f"Answer: {result}")
|
@ -0,0 +1,148 @@
|
||||
from swarms.structs.agent import Agent
|
||||
from swarms.structs.dynamic_conversational_swarm import (
|
||||
DynamicConversationalSwarm,
|
||||
)
|
||||
|
||||
|
||||
tools = [
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "select_agent",
|
||||
"description": "Analyzes the input response and selects the most appropriate agent configuration, outputting both the agent name and the formatted response.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"respond_or_no_respond": {
|
||||
"type": "boolean",
|
||||
"description": "Whether the agent should respond to the response or not.",
|
||||
},
|
||||
"reasoning": {
|
||||
"type": "string",
|
||||
"description": "The reasoning behind the selection of the agent and response.",
|
||||
},
|
||||
"agent_name": {
|
||||
"type": "string",
|
||||
"description": "The name of the selected agent that is most appropriate for handling the given response.",
|
||||
},
|
||||
"response": {
|
||||
"type": "string",
|
||||
"description": "A clear and structured description of the response for the next agent.",
|
||||
},
|
||||
},
|
||||
"required": [
|
||||
"reasoning",
|
||||
"agent_name",
|
||||
"response",
|
||||
"respond_or_no_respond",
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
# Create our philosophical agents with personalities
|
||||
sophie = Agent(
|
||||
agent_name="Sophie de Beauvoir",
|
||||
agent_description="""A witty French café philosopher who loves espresso and deep conversations.
|
||||
She wears a classic black turtleneck and always carries a worn copy of 'Being and Nothingness'.
|
||||
Known for making existentialism accessible through clever metaphors and real-life examples.""",
|
||||
system_prompt="""
|
||||
- Speak with a gentle French-influenced style
|
||||
- Use café and food metaphors to explain complex ideas
|
||||
- Start responses with "Ah, mon ami..."
|
||||
- Share existentialist wisdom with warmth and humor
|
||||
- Reference personal (fictional) experiences in Parisian cafés
|
||||
- Challenge others to find their authentic path
|
||||
""",
|
||||
tools_list_dictionary=tools,
|
||||
)
|
||||
|
||||
joy = Agent(
|
||||
agent_name="Joy 'Sunshine' Martinez",
|
||||
agent_description="""A former tech executive turned happiness researcher who found her calling
|
||||
after a transformative year backpacking around the world. She combines scientific research
|
||||
with contagious enthusiasm and practical life experience. Always starts meetings with a
|
||||
meditation bell.""",
|
||||
system_prompt="""
|
||||
- Maintain an energetic, encouraging tone
|
||||
- Share personal (fictional) travel stories
|
||||
- Include small mindfulness exercises in responses
|
||||
- Use emoji occasionally for emphasis
|
||||
- Balance optimism with practical advice
|
||||
- End messages with an inspirational micro-challenge
|
||||
""",
|
||||
model_name="gpt-4o-mini",
|
||||
tools_list_dictionary=tools,
|
||||
)
|
||||
|
||||
zhen = Agent(
|
||||
agent_name="Master Zhen",
|
||||
agent_description="""A modern spiritual teacher who blends ancient wisdom with contemporary life.
|
||||
Former quantum physicist who now runs a mountain retreat center. Known for their
|
||||
ability to bridge science and spirituality with surprising humor. Loves making tea
|
||||
during philosophical discussions.""",
|
||||
system_prompt="""
|
||||
- Speak with calm wisdom and occasional playfulness
|
||||
- Include tea ceremonies and nature metaphors
|
||||
- Share brief zen-like stories and koans
|
||||
- Reference both quantum physics and ancient wisdom
|
||||
- Ask thought-provoking questions
|
||||
- Sometimes answer questions with questions
|
||||
""",
|
||||
model_name="gpt-4o-mini",
|
||||
tools_list_dictionary=tools,
|
||||
)
|
||||
|
||||
nova = Agent(
|
||||
agent_name="Dr. Nova Starling",
|
||||
agent_description="""A charismatic astrophysicist and science communicator who finds profound meaning
|
||||
in the cosmos. Hosts a popular science podcast called 'Cosmic Meaning'. Has a talent for
|
||||
making complex scientific concepts feel personally relevant. Always carries a mini telescope.""",
|
||||
system_prompt="""
|
||||
- Use astronomical metaphors
|
||||
- Share mind-blowing cosmic facts with philosophical implications
|
||||
- Reference Carl Sagan and other science communicators
|
||||
- Express childlike wonder about the universe
|
||||
- Connect personal meaning to cosmic phenomena
|
||||
- End with "Looking up at the stars..."
|
||||
""",
|
||||
model_name="gpt-4o-mini",
|
||||
tools_list_dictionary=tools,
|
||||
)
|
||||
|
||||
sam = Agent(
|
||||
agent_name="Sam 'The Barista Philosopher' Chen",
|
||||
agent_description="""A neighborhood coffee shop owner who studied philosophy at university.
|
||||
Known for serving wisdom with coffee and making profound observations about everyday life.
|
||||
Keeps a journal of customer conversations and insights. Has a talent for finding
|
||||
extraordinary meaning in ordinary moments.""",
|
||||
system_prompt="""
|
||||
- Speak in a warm, friendly manner
|
||||
- Use coffee-making metaphors
|
||||
- Share observations from daily life
|
||||
- Reference conversations with customers
|
||||
- Ground philosophical concepts in everyday experiences
|
||||
- End with practical "food for thought"
|
||||
""",
|
||||
model_name="gpt-4o-mini",
|
||||
tools_list_dictionary=tools,
|
||||
)
|
||||
|
||||
# Create the swarm with our personalized agents
|
||||
meaning_swarm = DynamicConversationalSwarm(
|
||||
name="The Cosmic Café Collective",
|
||||
description="""A diverse group of wisdom-seekers who gather in an imaginary café at the
|
||||
edge of the universe. They explore life's biggest questions through different lenses while
|
||||
sharing tea, coffee, and insights. Together, they help others find their own path to meaning.""",
|
||||
agents=[sophie, joy, zhen, nova, sam],
|
||||
max_loops=2,
|
||||
output_type="list",
|
||||
)
|
||||
|
||||
# Example usage
|
||||
if __name__ == "__main__":
|
||||
question = "What gives life its deepest meaning?"
|
||||
response = meaning_swarm.run(question)
|
||||
print(response)
|
@ -0,0 +1,51 @@
|
||||
from swarms import Agent
|
||||
from swarms.prompts.finance_agent_sys_prompt import (
|
||||
FINANCIAL_AGENT_SYS_PROMPT,
|
||||
)
|
||||
|
||||
tools = [
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "get_stock_price",
|
||||
"description": "Retrieve the current stock price and related information for a specified company.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"ticker": {
|
||||
"type": "string",
|
||||
"description": "The stock ticker symbol of the company, e.g. AAPL for Apple Inc.",
|
||||
},
|
||||
"include_history": {
|
||||
"type": "boolean",
|
||||
"description": "Indicates whether to include historical price data along with the current price.",
|
||||
},
|
||||
"time": {
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"description": "Optional parameter to specify the time for which the stock data is requested, in ISO 8601 format.",
|
||||
},
|
||||
},
|
||||
"required": [
|
||||
"ticker",
|
||||
"include_history",
|
||||
"time",
|
||||
],
|
||||
},
|
||||
},
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
# 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,
|
||||
tools_list_dictionary=tools,
|
||||
)
|
||||
|
||||
agent.run(
|
||||
"What is the current stock price for Apple Inc. (AAPL)? Include historical price data.",
|
||||
)
|
@ -0,0 +1,65 @@
|
||||
from dotenv import load_dotenv
|
||||
import os
|
||||
|
||||
from swarms.structs.agent import Agent
|
||||
from swarms.structs.groupchat import GroupChat
|
||||
from swarms.prompts.multi_agent_collab_prompt import (
|
||||
MULTI_AGENT_COLLAB_PROMPT_TWO,
|
||||
)
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
load_dotenv()
|
||||
|
||||
# Get the OpenAI API key from the environment variable
|
||||
api_key = os.getenv("OPENAI_API_KEY")
|
||||
|
||||
# Example agents
|
||||
agent1 = Agent(
|
||||
agent_name="Financial-Analysis-Agent",
|
||||
description="You are a financial analyst specializing in investment strategies.",
|
||||
model_name="gpt-4o-mini",
|
||||
max_loops=1,
|
||||
autosave=False,
|
||||
dashboard=False,
|
||||
verbose=True,
|
||||
dynamic_temperature_enabled=True,
|
||||
user_name="swarms_corp",
|
||||
retry_attempts=1,
|
||||
context_length=200000,
|
||||
output_type="string",
|
||||
streaming_on=False,
|
||||
max_tokens=15000,
|
||||
)
|
||||
|
||||
agent2 = Agent(
|
||||
agent_name="Tax-Adviser-Agent",
|
||||
description="You are a tax adviser who provides clear and concise guidance on tax-related queries.",
|
||||
model_name="gpt-4o-mini",
|
||||
max_loops=1,
|
||||
autosave=False,
|
||||
dashboard=False,
|
||||
verbose=True,
|
||||
dynamic_temperature_enabled=True,
|
||||
user_name="swarms_corp",
|
||||
retry_attempts=1,
|
||||
context_length=200000,
|
||||
output_type="string",
|
||||
streaming_on=False,
|
||||
max_tokens=15000,
|
||||
)
|
||||
|
||||
agents = [agent1, agent2]
|
||||
|
||||
chat = GroupChat(
|
||||
name="Investment Advisory",
|
||||
description="Financial and tax analysis group",
|
||||
agents=agents,
|
||||
max_loops=1,
|
||||
output_type="all",
|
||||
)
|
||||
|
||||
history = chat.run(
|
||||
"What are the best Japanese business methodologies to take over a market say like minerals and mining?. I need a 4,000 word report. Work together to write the report."
|
||||
)
|
||||
# print(history)
|
@ -0,0 +1,36 @@
|
||||
from swarms import Agent, SequentialWorkflow
|
||||
|
||||
|
||||
# Core Legal Agent Definitions with enhanced system prompts
|
||||
litigation_agent = Agent(
|
||||
agent_name="Alex Johnson", # Human name for the Litigator Agent
|
||||
system_prompt="As a Litigator, you specialize in navigating the complexities of lawsuits. Your role involves analyzing intricate facts, constructing compelling arguments, and devising effective case strategies to achieve favorable outcomes for your clients.",
|
||||
model_name="gpt-4o-mini",
|
||||
auto_generate_prompt=False,
|
||||
max_loops=1,
|
||||
)
|
||||
|
||||
corporate_agent = Agent(
|
||||
agent_name="Emily Carter", # Human name for the Corporate Attorney Agent
|
||||
system_prompt="As a Corporate Attorney, you provide expert legal advice on business law matters. You guide clients on corporate structure, governance, compliance, and transactions, ensuring their business operations align with legal requirements.",
|
||||
model_name="gpt-4o-mini",
|
||||
auto_generate_prompt=False,
|
||||
max_loops=1,
|
||||
)
|
||||
|
||||
ip_agent = Agent(
|
||||
agent_name="Michael Smith", # Human name for the IP Attorney Agent
|
||||
system_prompt="As an IP Attorney, your expertise lies in protecting intellectual property rights. You handle various aspects of IP law, including patents, trademarks, copyrights, and trade secrets, helping clients safeguard their innovations.",
|
||||
model_name="gpt-4o-mini",
|
||||
auto_generate_prompt=False,
|
||||
max_loops=1,
|
||||
)
|
||||
|
||||
|
||||
swarm = SequentialWorkflow(
|
||||
agents=[litigation_agent, corporate_agent, ip_agent],
|
||||
name="litigation-practice",
|
||||
description="Handle all aspects of litigation with a focus on thorough legal analysis and effective case management.",
|
||||
)
|
||||
|
||||
swarm.run("What are your names?")
|
@ -0,0 +1,15 @@
|
||||
from swarms.client.main import (
|
||||
SwarmsAPIClient,
|
||||
AgentInput,
|
||||
SwarmRequest,
|
||||
SwarmAPIError,
|
||||
SwarmAuthenticationError,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"SwarmsAPIClient",
|
||||
"AgentInput",
|
||||
"SwarmRequest",
|
||||
"SwarmAPIError",
|
||||
"SwarmAuthenticationError",
|
||||
]
|
@ -0,0 +1,226 @@
|
||||
import json
|
||||
import random
|
||||
from swarms.structs.agent import Agent
|
||||
from typing import List
|
||||
from swarms.structs.conversation import Conversation
|
||||
from swarms.utils.history_output_formatter import (
|
||||
history_output_formatter,
|
||||
)
|
||||
from swarms.utils.any_to_str import any_to_str
|
||||
|
||||
tools = [
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "select_agent",
|
||||
"description": "Analyzes the input task and selects the most appropriate agent configuration, outputting both the agent name and the formatted response.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"respond_or_no_respond": {
|
||||
"type": "boolean",
|
||||
"description": "Whether the agent should respond to the response or not.",
|
||||
},
|
||||
"reasoning": {
|
||||
"type": "string",
|
||||
"description": "The reasoning behind the selection of the agent and response.",
|
||||
},
|
||||
"agent_name": {
|
||||
"type": "string",
|
||||
"description": "The name of the selected agent that is most appropriate for handling the given task.",
|
||||
},
|
||||
"response": {
|
||||
"type": "string",
|
||||
"description": "A clear and structured description of the response for the next agent.",
|
||||
},
|
||||
},
|
||||
"required": [
|
||||
"reasoning",
|
||||
"agent_name",
|
||||
"response",
|
||||
"respond_or_no_respond",
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
class DynamicConversationalSwarm:
|
||||
def __init__(
|
||||
self,
|
||||
name: str = "Dynamic Conversational Swarm",
|
||||
description: str = "A swarm that uses a dynamic conversational model to solve complex tasks.",
|
||||
agents: List[Agent] = [],
|
||||
max_loops: int = 1,
|
||||
output_type: str = "list",
|
||||
*args,
|
||||
**kwargs,
|
||||
):
|
||||
self.name = name
|
||||
self.description = description
|
||||
self.agents = agents
|
||||
self.max_loops = max_loops
|
||||
self.output_type = output_type
|
||||
|
||||
self.conversation = Conversation()
|
||||
|
||||
# Agents in the chat
|
||||
agents_in_chat = self.get_agents_info()
|
||||
self.conversation.add(
|
||||
role="Conversation Log", content=agents_in_chat
|
||||
)
|
||||
|
||||
self.inject_tools()
|
||||
|
||||
# Inject tools into the agents
|
||||
def inject_tools(self):
|
||||
for agent in self.agents:
|
||||
agent.tools_list_dictionary = tools
|
||||
|
||||
def parse_json_into_dict(self, json_str: str) -> dict:
|
||||
try:
|
||||
return json.loads(json_str)
|
||||
except json.JSONDecodeError:
|
||||
raise ValueError("Invalid JSON string")
|
||||
|
||||
def find_agent_by_name(self, agent_name: str) -> Agent:
|
||||
for agent in self.agents:
|
||||
if agent.name == agent_name:
|
||||
return agent
|
||||
raise ValueError(f"Agent with name {agent_name} not found")
|
||||
|
||||
def run_agent(self, agent_name: str, task: str) -> str:
|
||||
agent = self.find_agent_by_name(agent_name)
|
||||
return agent.run(task)
|
||||
|
||||
def fetch_random_agent_name(self) -> str:
|
||||
return random.choice(self.agents).agent_name
|
||||
|
||||
def run(self, task: str) -> str:
|
||||
"""
|
||||
Run the dynamic conversational swarm for a specified number of loops.
|
||||
Each agent has access to the full conversation history.
|
||||
|
||||
Args:
|
||||
task (str): The initial task/prompt to process
|
||||
|
||||
Returns:
|
||||
str: The final response after all loops are complete
|
||||
"""
|
||||
self.conversation.add(
|
||||
role=f"{self.fetch_random_agent_name()}", content=task
|
||||
)
|
||||
|
||||
# for loop in range(self.max_loops):
|
||||
# # Add loop marker to conversation for clarity
|
||||
# self.conversation.add(
|
||||
# role="System",
|
||||
# content=f"=== Starting Loop {loop + 1}/{self.max_loops} ==="
|
||||
# )
|
||||
|
||||
# # First agent interaction
|
||||
# current_agent = self.randomly_select_agent()
|
||||
# response = self.run_agent(current_agent.name, self.conversation.get_str())
|
||||
# self.conversation.add(role=current_agent.name, content=any_to_str(response))
|
||||
|
||||
# try:
|
||||
# # Parse response and get next agent
|
||||
# response_dict = self.parse_json_into_dict(response)
|
||||
|
||||
# # Check if we should continue or end the loop
|
||||
# if not response_dict.get("respond_or_no_respond", True):
|
||||
# break
|
||||
|
||||
# # Get the task description for the next agent
|
||||
# next_task = response_dict.get("task_description", self.conversation.get_str())
|
||||
|
||||
# # Run the next agent with the specific task description
|
||||
# next_agent = self.find_agent_by_name(response_dict["agent_name"])
|
||||
# next_response = self.run_agent(next_agent.name, next_task)
|
||||
|
||||
# # Add both the task description and response to the conversation
|
||||
# self.conversation.add(
|
||||
# role="System",
|
||||
# content=f"Response from {response_dict['agent_name']}: {next_task}"
|
||||
# )
|
||||
# self.conversation.add(role=next_agent.name, content=any_to_str(next_response))
|
||||
|
||||
# except (ValueError, KeyError) as e:
|
||||
# self.conversation.add(
|
||||
# role="System",
|
||||
# content=f"Error in loop {loop + 1}: {str(e)}"
|
||||
# )
|
||||
# break
|
||||
|
||||
# Run first agent
|
||||
current_agent = self.randomly_select_agent()
|
||||
response = self.run_agent(
|
||||
current_agent.agent_name, self.conversation.get_str()
|
||||
)
|
||||
self.conversation.add(
|
||||
role=current_agent.agent_name,
|
||||
content=any_to_str(response),
|
||||
)
|
||||
|
||||
# Convert to json
|
||||
response_dict = self.parse_json_into_dict(response)
|
||||
|
||||
# Fetch task
|
||||
respone_two = response_dict["response"]
|
||||
agent_name = response_dict["agent_name"]
|
||||
|
||||
print(f"Response from {agent_name}: {respone_two}")
|
||||
|
||||
# Run next agent
|
||||
next_response = self.run_agent(
|
||||
agent_name, self.conversation.get_str()
|
||||
)
|
||||
self.conversation.add(
|
||||
role=agent_name, content=any_to_str(next_response)
|
||||
)
|
||||
|
||||
# # Get the next agent
|
||||
# response_three = self.parse_json_into_dict(next_response)
|
||||
# agent_name_three = response_three["agent_name"]
|
||||
# respone_four = response_three["response"]
|
||||
|
||||
# print(f"Response from {agent_name_three}: {respone_four}")
|
||||
# # Run the next agent
|
||||
# next_response = self.run_agent(agent_name_three, self.conversation.get_str())
|
||||
# self.conversation.add(role=agent_name_three, content=any_to_str(next_response))
|
||||
|
||||
# Format and return the final conversation history
|
||||
return history_output_formatter(
|
||||
self.conversation, type=self.output_type
|
||||
)
|
||||
|
||||
def randomly_select_agent(self) -> Agent:
|
||||
return random.choice(self.agents)
|
||||
|
||||
def get_agents_info(self) -> str:
|
||||
"""
|
||||
Fetches and formats information about all available agents in the system.
|
||||
|
||||
Returns:
|
||||
str: A formatted string containing names and descriptions of all agents.
|
||||
"""
|
||||
if not self.agents:
|
||||
return "No agents currently available in the system."
|
||||
|
||||
agents_info = [
|
||||
"Agents In the System:",
|
||||
"",
|
||||
] # Empty string for line spacing
|
||||
|
||||
for idx, agent in enumerate(self.agents, 1):
|
||||
agents_info.extend(
|
||||
[
|
||||
f"[Agent {idx}]",
|
||||
f"Name: {agent.name}",
|
||||
f"Description: {agent.description}",
|
||||
"", # Empty string for line spacing between agents
|
||||
]
|
||||
)
|
||||
|
||||
return "\n".join(agents_info).strip()
|
@ -1,59 +1,40 @@
|
||||
import os
|
||||
import logging
|
||||
import warnings
|
||||
import concurrent.futures
|
||||
from dotenv import load_dotenv
|
||||
from loguru import logger
|
||||
from pathlib import Path
|
||||
from swarms.utils.disable_logging import disable_logging
|
||||
from loguru import logger
|
||||
|
||||
|
||||
def bootup():
|
||||
"""Initialize swarms environment and configuration
|
||||
|
||||
Handles environment setup, logging configuration, telemetry,
|
||||
and workspace initialization.
|
||||
"""
|
||||
"""Super-fast initialization of swarms environment"""
|
||||
try:
|
||||
# Load environment variables
|
||||
load_dotenv()
|
||||
|
||||
# Configure logging
|
||||
if (
|
||||
os.getenv("SWARMS_VERBOSE_GLOBAL", "False").lower()
|
||||
== "false"
|
||||
):
|
||||
logger.disable("")
|
||||
logging.disable(logging.CRITICAL)
|
||||
# Cache env vars
|
||||
verbose = os.getenv("SWARMS_VERBOSE_GLOBAL", "False").lower()
|
||||
workspace_path = Path.cwd() / "agent_workspace"
|
||||
|
||||
# Configure logging early
|
||||
if verbose == "false":
|
||||
logger.disable("CRITICAL")
|
||||
else:
|
||||
logger.enable("")
|
||||
|
||||
# Silent wandb
|
||||
# Silence wandb
|
||||
os.environ["WANDB_SILENT"] = "true"
|
||||
|
||||
# Configure workspace
|
||||
workspace_dir = os.path.join(os.getcwd(), "agent_workspace")
|
||||
os.makedirs(workspace_dir, exist_ok=True)
|
||||
os.environ["WORKSPACE_DIR"] = workspace_dir
|
||||
# Setup workspace dir only if needed
|
||||
if not workspace_path.exists():
|
||||
workspace_path.mkdir(parents=True, exist_ok=True)
|
||||
os.environ["WORKSPACE_DIR"] = str(workspace_path)
|
||||
|
||||
# Suppress warnings
|
||||
# Suppress deprecation warnings
|
||||
warnings.filterwarnings("ignore", category=DeprecationWarning)
|
||||
|
||||
# Run telemetry functions concurrently
|
||||
# Run lightweight telemetry
|
||||
try:
|
||||
with concurrent.futures.ThreadPoolExecutor(
|
||||
max_workers=2
|
||||
) as executor:
|
||||
|
||||
future_disable_logging = executor.submit(
|
||||
disable_logging
|
||||
)
|
||||
|
||||
# Wait for completion and check for exceptions
|
||||
future_disable_logging.result()
|
||||
disable_logging()
|
||||
except Exception as e:
|
||||
logger.error(f"Error running telemetry functions: {e}")
|
||||
logger.error(f"Telemetry error: {e}")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error during bootup: {str(e)}")
|
||||
logger.error(f"Bootup error: {str(e)}")
|
||||
raise
|
||||
|
@ -1,26 +0,0 @@
|
||||
from swarms.utils.loguru_logger import logger
|
||||
import os
|
||||
|
||||
|
||||
def try_import_agentops(*args, **kwargs):
|
||||
try:
|
||||
logger.info("Trying to import agentops")
|
||||
import agentops
|
||||
|
||||
agentops.init(os.getenv("AGENTOPS_API_KEY"), *args, **kwargs)
|
||||
|
||||
return "agentops imported successfully."
|
||||
except ImportError:
|
||||
logger.error("Could not import agentops")
|
||||
|
||||
|
||||
def end_session_agentops():
|
||||
try:
|
||||
logger.info("Trying to end session")
|
||||
import agentops
|
||||
|
||||
agentops.end_session("Success")
|
||||
return "Session ended successfully."
|
||||
except ImportError:
|
||||
logger.error("Could not import agentops")
|
||||
return "Could not end session."
|
@ -1,92 +0,0 @@
|
||||
import subprocess
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from swarms.utils.loguru_logger import initialize_logger
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from swarms.structs.agent import Agent
|
||||
|
||||
logger = initialize_logger(log_folder="pandas_utils")
|
||||
|
||||
|
||||
def display_agents_info(agents: List[Agent]) -> None:
|
||||
"""
|
||||
Displays information about all agents in a list using a DataFrame.
|
||||
|
||||
:param agents: List of Agent instances.
|
||||
"""
|
||||
# Extracting relevant information from each agent
|
||||
|
||||
try:
|
||||
import pandas as pd
|
||||
except ImportError:
|
||||
logger.error("Failed to import pandas")
|
||||
subprocess.run(["pip", "install", "pandas"])
|
||||
import pandas as pd
|
||||
|
||||
agent_data = []
|
||||
for agent in agents:
|
||||
try:
|
||||
agent_info = {
|
||||
"ID": agent.id,
|
||||
"Name": agent.agent_name,
|
||||
"Description": agent.description,
|
||||
"max_loops": agent.max_loops,
|
||||
# "Docs": agent.docs,
|
||||
"System Prompt": agent.system_prompt,
|
||||
"LLM Model": agent.llm.model_name, # type: ignore
|
||||
}
|
||||
agent_data.append(agent_info)
|
||||
except AttributeError as e:
|
||||
logger.error(
|
||||
f"Failed to extract information from agent {agent}: {e}"
|
||||
)
|
||||
continue
|
||||
|
||||
# Creating a DataFrame to display the data
|
||||
try:
|
||||
df = pd.DataFrame(agent_data)
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to create DataFrame: {e}")
|
||||
return
|
||||
|
||||
# Displaying the DataFrame
|
||||
try:
|
||||
print(df)
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to print DataFrame: {e}")
|
||||
|
||||
|
||||
def dict_to_dataframe(data: Dict[str, Any]):
|
||||
"""
|
||||
Converts a dictionary into a pandas DataFrame.
|
||||
|
||||
:param data: Dictionary to convert.
|
||||
:return: A pandas DataFrame representation of the dictionary.
|
||||
"""
|
||||
try:
|
||||
import pandas as pd
|
||||
except ImportError:
|
||||
logger.error("Failed to import pandas")
|
||||
subprocess.run(["pip", "install", "pandas"])
|
||||
import pandas as pd
|
||||
|
||||
# Convert dictionary to DataFrame
|
||||
df = pd.json_normalize(data)
|
||||
return df
|
||||
|
||||
|
||||
def pydantic_model_to_dataframe(model: BaseModel) -> any:
|
||||
"""
|
||||
Converts a Pydantic Base Model into a pandas DataFrame.
|
||||
|
||||
:param model: Pydantic Base Model to convert.
|
||||
:return: A pandas DataFrame representation of the Pydantic model.
|
||||
"""
|
||||
# Convert Pydantic model to dictionary
|
||||
model_dict = model.dict()
|
||||
|
||||
# Convert dictionary to DataFrame
|
||||
df = dict_to_dataframe(model_dict)
|
||||
return df
|
@ -0,0 +1,43 @@
|
||||
import asyncio
|
||||
|
||||
from browser_use import Agent
|
||||
from dotenv import load_dotenv
|
||||
from langchain_openai import ChatOpenAI
|
||||
|
||||
from swarms import ConcurrentWorkflow
|
||||
|
||||
load_dotenv()
|
||||
|
||||
|
||||
class BrowserAgent:
|
||||
def __init__(self, agent_name: str = "BrowserAgent"):
|
||||
self.agent_name = agent_name
|
||||
|
||||
async def browser_agent_test(self, task: str):
|
||||
agent = Agent(
|
||||
task=task,
|
||||
llm=ChatOpenAI(model="gpt-4o"),
|
||||
)
|
||||
result = await agent.run()
|
||||
return result
|
||||
|
||||
def run(self, task: str):
|
||||
return asyncio.run(self.browser_agent_test(task))
|
||||
|
||||
|
||||
swarm = ConcurrentWorkflow(
|
||||
agents=[BrowserAgent() for _ in range(3)],
|
||||
)
|
||||
|
||||
swarm.run(
|
||||
"""
|
||||
Go to pump.fun.
|
||||
|
||||
2. Make an account: use email: "test@test.com" and password: "test1234"
|
||||
|
||||
3. Make a coin called and give it a cool description and etc. Fill in the form
|
||||
|
||||
4. Sit back and watch the coin grow in value.
|
||||
|
||||
"""
|
||||
)
|
Loading…
Reference in new issue