commit
5a054b0781
@ -0,0 +1,188 @@
|
||||
# Agent Output Types Examples
|
||||
|
||||
This example demonstrates how to use different output types when working with Swarms agents. Each output type formats the agent's response in a specific way, making it easier to integrate with different parts of your application.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Python 3.7+
|
||||
- OpenAI API key
|
||||
- Swarms library
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
pip3 install -U swarms
|
||||
```
|
||||
|
||||
## Environment Variables
|
||||
|
||||
```plaintext
|
||||
WORKSPACE_DIR="agent_workspace"
|
||||
OPENAI_API_KEY=""
|
||||
ANTHROPIC_API_KEY=""
|
||||
```
|
||||
|
||||
## Available Output Types
|
||||
|
||||
The following output types are supported:
|
||||
|
||||
| Output Type | Description |
|
||||
|------------|-------------|
|
||||
| `"list"` | Returns response as a JSON string containing a list |
|
||||
| `"dict"` or `"dictionary"` | Returns response as a Python dictionary |
|
||||
| `"string"` or `"str"` | Returns response as a plain string |
|
||||
| `"final"` or `"last"` | Returns only the final response |
|
||||
| `"json"` | Returns response as a JSON string |
|
||||
| `"all"` | Returns all responses in the conversation |
|
||||
| `"yaml"` | Returns response formatted as YAML |
|
||||
| `"xml"` | Returns response formatted as XML |
|
||||
| `"dict-all-except-first"` | Returns all responses except the first as a dictionary |
|
||||
| `"str-all-except-first"` | Returns all responses except the first as a string |
|
||||
| `"basemodel"` | Returns response as a Pydantic BaseModel |
|
||||
|
||||
## Examples
|
||||
|
||||
### 1. String Output (Default)
|
||||
|
||||
```python
|
||||
from swarms import Agent
|
||||
|
||||
# Initialize agent with string output
|
||||
agent = Agent(
|
||||
agent_name="String-Output-Agent",
|
||||
agent_description="Demonstrates string output format",
|
||||
system_prompt="You are a helpful assistant that provides clear text responses.",
|
||||
output_type="str", # or "string"
|
||||
)
|
||||
|
||||
response = agent.run("What is the capital of France?")
|
||||
|
||||
```
|
||||
|
||||
### 2. JSON Output
|
||||
|
||||
```python
|
||||
# Initialize agent with JSON output
|
||||
agent = Agent(
|
||||
agent_name="JSON-Output-Agent",
|
||||
agent_description="Demonstrates JSON output format",
|
||||
system_prompt="You are an assistant that provides structured data responses.",
|
||||
output_type="json"
|
||||
)
|
||||
|
||||
response = agent.run("List the top 3 programming languages.")
|
||||
|
||||
```
|
||||
|
||||
### 3. List Output
|
||||
|
||||
```python
|
||||
# Initialize agent with list output
|
||||
agent = Agent(
|
||||
agent_name="List-Output-Agent",
|
||||
agent_description="Demonstrates list output format",
|
||||
system_prompt="You are an assistant that provides list-based responses.",
|
||||
output_type="list"
|
||||
)
|
||||
|
||||
response = agent.run("Name three primary colors.")
|
||||
|
||||
```
|
||||
|
||||
### 4. Dictionary Output
|
||||
|
||||
```python
|
||||
# Initialize agent with dictionary output
|
||||
agent = Agent(
|
||||
agent_name="Dict-Output-Agent",
|
||||
agent_description="Demonstrates dictionary output format",
|
||||
system_prompt="You are an assistant that provides dictionary-based responses.",
|
||||
output_type="dict" # or "dictionary"
|
||||
)
|
||||
|
||||
response = agent.run("Provide information about a book.")
|
||||
|
||||
```
|
||||
|
||||
### 5. YAML Output
|
||||
|
||||
```python
|
||||
# Initialize agent with YAML output
|
||||
agent = Agent(
|
||||
agent_name="YAML-Output-Agent",
|
||||
agent_description="Demonstrates YAML output format",
|
||||
system_prompt="You are an assistant that provides YAML-formatted responses.",
|
||||
output_type="yaml"
|
||||
)
|
||||
|
||||
response = agent.run("Describe a recipe.")
|
||||
```
|
||||
|
||||
### 6. XML Output
|
||||
|
||||
```python
|
||||
# Initialize agent with XML output
|
||||
agent = Agent(
|
||||
agent_name="XML-Output-Agent",
|
||||
agent_description="Demonstrates XML output format",
|
||||
system_prompt="You are an assistant that provides XML-formatted responses.",
|
||||
output_type="xml"
|
||||
)
|
||||
|
||||
response = agent.run("Provide user information.")
|
||||
```
|
||||
|
||||
### 7. All Responses
|
||||
|
||||
```python
|
||||
# Initialize agent to get all responses
|
||||
agent = Agent(
|
||||
agent_name="All-Output-Agent",
|
||||
agent_description="Demonstrates getting all responses",
|
||||
system_prompt="You are an assistant that provides multiple responses.",
|
||||
output_type="all"
|
||||
)
|
||||
|
||||
response = agent.run("Tell me about climate change.")
|
||||
```
|
||||
|
||||
### 8. Final Response Only
|
||||
|
||||
```python
|
||||
# Initialize agent to get only final response
|
||||
agent = Agent(
|
||||
agent_name="Final-Output-Agent",
|
||||
agent_description="Demonstrates getting only final response",
|
||||
system_prompt="You are an assistant that provides concise final answers.",
|
||||
output_type="final" # or "last"
|
||||
)
|
||||
|
||||
response = agent.run("What's the meaning of life?")
|
||||
```
|
||||
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. Choose the output type based on your application's needs:
|
||||
|
||||
| Output Type | Use Case |
|
||||
|------------|----------|
|
||||
| `"str"` | Simple text responses |
|
||||
| `"json"` or `"dict"` | Structured data |
|
||||
| `"list"` | Array-like data |
|
||||
| `"yaml"` | Configuration-like data |
|
||||
| `"xml"` | XML-based integrations |
|
||||
| `"basemodel"` | Type-safe data handling |
|
||||
|
||||
2. Handle the output appropriately in your application:
|
||||
|
||||
- Parse JSON/YAML responses when needed
|
||||
|
||||
- Validate structured data
|
||||
|
||||
- Handle potential formatting errors
|
||||
|
||||
3. Consider using `try-except` blocks when working with structured output types to handle potential parsing errors.
|
||||
|
||||
|
||||
This comprehensive guide shows how to use all available output types in the Swarms framework, making it easier to integrate agent responses into your applications in the most suitable format for your needs.
|
@ -0,0 +1,199 @@
|
||||
# Agent Structured Outputs
|
||||
|
||||
This example demonstrates how to use structured outputs with Swarms agents following OpenAI's function calling schema. By defining function schemas, you can specify exactly how agents should structure their responses, making it easier to parse and use the outputs in your applications.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Python 3.7+
|
||||
- OpenAI API key
|
||||
- Swarms library
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
pip3 install -U swarms
|
||||
```
|
||||
|
||||
## Environment Variables
|
||||
|
||||
```plaintext
|
||||
WORKSPACE_DIR="agent_workspace"
|
||||
OPENAI_API_KEY=""
|
||||
ANTHROPIC_API_KEY=""
|
||||
```
|
||||
|
||||
## Understanding Function Schemas
|
||||
|
||||
Function schemas in Swarms follow OpenAI's function calling format. Each function schema is defined as a dictionary with the following structure:
|
||||
|
||||
```python
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "function_name",
|
||||
"description": "A clear description of what the function does",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
# Define the parameters your function accepts
|
||||
},
|
||||
"required": ["list", "of", "required", "parameters"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Code Example
|
||||
|
||||
Here's an example showing how to use multiple function schemas with a Swarms agent:
|
||||
|
||||
```python
|
||||
from swarms import Agent
|
||||
from swarms.prompts.finance_agent_sys_prompt import FINANCIAL_AGENT_SYS_PROMPT
|
||||
|
||||
# Define multiple function schemas
|
||||
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": "Whether to include historical price data.",
|
||||
},
|
||||
"time": {
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"description": "Optional time for stock data, in ISO 8601 format.",
|
||||
},
|
||||
},
|
||||
"required": ["ticker", "include_history"]
|
||||
},
|
||||
},
|
||||
},
|
||||
# Can pass in multiple function schemas as well
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "analyze_company_financials",
|
||||
"description": "Analyze key financial metrics and ratios for a company.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"ticker": {
|
||||
"type": "string",
|
||||
"description": "The stock ticker symbol of the company",
|
||||
},
|
||||
"metrics": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"enum": ["PE_ratio", "market_cap", "revenue", "profit_margin"]
|
||||
},
|
||||
"description": "List of financial metrics to analyze"
|
||||
},
|
||||
"timeframe": {
|
||||
"type": "string",
|
||||
"enum": ["quarterly", "annual", "ttm"],
|
||||
"description": "Timeframe for the analysis"
|
||||
}
|
||||
},
|
||||
"required": ["ticker", "metrics"]
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
# Initialize the agent with multiple function schemas
|
||||
agent = Agent(
|
||||
agent_name="Financial-Analysis-Agent",
|
||||
agent_description="Personal finance advisor agent that can fetch stock prices and analyze financials",
|
||||
system_prompt=FINANCIAL_AGENT_SYS_PROMPT,
|
||||
max_loops=1,
|
||||
tools_list_dictionary=tools, # Pass in the list of function schemas
|
||||
output_type="final"
|
||||
)
|
||||
|
||||
# Example usage with stock price query
|
||||
stock_response = agent.run(
|
||||
"What is the current stock price for Apple Inc. (AAPL)? Include historical data."
|
||||
)
|
||||
print("Stock Price Response:", stock_response)
|
||||
|
||||
# Example usage with financial analysis query
|
||||
analysis_response = agent.run(
|
||||
"Analyze Apple's PE ratio and market cap using quarterly data."
|
||||
)
|
||||
print("Financial Analysis Response:", analysis_response)
|
||||
```
|
||||
|
||||
## Schema Types and Properties
|
||||
|
||||
The function schema supports various parameter types and properties:
|
||||
|
||||
| Schema Type | Description |
|
||||
|------------|-------------|
|
||||
| Basic Types | `string`, `number`, `integer`, `boolean`, `array`, `object` |
|
||||
| Format Specifications | `date-time`, `date`, `email`, etc. |
|
||||
| Enums | Restrict values to a predefined set |
|
||||
| Required vs Optional Parameters | Specify which parameters must be provided |
|
||||
| Nested Objects and Arrays | Support for complex data structures |
|
||||
|
||||
Example of a more complex schema:
|
||||
|
||||
```python
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "generate_investment_report",
|
||||
"description": "Generate a comprehensive investment report",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"portfolio": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"stocks": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"ticker": {"type": "string"},
|
||||
"shares": {"type": "number"},
|
||||
"entry_price": {"type": "number"}
|
||||
}
|
||||
}
|
||||
},
|
||||
"risk_tolerance": {
|
||||
"type": "string",
|
||||
"enum": ["low", "medium", "high"]
|
||||
},
|
||||
"time_horizon": {
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"maximum": 30,
|
||||
"description": "Investment time horizon in years"
|
||||
}
|
||||
},
|
||||
"required": ["stocks", "risk_tolerance"]
|
||||
},
|
||||
"report_type": {
|
||||
"type": "string",
|
||||
"enum": ["summary", "detailed", "risk_analysis"]
|
||||
}
|
||||
},
|
||||
"required": ["portfolio"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This example shows how to structure complex nested objects, arrays, and various parameter types while following OpenAI's function calling schema.
|
@ -0,0 +1,646 @@
|
||||
# Basic Agent Example
|
||||
|
||||
This tutorial demonstrates how to create and use tools (callables) with the Swarms framework. Tools are Python functions that your agent can call to perform specific tasks, interact with external services, or process data. We'll show you how to build well-structured tools and integrate them with your agent.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Python 3.7+
|
||||
|
||||
- OpenAI API key
|
||||
|
||||
- Swarms library
|
||||
|
||||
## Building Tools for Your Agent
|
||||
|
||||
Tools are functions that your agent can use to interact with external services, process data, or perform specific tasks. Here's a guide on how to build effective tools for your agent:
|
||||
|
||||
### Tool Structure Best Practices
|
||||
|
||||
1. **Type Hints**: Always use type hints to specify input and output types
|
||||
|
||||
2. **Docstrings**: Include comprehensive docstrings with description, args, returns, and examples
|
||||
|
||||
3. **Error Handling**: Implement proper error handling and return consistent JSON responses
|
||||
|
||||
4. **Rate Limiting**: Include rate limiting when dealing with APIs
|
||||
|
||||
5. **Input Validation**: Validate input parameters before processing
|
||||
|
||||
### Example Tool Template
|
||||
|
||||
Here's a template for creating a well-structured tool:
|
||||
|
||||
```python
|
||||
from typing import Optional, Dict, Any
|
||||
import json
|
||||
|
||||
def example_tool(param1: str, param2: Optional[int] = None) -> str:
|
||||
"""
|
||||
Brief description of what the tool does.
|
||||
|
||||
Args:
|
||||
param1 (str): Description of first parameter
|
||||
param2 (Optional[int]): Description of optional parameter
|
||||
|
||||
Returns:
|
||||
str: JSON formatted string containing the result
|
||||
|
||||
Raises:
|
||||
ValueError: Description of when this error occurs
|
||||
RequestException: Description of when this error occurs
|
||||
|
||||
Example:
|
||||
>>> result = example_tool("test", 123)
|
||||
>>> print(result)
|
||||
{"status": "success", "data": {"key": "value"}}
|
||||
"""
|
||||
try:
|
||||
# Input validation
|
||||
if not isinstance(param1, str):
|
||||
raise ValueError("param1 must be a string")
|
||||
|
||||
# Main logic
|
||||
result: Dict[str, Any] = {
|
||||
"status": "success",
|
||||
"data": {
|
||||
"param1": param1,
|
||||
"param2": param2
|
||||
}
|
||||
}
|
||||
|
||||
# Return JSON string
|
||||
return json.dumps(result, indent=2)
|
||||
|
||||
except ValueError as e:
|
||||
return json.dumps({"error": f"Validation error: {str(e)}"})
|
||||
except Exception as e:
|
||||
return json.dumps({"error": f"Unexpected error: {str(e)}"})
|
||||
```
|
||||
|
||||
### Building API Integration Tools
|
||||
|
||||
When building tools that interact with external APIs:
|
||||
|
||||
1. **API Client Setup**:
|
||||
|
||||
```python
|
||||
def get_api_data(endpoint: str, params: Dict[str, Any]) -> str:
|
||||
"""
|
||||
Generic API data fetcher with proper error handling.
|
||||
|
||||
Args:
|
||||
endpoint (str): API endpoint to call
|
||||
params (Dict[str, Any]): Query parameters
|
||||
|
||||
Returns:
|
||||
str: JSON formatted response
|
||||
"""
|
||||
try:
|
||||
response = requests.get(
|
||||
endpoint,
|
||||
params=params,
|
||||
timeout=10
|
||||
)
|
||||
response.raise_for_status()
|
||||
return json.dumps(response.json(), indent=2)
|
||||
except requests.RequestException as e:
|
||||
return json.dumps({"error": f"API error: {str(e)}"})
|
||||
```
|
||||
|
||||
|
||||
|
||||
### Data Processing Tools
|
||||
|
||||
Example of a tool that processes data:
|
||||
|
||||
```python
|
||||
from typing import List, Dict
|
||||
import pandas as pd
|
||||
|
||||
def process_market_data(prices: List[float], window: int = 14) -> str:
|
||||
"""
|
||||
Calculate technical indicators from price data.
|
||||
|
||||
Args:
|
||||
prices (List[float]): List of historical prices
|
||||
window (int): Rolling window size for calculations
|
||||
|
||||
Returns:
|
||||
str: JSON formatted string with calculated indicators
|
||||
|
||||
Example:
|
||||
>>> prices = [100, 101, 99, 102, 98, 103]
|
||||
>>> result = process_market_data(prices, window=3)
|
||||
>>> print(result)
|
||||
{"sma": 101.0, "volatility": 2.1}
|
||||
"""
|
||||
try:
|
||||
df = pd.DataFrame({"price": prices})
|
||||
|
||||
results: Dict[str, float] = {
|
||||
"sma": df["price"].rolling(window).mean().iloc[-1],
|
||||
"volatility": df["price"].rolling(window).std().iloc[-1]
|
||||
}
|
||||
|
||||
return json.dumps(results, indent=2)
|
||||
|
||||
except Exception as e:
|
||||
return json.dumps({"error": f"Processing error: {str(e)}"})
|
||||
```
|
||||
|
||||
### Adding Tools to Your Agent
|
||||
|
||||
Once you've created your tools, add them to your agent like this:
|
||||
|
||||
```python
|
||||
agent = Agent(
|
||||
agent_name="Your-Agent",
|
||||
agent_description="Description of your agent",
|
||||
system_prompt="System prompt for your agent",
|
||||
tools=[
|
||||
example_tool,
|
||||
get_api_data,
|
||||
rate_limited_api_call,
|
||||
process_market_data
|
||||
]
|
||||
)
|
||||
```
|
||||
|
||||
## Tutorial Steps
|
||||
|
||||
1. First, install the latest version of Swarms:
|
||||
|
||||
```bash
|
||||
pip3 install -U swarms
|
||||
```
|
||||
|
||||
2. Set up your environment variables in a `.env` file:
|
||||
|
||||
```plaintext
|
||||
OPENAI_API_KEY="your-api-key-here"
|
||||
WORKSPACE_DIR="agent_workspace"
|
||||
```
|
||||
|
||||
3. Create a new Python file and customize your agent with the following parameters:
|
||||
- `agent_name`: A unique identifier for your agent
|
||||
|
||||
- `agent_description`: A detailed description of your agent's capabilities
|
||||
|
||||
- `system_prompt`: The core instructions that define your agent's behavior
|
||||
|
||||
- `model_name`: The GPT model to use
|
||||
|
||||
- Additional configuration options for temperature and output format
|
||||
|
||||
4. Run the example code below:
|
||||
|
||||
|
||||
|
||||
```python
|
||||
import json
|
||||
import requests
|
||||
from swarms import Agent
|
||||
from typing import List
|
||||
import time
|
||||
|
||||
|
||||
def get_coin_price(coin_id: str, vs_currency: str) -> str:
|
||||
"""
|
||||
Get the current price of a specific cryptocurrency.
|
||||
|
||||
Args:
|
||||
coin_id (str): The CoinGecko ID of the cryptocurrency (e.g., 'bitcoin', 'ethereum')
|
||||
vs_currency (str, optional): The target currency. Defaults to "usd".
|
||||
|
||||
Returns:
|
||||
str: JSON formatted string containing the coin's current price and market data
|
||||
|
||||
Raises:
|
||||
requests.RequestException: If the API request fails
|
||||
|
||||
Example:
|
||||
>>> result = get_coin_price("bitcoin")
|
||||
>>> print(result)
|
||||
{"bitcoin": {"usd": 45000, "usd_market_cap": 850000000000, ...}}
|
||||
"""
|
||||
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,
|
||||
"include_last_updated_at": True,
|
||||
}
|
||||
|
||||
response = requests.get(url, params=params, timeout=10)
|
||||
response.raise_for_status()
|
||||
|
||||
data = response.json()
|
||||
return json.dumps(data, indent=2)
|
||||
|
||||
except requests.RequestException as e:
|
||||
return json.dumps(
|
||||
{
|
||||
"error": f"Failed to fetch price for {coin_id}: {str(e)}"
|
||||
}
|
||||
)
|
||||
except Exception as e:
|
||||
return json.dumps({"error": f"Unexpected error: {str(e)}"})
|
||||
|
||||
|
||||
def get_top_cryptocurrencies(limit: int, vs_currency: str) -> str:
|
||||
"""
|
||||
Fetch the top cryptocurrencies by market capitalization.
|
||||
|
||||
Args:
|
||||
limit (int, optional): Number of coins to retrieve (1-250). Defaults to 10.
|
||||
vs_currency (str, optional): The target currency. Defaults to "usd".
|
||||
|
||||
Returns:
|
||||
str: JSON formatted string containing top cryptocurrencies with detailed market data
|
||||
|
||||
Raises:
|
||||
requests.RequestException: If the API request fails
|
||||
ValueError: If limit is not between 1 and 250
|
||||
|
||||
Example:
|
||||
>>> result = get_top_cryptocurrencies(5)
|
||||
>>> print(result)
|
||||
[{"id": "bitcoin", "name": "Bitcoin", "current_price": 45000, ...}]
|
||||
"""
|
||||
try:
|
||||
if not 1 <= limit <= 250:
|
||||
raise ValueError("Limit must be between 1 and 250")
|
||||
|
||||
url = "https://api.coingecko.com/api/v3/coins/markets"
|
||||
params = {
|
||||
"vs_currency": vs_currency,
|
||||
"order": "market_cap_desc",
|
||||
"per_page": limit,
|
||||
"page": 1,
|
||||
"sparkline": False,
|
||||
"price_change_percentage": "24h,7d",
|
||||
}
|
||||
|
||||
response = requests.get(url, params=params, timeout=10)
|
||||
response.raise_for_status()
|
||||
|
||||
data = response.json()
|
||||
|
||||
# Simplify the data structure for better readability
|
||||
simplified_data = []
|
||||
for coin in data:
|
||||
simplified_data.append(
|
||||
{
|
||||
"id": coin.get("id"),
|
||||
"symbol": coin.get("symbol"),
|
||||
"name": coin.get("name"),
|
||||
"current_price": coin.get("current_price"),
|
||||
"market_cap": coin.get("market_cap"),
|
||||
"market_cap_rank": coin.get("market_cap_rank"),
|
||||
"total_volume": coin.get("total_volume"),
|
||||
"price_change_24h": coin.get(
|
||||
"price_change_percentage_24h"
|
||||
),
|
||||
"price_change_7d": coin.get(
|
||||
"price_change_percentage_7d_in_currency"
|
||||
),
|
||||
"last_updated": coin.get("last_updated"),
|
||||
}
|
||||
)
|
||||
|
||||
return json.dumps(simplified_data, indent=2)
|
||||
|
||||
except (requests.RequestException, ValueError) as e:
|
||||
return json.dumps(
|
||||
{
|
||||
"error": f"Failed to fetch top cryptocurrencies: {str(e)}"
|
||||
}
|
||||
)
|
||||
except Exception as e:
|
||||
return json.dumps({"error": f"Unexpected error: {str(e)}"})
|
||||
|
||||
|
||||
def search_cryptocurrencies(query: str) -> str:
|
||||
"""
|
||||
Search for cryptocurrencies by name or symbol.
|
||||
|
||||
Args:
|
||||
query (str): The search term (coin name or symbol)
|
||||
|
||||
Returns:
|
||||
str: JSON formatted string containing search results with coin details
|
||||
|
||||
Raises:
|
||||
requests.RequestException: If the API request fails
|
||||
|
||||
Example:
|
||||
>>> result = search_cryptocurrencies("ethereum")
|
||||
>>> print(result)
|
||||
{"coins": [{"id": "ethereum", "name": "Ethereum", "symbol": "eth", ...}]}
|
||||
"""
|
||||
try:
|
||||
url = "https://api.coingecko.com/api/v3/search"
|
||||
params = {"query": query}
|
||||
|
||||
response = requests.get(url, params=params, timeout=10)
|
||||
response.raise_for_status()
|
||||
|
||||
data = response.json()
|
||||
|
||||
# Extract and format the results
|
||||
result = {
|
||||
"coins": data.get("coins", [])[
|
||||
:10
|
||||
], # Limit to top 10 results
|
||||
"query": query,
|
||||
"total_results": len(data.get("coins", [])),
|
||||
}
|
||||
|
||||
return json.dumps(result, indent=2)
|
||||
|
||||
except requests.RequestException as e:
|
||||
return json.dumps(
|
||||
{"error": f'Failed to search for "{query}": {str(e)}'}
|
||||
)
|
||||
except Exception as e:
|
||||
return json.dumps({"error": f"Unexpected error: {str(e)}"})
|
||||
|
||||
|
||||
def get_jupiter_quote(
|
||||
input_mint: str,
|
||||
output_mint: str,
|
||||
amount: float,
|
||||
slippage: float = 0.5,
|
||||
) -> str:
|
||||
"""
|
||||
Get a quote for token swaps using Jupiter Protocol on Solana.
|
||||
|
||||
Args:
|
||||
input_mint (str): Input token mint address
|
||||
output_mint (str): Output token mint address
|
||||
amount (float): Amount of input tokens to swap
|
||||
slippage (float, optional): Slippage tolerance percentage. Defaults to 0.5.
|
||||
|
||||
Returns:
|
||||
str: JSON formatted string containing the swap quote details
|
||||
|
||||
Example:
|
||||
>>> result = get_jupiter_quote("SOL_MINT_ADDRESS", "USDC_MINT_ADDRESS", 1.0)
|
||||
>>> print(result)
|
||||
{"inputAmount": "1000000000", "outputAmount": "22.5", "route": [...]}
|
||||
"""
|
||||
try:
|
||||
url = "https://lite-api.jup.ag/swap/v1/quote"
|
||||
params = {
|
||||
"inputMint": input_mint,
|
||||
"outputMint": output_mint,
|
||||
"amount": str(int(amount * 1e9)), # Convert to lamports
|
||||
"slippageBps": int(slippage * 100),
|
||||
}
|
||||
|
||||
response = requests.get(url, params=params, timeout=10)
|
||||
response.raise_for_status()
|
||||
return json.dumps(response.json(), indent=2)
|
||||
|
||||
except requests.RequestException as e:
|
||||
return json.dumps(
|
||||
{"error": f"Failed to get Jupiter quote: {str(e)}"}
|
||||
)
|
||||
except Exception as e:
|
||||
return json.dumps({"error": f"Unexpected error: {str(e)}"})
|
||||
|
||||
|
||||
def get_htx_market_data(symbol: str) -> str:
|
||||
"""
|
||||
Get market data for a trading pair from HTX exchange.
|
||||
|
||||
Args:
|
||||
symbol (str): Trading pair symbol (e.g., 'btcusdt', 'ethusdt')
|
||||
|
||||
Returns:
|
||||
str: JSON formatted string containing market data
|
||||
|
||||
Example:
|
||||
>>> result = get_htx_market_data("btcusdt")
|
||||
>>> print(result)
|
||||
{"symbol": "btcusdt", "price": "45000", "volume": "1000000", ...}
|
||||
"""
|
||||
try:
|
||||
url = "https://api.htx.com/market/detail/merged"
|
||||
params = {"symbol": symbol.lower()}
|
||||
|
||||
response = requests.get(url, params=params, timeout=10)
|
||||
response.raise_for_status()
|
||||
return json.dumps(response.json(), indent=2)
|
||||
|
||||
except requests.RequestException as e:
|
||||
return json.dumps(
|
||||
{"error": f"Failed to fetch HTX market data: {str(e)}"}
|
||||
)
|
||||
except Exception as e:
|
||||
return json.dumps({"error": f"Unexpected error: {str(e)}"})
|
||||
|
||||
|
||||
def get_token_historical_data(
|
||||
token_id: str, days: int = 30, vs_currency: str = "usd"
|
||||
) -> str:
|
||||
"""
|
||||
Get historical price and market data for a cryptocurrency.
|
||||
|
||||
Args:
|
||||
token_id (str): The CoinGecko ID of the cryptocurrency
|
||||
days (int, optional): Number of days of historical data. Defaults to 30.
|
||||
vs_currency (str, optional): The target currency. Defaults to "usd".
|
||||
|
||||
Returns:
|
||||
str: JSON formatted string containing historical price and market data
|
||||
|
||||
Example:
|
||||
>>> result = get_token_historical_data("bitcoin", 7)
|
||||
>>> print(result)
|
||||
{"prices": [[timestamp, price], ...], "market_caps": [...], "volumes": [...]}
|
||||
"""
|
||||
try:
|
||||
url = f"https://api.coingecko.com/api/v3/coins/{token_id}/market_chart"
|
||||
params = {
|
||||
"vs_currency": vs_currency,
|
||||
"days": days,
|
||||
"interval": "daily",
|
||||
}
|
||||
|
||||
response = requests.get(url, params=params, timeout=10)
|
||||
response.raise_for_status()
|
||||
return json.dumps(response.json(), indent=2)
|
||||
|
||||
except requests.RequestException as e:
|
||||
return json.dumps(
|
||||
{"error": f"Failed to fetch historical data: {str(e)}"}
|
||||
)
|
||||
except Exception as e:
|
||||
return json.dumps({"error": f"Unexpected error: {str(e)}"})
|
||||
|
||||
|
||||
def get_defi_stats() -> str:
|
||||
"""
|
||||
Get global DeFi statistics including TVL, trading volumes, and dominance.
|
||||
|
||||
Returns:
|
||||
str: JSON formatted string containing global DeFi statistics
|
||||
|
||||
Example:
|
||||
>>> result = get_defi_stats()
|
||||
>>> print(result)
|
||||
{"total_value_locked": 50000000000, "defi_dominance": 15.5, ...}
|
||||
"""
|
||||
try:
|
||||
url = "https://api.coingecko.com/api/v3/global/decentralized_finance_defi"
|
||||
response = requests.get(url, timeout=10)
|
||||
response.raise_for_status()
|
||||
return json.dumps(response.json(), indent=2)
|
||||
|
||||
except requests.RequestException as e:
|
||||
return json.dumps(
|
||||
{"error": f"Failed to fetch DeFi stats: {str(e)}"}
|
||||
)
|
||||
except Exception as e:
|
||||
return json.dumps({"error": f"Unexpected error: {str(e)}"})
|
||||
|
||||
|
||||
def get_jupiter_tokens() -> str:
|
||||
"""
|
||||
Get list of tokens supported by Jupiter Protocol on Solana.
|
||||
|
||||
Returns:
|
||||
str: JSON formatted string containing supported tokens
|
||||
|
||||
Example:
|
||||
>>> result = get_jupiter_tokens()
|
||||
>>> print(result)
|
||||
{"tokens": [{"symbol": "SOL", "mint": "...", "decimals": 9}, ...]}
|
||||
"""
|
||||
try:
|
||||
url = "https://lite-api.jup.ag/tokens/v1/mints/tradable"
|
||||
response = requests.get(url, timeout=10)
|
||||
response.raise_for_status()
|
||||
return json.dumps(response.json(), indent=2)
|
||||
|
||||
except requests.RequestException as e:
|
||||
return json.dumps(
|
||||
{"error": f"Failed to fetch Jupiter tokens: {str(e)}"}
|
||||
)
|
||||
except Exception as e:
|
||||
return json.dumps({"error": f"Unexpected error: {str(e)}"})
|
||||
|
||||
|
||||
def get_htx_trading_pairs() -> str:
|
||||
"""
|
||||
Get list of all trading pairs available on HTX exchange.
|
||||
|
||||
Returns:
|
||||
str: JSON formatted string containing trading pairs information
|
||||
|
||||
Example:
|
||||
>>> result = get_htx_trading_pairs()
|
||||
>>> print(result)
|
||||
{"symbols": [{"symbol": "btcusdt", "state": "online", "type": "spot"}, ...]}
|
||||
"""
|
||||
try:
|
||||
url = "https://api.htx.com/v1/common/symbols"
|
||||
response = requests.get(url, timeout=10)
|
||||
response.raise_for_status()
|
||||
return json.dumps(response.json(), indent=2)
|
||||
|
||||
except requests.RequestException as e:
|
||||
return json.dumps(
|
||||
{"error": f"Failed to fetch HTX trading pairs: {str(e)}"}
|
||||
)
|
||||
except Exception as e:
|
||||
return json.dumps({"error": f"Unexpected error: {str(e)}"})
|
||||
|
||||
|
||||
def get_market_sentiment(coin_ids: List[str]) -> str:
|
||||
"""
|
||||
Get market sentiment data including social metrics and developer activity.
|
||||
|
||||
Args:
|
||||
coin_ids (List[str]): List of CoinGecko coin IDs
|
||||
|
||||
Returns:
|
||||
str: JSON formatted string containing market sentiment data
|
||||
|
||||
Example:
|
||||
>>> result = get_market_sentiment(["bitcoin", "ethereum"])
|
||||
>>> print(result)
|
||||
{"bitcoin": {"sentiment_score": 75, "social_volume": 15000, ...}, ...}
|
||||
"""
|
||||
try:
|
||||
sentiment_data = {}
|
||||
for coin_id in coin_ids:
|
||||
url = f"https://api.coingecko.com/api/v3/coins/{coin_id}"
|
||||
params = {
|
||||
"localization": False,
|
||||
"tickers": False,
|
||||
"market_data": False,
|
||||
"community_data": True,
|
||||
"developer_data": True,
|
||||
}
|
||||
|
||||
response = requests.get(url, params=params, timeout=10)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
|
||||
sentiment_data[coin_id] = {
|
||||
"community_score": data.get("community_score"),
|
||||
"developer_score": data.get("developer_score"),
|
||||
"public_interest_score": data.get(
|
||||
"public_interest_score"
|
||||
),
|
||||
"community_data": data.get("community_data"),
|
||||
"developer_data": data.get("developer_data"),
|
||||
}
|
||||
|
||||
# Rate limiting to avoid API restrictions
|
||||
time.sleep(0.6)
|
||||
|
||||
return json.dumps(sentiment_data, indent=2)
|
||||
|
||||
except requests.RequestException as e:
|
||||
return json.dumps(
|
||||
{"error": f"Failed to fetch market sentiment: {str(e)}"}
|
||||
)
|
||||
except Exception as e:
|
||||
return json.dumps({"error": f"Unexpected error: {str(e)}"})
|
||||
|
||||
|
||||
# Initialize the agent with expanded tools
|
||||
agent = Agent(
|
||||
agent_name="Financial-Analysis-Agent",
|
||||
agent_description="Advanced financial advisor agent with comprehensive cryptocurrency market analysis capabilities across multiple platforms including Jupiter Protocol and HTX",
|
||||
system_prompt="You are an advanced financial advisor agent with access to real-time cryptocurrency data from multiple sources including CoinGecko, Jupiter Protocol, and HTX. You can help users analyze market trends, check prices, find trading opportunities, perform swaps, and get detailed market insights. Always provide accurate, up-to-date information and explain market data in an easy-to-understand way.",
|
||||
max_loops=1,
|
||||
max_tokens=4096,
|
||||
model_name="gpt-4o-mini",
|
||||
dynamic_temperature_enabled=True,
|
||||
output_type="all",
|
||||
tools=[
|
||||
get_coin_price,
|
||||
get_top_cryptocurrencies,
|
||||
search_cryptocurrencies,
|
||||
get_jupiter_quote,
|
||||
get_htx_market_data,
|
||||
get_token_historical_data,
|
||||
get_defi_stats,
|
||||
get_jupiter_tokens,
|
||||
get_htx_trading_pairs,
|
||||
get_market_sentiment,
|
||||
],
|
||||
# Upload your tools to the tools parameter here!
|
||||
)
|
||||
|
||||
# agent.run("Use defi stats to find the best defi project to invest in")
|
||||
agent.run("Get the market sentiment for bitcoin")
|
||||
# Automatically executes any number and combination of tools you have uploaded to the tools parameter!
|
||||
```
|
@ -0,0 +1,107 @@
|
||||
# Basic Agent Example
|
||||
|
||||
This example demonstrates how to create and configure a sophisticated AI agent using the Swarms framework. In this tutorial, we'll build a Quantitative Trading Agent that can analyze financial markets and provide investment insights. The agent is powered by GPT models and can be customized for various financial analysis tasks.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Python 3.7+
|
||||
|
||||
- OpenAI API key
|
||||
|
||||
- Swarms library
|
||||
|
||||
## Tutorial Steps
|
||||
|
||||
1. First, install the latest version of Swarms:
|
||||
|
||||
```bash
|
||||
pip3 install -U swarms
|
||||
```
|
||||
|
||||
2. Set up your environment variables in a `.env` file:
|
||||
|
||||
```plaintext
|
||||
OPENAI_API_KEY="your-api-key-here"
|
||||
WORKSPACE_DIR="agent_workspace"
|
||||
```
|
||||
|
||||
3. Create a new Python file and customize your agent with the following parameters:
|
||||
- `agent_name`: A unique identifier for your agent
|
||||
|
||||
- `agent_description`: A detailed description of your agent's capabilities
|
||||
|
||||
- `system_prompt`: The core instructions that define your agent's behavior
|
||||
|
||||
- `model_name`: The GPT model to use
|
||||
|
||||
- Additional configuration options for temperature and output format
|
||||
|
||||
4. Run the example code below:
|
||||
|
||||
|
||||
## Code
|
||||
|
||||
```python
|
||||
import time
|
||||
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="json",
|
||||
safety_prompt_on=True,
|
||||
)
|
||||
|
||||
out = agent.run("What are the best top 3 etfs for gold coverage?")
|
||||
|
||||
time.sleep(10)
|
||||
print(out)
|
||||
```
|
||||
|
||||
## Example Output
|
||||
|
||||
The agent will return a JSON response containing recommendations for gold ETFs based on the query.
|
||||
|
||||
## Customization
|
||||
|
||||
You can modify the system prompt and agent parameters to create specialized agents for different use cases:
|
||||
|
||||
| Use Case | Description |
|
||||
|----------|-------------|
|
||||
| Market Analysis | Analyze market trends, patterns, and indicators to identify trading opportunities |
|
||||
| Portfolio Management | Optimize asset allocation and rebalancing strategies |
|
||||
| Risk Assessment | Evaluate and mitigate potential risks in trading strategies |
|
||||
| Trading Strategy Development | Design and implement algorithmic trading strategies |
|
@ -0,0 +1,248 @@
|
||||
# ConcurrentWorkflow Examples
|
||||
|
||||
The ConcurrentWorkflow architecture enables parallel execution of multiple agents, allowing them to work simultaneously on different aspects of a task. This is particularly useful for complex tasks that can be broken down into independent subtasks.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Python 3.7+
|
||||
- OpenAI API key or other supported LLM provider keys
|
||||
- Swarms library
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
pip3 install -U swarms
|
||||
```
|
||||
|
||||
## Environment Variables
|
||||
|
||||
```plaintext
|
||||
WORKSPACE_DIR="agent_workspace"
|
||||
OPENAI_API_KEY=""
|
||||
ANTHROPIC_API_KEY=""
|
||||
GROQ_API_KEY=""
|
||||
```
|
||||
|
||||
## Basic Usage
|
||||
|
||||
### 1. Initialize Specialized Agents
|
||||
|
||||
```python
|
||||
from swarms import Agent, ConcurrentWorkflow
|
||||
|
||||
# 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="gpt-4o",
|
||||
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="gpt-4o",
|
||||
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="gpt-4o",
|
||||
max_loops=1,
|
||||
)
|
||||
```
|
||||
|
||||
### 2. Create and Run ConcurrentWorkflow
|
||||
|
||||
```python
|
||||
# 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"
|
||||
)
|
||||
```
|
||||
|
||||
## Advanced Usage
|
||||
|
||||
### 1. Custom Agent Configuration
|
||||
|
||||
```python
|
||||
from swarms import Agent, ConcurrentWorkflow
|
||||
|
||||
# Initialize agents with custom configurations
|
||||
sentiment_analyzer = Agent(
|
||||
agent_name="Sentiment-Analyzer",
|
||||
system_prompt="You analyze social media sentiment...",
|
||||
model_name="gpt-4o",
|
||||
max_loops=1,
|
||||
temperature=0.7,
|
||||
streaming_on=True,
|
||||
verbose=True,
|
||||
)
|
||||
|
||||
news_analyzer = Agent(
|
||||
agent_name="News-Analyzer",
|
||||
system_prompt="You analyze news articles and reports...",
|
||||
model_name="gpt-4o",
|
||||
max_loops=1,
|
||||
temperature=0.5,
|
||||
streaming_on=True,
|
||||
verbose=True,
|
||||
)
|
||||
|
||||
# Create and run workflow
|
||||
workflow = ConcurrentWorkflow(
|
||||
name="sentiment-analysis-workflow",
|
||||
agents=[sentiment_analyzer, news_analyzer],
|
||||
max_loops=1,
|
||||
verbose=True,
|
||||
)
|
||||
|
||||
result = workflow.run(
|
||||
"Analyze the market sentiment for Bitcoin based on social media and news"
|
||||
)
|
||||
```
|
||||
|
||||
### 2. Error Handling and Logging
|
||||
|
||||
```python
|
||||
try:
|
||||
workflow = ConcurrentWorkflow(
|
||||
name="error-handled-workflow",
|
||||
agents=agents,
|
||||
max_loops=1,
|
||||
verbose=True,
|
||||
)
|
||||
|
||||
result = workflow.run("Complex analysis task")
|
||||
|
||||
# Process results
|
||||
for agent_result in result:
|
||||
print(f"Agent {agent_result['agent']}: {agent_result['output']}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error in workflow: {str(e)}")
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. Task Distribution:
|
||||
- Break down complex tasks into independent subtasks
|
||||
- Assign appropriate agents to each subtask
|
||||
- Ensure tasks can be processed concurrently
|
||||
|
||||
2. Agent Configuration:
|
||||
- Use specialized agents for specific tasks
|
||||
- Configure appropriate model parameters
|
||||
- Set meaningful system prompts
|
||||
|
||||
3. Resource Management:
|
||||
- Monitor concurrent execution
|
||||
- Handle rate limits appropriately
|
||||
- Manage memory usage
|
||||
|
||||
4. Error Handling:
|
||||
- Implement proper error handling
|
||||
- Log errors and exceptions
|
||||
- Provide fallback mechanisms
|
||||
|
||||
## Example Implementation
|
||||
|
||||
Here's a complete example showing how to use ConcurrentWorkflow for a comprehensive market analysis:
|
||||
|
||||
```python
|
||||
import os
|
||||
from swarms import Agent, ConcurrentWorkflow
|
||||
|
||||
# Initialize specialized agents
|
||||
market_analyst = Agent(
|
||||
agent_name="Market-Analyst",
|
||||
system_prompt="""You are a market analysis specialist focusing on:
|
||||
1. Market trends and patterns
|
||||
2. Competitive analysis
|
||||
3. Market opportunities
|
||||
4. Industry dynamics
|
||||
5. Growth potential""",
|
||||
model_name="gpt-4o",
|
||||
max_loops=1,
|
||||
)
|
||||
|
||||
financial_analyst = Agent(
|
||||
agent_name="Financial-Analyst",
|
||||
system_prompt="""You are a financial analysis expert specializing in:
|
||||
1. Financial statements analysis
|
||||
2. Ratio analysis
|
||||
3. Cash flow analysis
|
||||
4. Valuation metrics
|
||||
5. Risk assessment""",
|
||||
model_name="gpt-4o",
|
||||
max_loops=1,
|
||||
)
|
||||
|
||||
risk_analyst = Agent(
|
||||
agent_name="Risk-Analyst",
|
||||
system_prompt="""You are a risk assessment specialist focusing on:
|
||||
1. Market risks
|
||||
2. Operational risks
|
||||
3. Financial risks
|
||||
4. Regulatory risks
|
||||
5. Strategic risks""",
|
||||
model_name="gpt-4o",
|
||||
max_loops=1,
|
||||
)
|
||||
|
||||
# Create the concurrent workflow
|
||||
workflow = ConcurrentWorkflow(
|
||||
name="comprehensive-analysis-workflow",
|
||||
agents=[market_analyst, financial_analyst, risk_analyst],
|
||||
max_loops=1,
|
||||
verbose=True,
|
||||
)
|
||||
|
||||
# Run the analysis
|
||||
try:
|
||||
result = workflow.run(
|
||||
"""Provide a comprehensive analysis of Apple Inc. (AAPL) including:
|
||||
1. Market position and competitive analysis
|
||||
2. Financial performance and health
|
||||
3. Risk assessment and mitigation strategies"""
|
||||
)
|
||||
|
||||
# Process and display results
|
||||
for agent_result in result:
|
||||
print(f"\nAnalysis from {agent_result['agent']}:")
|
||||
print(agent_result['output'])
|
||||
print("-" * 50)
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error during analysis: {str(e)}")
|
||||
```
|
||||
|
||||
This comprehensive guide demonstrates how to effectively use the ConcurrentWorkflow architecture for parallel processing of complex tasks using multiple specialized agents.
|
@ -0,0 +1,261 @@
|
||||
# MixtureOfAgents Examples
|
||||
|
||||
The MixtureOfAgents architecture combines multiple specialized agents with an aggregator agent to process complex tasks. This architecture is particularly effective for tasks requiring diverse expertise and consensus-building among different specialists.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Python 3.7+
|
||||
- OpenAI API key or other supported LLM provider keys
|
||||
- Swarms library
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
pip3 install -U swarms
|
||||
```
|
||||
|
||||
## Environment Variables
|
||||
|
||||
```plaintext
|
||||
WORKSPACE_DIR="agent_workspace"
|
||||
OPENAI_API_KEY=""
|
||||
ANTHROPIC_API_KEY=""
|
||||
GROQ_API_KEY=""
|
||||
```
|
||||
|
||||
## Basic Usage
|
||||
|
||||
### 1. Initialize Specialized Agents
|
||||
|
||||
```python
|
||||
from swarms import Agent, MixtureOfAgents
|
||||
|
||||
# Initialize specialized agents
|
||||
legal_expert = Agent(
|
||||
agent_name="Legal-Expert",
|
||||
system_prompt="""You are a legal expert specializing in contract law. Your responsibilities include:
|
||||
1. Analyzing legal documents and contracts
|
||||
2. Identifying potential legal risks
|
||||
3. Ensuring regulatory compliance
|
||||
4. Providing legal recommendations
|
||||
5. Drafting and reviewing legal documents""",
|
||||
model_name="gpt-4o",
|
||||
max_loops=1,
|
||||
)
|
||||
|
||||
financial_expert = Agent(
|
||||
agent_name="Financial-Expert",
|
||||
system_prompt="""You are a financial expert specializing in business finance. Your tasks include:
|
||||
1. Analyzing financial implications
|
||||
2. Evaluating costs and benefits
|
||||
3. Assessing financial risks
|
||||
4. Providing financial projections
|
||||
5. Recommending financial strategies""",
|
||||
model_name="gpt-4o",
|
||||
max_loops=1,
|
||||
)
|
||||
|
||||
business_expert = Agent(
|
||||
agent_name="Business-Expert",
|
||||
system_prompt="""You are a business strategy expert. Your focus areas include:
|
||||
1. Analyzing business models
|
||||
2. Evaluating market opportunities
|
||||
3. Assessing competitive advantages
|
||||
4. Providing strategic recommendations
|
||||
5. Planning business development""",
|
||||
model_name="gpt-4o",
|
||||
max_loops=1,
|
||||
)
|
||||
|
||||
# Initialize aggregator agent
|
||||
aggregator = Agent(
|
||||
agent_name="Decision-Aggregator",
|
||||
system_prompt="""You are a decision aggregator responsible for:
|
||||
1. Synthesizing input from multiple experts
|
||||
2. Resolving conflicting viewpoints
|
||||
3. Prioritizing recommendations
|
||||
4. Providing coherent final decisions
|
||||
5. Ensuring comprehensive coverage of all aspects""",
|
||||
model_name="gpt-4o",
|
||||
max_loops=1,
|
||||
)
|
||||
```
|
||||
|
||||
### 2. Create and Run MixtureOfAgents
|
||||
|
||||
```python
|
||||
# Create list of specialist agents
|
||||
specialists = [legal_expert, financial_expert, business_expert]
|
||||
|
||||
# Initialize the mixture of agents
|
||||
moa = MixtureOfAgents(
|
||||
agents=specialists,
|
||||
aggregator_agent=aggregator,
|
||||
layers=3,
|
||||
)
|
||||
|
||||
# Run the analysis
|
||||
result = moa.run(
|
||||
"Analyze the proposed merger between Company A and Company B, considering legal, financial, and business aspects."
|
||||
)
|
||||
```
|
||||
|
||||
## Advanced Usage
|
||||
|
||||
### 1. Custom Configuration with System Prompts
|
||||
|
||||
```python
|
||||
# Initialize MixtureOfAgents with custom aggregator prompt
|
||||
moa = MixtureOfAgents(
|
||||
agents=specialists,
|
||||
aggregator_agent=aggregator,
|
||||
aggregator_system_prompt="""As the decision aggregator, synthesize the analyses from all specialists into a coherent recommendation:
|
||||
1. Summarize key points from each specialist
|
||||
2. Identify areas of agreement and disagreement
|
||||
3. Weigh different perspectives
|
||||
4. Provide a balanced final recommendation
|
||||
5. Highlight key risks and opportunities""",
|
||||
layers=3,
|
||||
)
|
||||
|
||||
result = moa.run("Evaluate the potential acquisition of StartupX")
|
||||
```
|
||||
|
||||
### 2. Error Handling and Validation
|
||||
|
||||
```python
|
||||
try:
|
||||
moa = MixtureOfAgents(
|
||||
agents=specialists,
|
||||
aggregator_agent=aggregator,
|
||||
layers=3,
|
||||
verbose=True,
|
||||
)
|
||||
|
||||
result = moa.run("Complex analysis task")
|
||||
|
||||
# Validate and process results
|
||||
if result:
|
||||
print("Analysis complete:")
|
||||
print(result)
|
||||
else:
|
||||
print("Analysis failed to produce results")
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error in analysis: {str(e)}")
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. Agent Selection and Configuration:
|
||||
- Choose specialists with complementary expertise
|
||||
- Configure appropriate system prompts
|
||||
- Set suitable model parameters
|
||||
|
||||
2. Aggregator Configuration:
|
||||
- Define clear aggregation criteria
|
||||
- Set appropriate weights for different opinions
|
||||
- Configure conflict resolution strategies
|
||||
|
||||
3. Layer Management:
|
||||
- Set appropriate number of layers
|
||||
- Monitor layer effectiveness
|
||||
- Adjust based on task complexity
|
||||
|
||||
4. Quality Control:
|
||||
- Implement validation checks
|
||||
- Monitor agent performance
|
||||
- Ensure comprehensive coverage
|
||||
|
||||
## Example Implementation
|
||||
|
||||
Here's a complete example showing how to use MixtureOfAgents for a comprehensive business analysis:
|
||||
|
||||
```python
|
||||
import os
|
||||
from swarms import Agent, MixtureOfAgents
|
||||
|
||||
# Initialize specialist agents
|
||||
market_analyst = Agent(
|
||||
agent_name="Market-Analyst",
|
||||
system_prompt="""You are a market analysis specialist focusing on:
|
||||
1. Market size and growth
|
||||
2. Competitive landscape
|
||||
3. Customer segments
|
||||
4. Market trends
|
||||
5. Entry barriers""",
|
||||
model_name="gpt-4o",
|
||||
max_loops=1,
|
||||
)
|
||||
|
||||
financial_analyst = Agent(
|
||||
agent_name="Financial-Analyst",
|
||||
system_prompt="""You are a financial analysis expert specializing in:
|
||||
1. Financial performance
|
||||
2. Valuation metrics
|
||||
3. Cash flow analysis
|
||||
4. Investment requirements
|
||||
5. ROI projections""",
|
||||
model_name="gpt-4o",
|
||||
max_loops=1,
|
||||
)
|
||||
|
||||
risk_analyst = Agent(
|
||||
agent_name="Risk-Analyst",
|
||||
system_prompt="""You are a risk assessment specialist focusing on:
|
||||
1. Market risks
|
||||
2. Operational risks
|
||||
3. Financial risks
|
||||
4. Regulatory risks
|
||||
5. Strategic risks""",
|
||||
model_name="gpt-4o",
|
||||
max_loops=1,
|
||||
)
|
||||
|
||||
# Initialize aggregator
|
||||
aggregator = Agent(
|
||||
agent_name="Strategic-Aggregator",
|
||||
system_prompt="""You are a strategic decision aggregator responsible for:
|
||||
1. Synthesizing specialist analyses
|
||||
2. Identifying key insights
|
||||
3. Evaluating trade-offs
|
||||
4. Making recommendations
|
||||
5. Providing action plans""",
|
||||
model_name="gpt-4o",
|
||||
max_loops=1,
|
||||
)
|
||||
|
||||
# Create and configure MixtureOfAgents
|
||||
try:
|
||||
moa = MixtureOfAgents(
|
||||
agents=[market_analyst, financial_analyst, risk_analyst],
|
||||
aggregator_agent=aggregator,
|
||||
aggregator_system_prompt="""Synthesize the analyses from all specialists to provide:
|
||||
1. Comprehensive situation analysis
|
||||
2. Key opportunities and risks
|
||||
3. Strategic recommendations
|
||||
4. Implementation considerations
|
||||
5. Success metrics""",
|
||||
layers=3,
|
||||
verbose=True,
|
||||
)
|
||||
|
||||
# Run the analysis
|
||||
result = moa.run(
|
||||
"""Evaluate the business opportunity for expanding into the electric vehicle market:
|
||||
1. Market potential and competition
|
||||
2. Financial requirements and projections
|
||||
3. Risk assessment and mitigation strategies"""
|
||||
)
|
||||
|
||||
# Process and display results
|
||||
print("\nComprehensive Analysis Results:")
|
||||
print("=" * 50)
|
||||
print(result)
|
||||
print("=" * 50)
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error during analysis: {str(e)}")
|
||||
```
|
||||
|
||||
This comprehensive guide demonstrates how to effectively use the MixtureOfAgents architecture for complex analysis tasks requiring multiple expert perspectives and consensus-building.
|
@ -0,0 +1,240 @@
|
||||
# SwarmRouter Examples
|
||||
|
||||
The SwarmRouter is a flexible routing system designed to manage different types of swarms for task execution. It provides a unified interface to interact with various swarm types, including `AgentRearrange`, `MixtureOfAgents`, `SpreadSheetSwarm`, `SequentialWorkflow`, and `ConcurrentWorkflow`.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Python 3.7+
|
||||
- OpenAI API key or other supported LLM provider keys
|
||||
- Swarms library
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
pip3 install -U swarms
|
||||
```
|
||||
|
||||
## Environment Variables
|
||||
|
||||
```plaintext
|
||||
WORKSPACE_DIR="agent_workspace"
|
||||
OPENAI_API_KEY=""
|
||||
ANTHROPIC_API_KEY=""
|
||||
GROQ_API_KEY=""
|
||||
```
|
||||
|
||||
## Basic Usage
|
||||
|
||||
### 1. Initialize Specialized Agents
|
||||
|
||||
```python
|
||||
from swarms import Agent
|
||||
from swarms.structs.swarm_router import SwarmRouter, SwarmType
|
||||
|
||||
# Initialize specialized agents
|
||||
data_extractor_agent = Agent(
|
||||
agent_name="Data-Extractor",
|
||||
system_prompt="You are a data extraction specialist...",
|
||||
model_name="gpt-4o",
|
||||
max_loops=1,
|
||||
)
|
||||
|
||||
summarizer_agent = Agent(
|
||||
agent_name="Document-Summarizer",
|
||||
system_prompt="You are a document summarization expert...",
|
||||
model_name="gpt-4o",
|
||||
max_loops=1,
|
||||
)
|
||||
|
||||
financial_analyst_agent = Agent(
|
||||
agent_name="Financial-Analyst",
|
||||
system_prompt="You are a financial analysis specialist...",
|
||||
model_name="gpt-4o",
|
||||
max_loops=1,
|
||||
)
|
||||
```
|
||||
|
||||
### 2. Create SwarmRouter with Sequential Workflow
|
||||
|
||||
```python
|
||||
sequential_router = SwarmRouter(
|
||||
name="SequentialRouter",
|
||||
description="Process tasks in sequence",
|
||||
agents=[data_extractor_agent, summarizer_agent, financial_analyst_agent],
|
||||
swarm_type=SwarmType.SequentialWorkflow,
|
||||
max_loops=1
|
||||
)
|
||||
|
||||
# Run a task
|
||||
result = sequential_router.run("Analyze and summarize the quarterly financial report")
|
||||
```
|
||||
|
||||
### 3. Create SwarmRouter with Concurrent Workflow
|
||||
|
||||
```python
|
||||
concurrent_router = SwarmRouter(
|
||||
name="ConcurrentRouter",
|
||||
description="Process tasks concurrently",
|
||||
agents=[data_extractor_agent, summarizer_agent, financial_analyst_agent],
|
||||
swarm_type=SwarmType.ConcurrentWorkflow,
|
||||
max_loops=1
|
||||
)
|
||||
|
||||
# Run a task
|
||||
result = concurrent_router.run("Evaluate multiple aspects of the company simultaneously")
|
||||
```
|
||||
|
||||
### 4. Create SwarmRouter with AgentRearrange
|
||||
|
||||
```python
|
||||
rearrange_router = SwarmRouter(
|
||||
name="RearrangeRouter",
|
||||
description="Dynamically rearrange agents for optimal task processing",
|
||||
agents=[data_extractor_agent, summarizer_agent, financial_analyst_agent],
|
||||
swarm_type=SwarmType.AgentRearrange,
|
||||
flow=f"{data_extractor_agent.agent_name} -> {summarizer_agent.agent_name} -> {financial_analyst_agent.agent_name}",
|
||||
max_loops=1
|
||||
)
|
||||
|
||||
# Run a task
|
||||
result = rearrange_router.run("Process and analyze company documents")
|
||||
```
|
||||
|
||||
### 5. Create SwarmRouter with MixtureOfAgents
|
||||
|
||||
```python
|
||||
mixture_router = SwarmRouter(
|
||||
name="MixtureRouter",
|
||||
description="Combine multiple expert agents",
|
||||
agents=[data_extractor_agent, summarizer_agent, financial_analyst_agent],
|
||||
swarm_type=SwarmType.MixtureOfAgents,
|
||||
max_loops=1
|
||||
)
|
||||
|
||||
# Run a task
|
||||
result = mixture_router.run("Provide comprehensive analysis of company performance")
|
||||
```
|
||||
|
||||
## Advanced Features
|
||||
|
||||
### 1. Error Handling and Logging
|
||||
|
||||
```python
|
||||
try:
|
||||
result = router.run("Complex analysis task")
|
||||
|
||||
# Retrieve and print logs
|
||||
for log in router.get_logs():
|
||||
print(f"{log.timestamp} - {log.level}: {log.message}")
|
||||
except Exception as e:
|
||||
print(f"Error occurred: {str(e)}")
|
||||
```
|
||||
|
||||
### 2. Custom Configuration
|
||||
|
||||
```python
|
||||
router = SwarmRouter(
|
||||
name="CustomRouter",
|
||||
description="Custom router configuration",
|
||||
agents=[data_extractor_agent, summarizer_agent, financial_analyst_agent],
|
||||
swarm_type=SwarmType.SequentialWorkflow,
|
||||
max_loops=3,
|
||||
autosave=True,
|
||||
verbose=True,
|
||||
output_type="json"
|
||||
)
|
||||
```
|
||||
|
||||
# Best Practices
|
||||
|
||||
## Choose the appropriate swarm type based on your task requirements:
|
||||
|
||||
| Swarm Type | Use Case |
|
||||
|------------|----------|
|
||||
| `SequentialWorkflow` | Tasks that need to be processed in order |
|
||||
| `ConcurrentWorkflow` | Independent tasks that can be processed simultaneously |
|
||||
| `AgentRearrange` | Tasks requiring dynamic agent organization |
|
||||
| `MixtureOfAgents` | Complex tasks needing multiple expert perspectives |
|
||||
|
||||
## Configure agents appropriately:
|
||||
|
||||
| Configuration Aspect | Description |
|
||||
|---------------------|-------------|
|
||||
| Agent Names & Descriptions | Set meaningful and descriptive names that reflect the agent's role and purpose |
|
||||
| System Prompts | Define clear, specific prompts that outline the agent's responsibilities and constraints |
|
||||
| Model Parameters | Configure appropriate parameters like temperature, max_tokens, and other model-specific settings |
|
||||
|
||||
## Implement proper error handling:
|
||||
|
||||
| Error Handling Practice | Description |
|
||||
|------------------------|-------------|
|
||||
| Try-Except Blocks | Implement proper exception handling with try-except blocks |
|
||||
| Log Monitoring | Regularly monitor and analyze system logs for potential issues |
|
||||
| Edge Case Handling | Implement specific handling for edge cases and unexpected scenarios |
|
||||
|
||||
## Optimize performance:
|
||||
|
||||
| Performance Optimization | Description |
|
||||
|------------------------|-------------|
|
||||
| Concurrent Processing | Utilize parallel processing capabilities when tasks can be executed simultaneously |
|
||||
| Max Loops Configuration | Set appropriate iteration limits based on task complexity and requirements |
|
||||
| Resource Management | Continuously monitor and optimize system resource utilization |
|
||||
|
||||
## Example Implementation
|
||||
|
||||
Here's a complete example showing how to use SwarmRouter in a real-world scenario:
|
||||
|
||||
```python
|
||||
import os
|
||||
from swarms import Agent
|
||||
from swarms.structs.swarm_router import SwarmRouter, SwarmType
|
||||
|
||||
# Initialize specialized agents
|
||||
research_agent = Agent(
|
||||
agent_name="ResearchAgent",
|
||||
system_prompt="You are a research specialist...",
|
||||
model_name="gpt-4o",
|
||||
max_loops=1
|
||||
)
|
||||
|
||||
analysis_agent = Agent(
|
||||
agent_name="AnalysisAgent",
|
||||
system_prompt="You are an analysis expert...",
|
||||
model_name="gpt-4o",
|
||||
max_loops=1
|
||||
)
|
||||
|
||||
summary_agent = Agent(
|
||||
agent_name="SummaryAgent",
|
||||
system_prompt="You are a summarization specialist...",
|
||||
model_name="gpt-4o",
|
||||
max_loops=1
|
||||
)
|
||||
|
||||
# Create router with sequential workflow
|
||||
router = SwarmRouter(
|
||||
name="ResearchAnalysisRouter",
|
||||
description="Process research and analysis tasks",
|
||||
agents=[research_agent, analysis_agent, summary_agent],
|
||||
swarm_type=SwarmType.SequentialWorkflow,
|
||||
max_loops=1,
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Run complex task
|
||||
try:
|
||||
result = router.run(
|
||||
"Research and analyze the impact of AI on healthcare, "
|
||||
"providing a comprehensive summary of findings."
|
||||
)
|
||||
print("Task Result:", result)
|
||||
|
||||
# Print logs
|
||||
for log in router.get_logs():
|
||||
print(f"{log.timestamp} - {log.level}: {log.message}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error processing task: {str(e)}")
|
||||
```
|
||||
|
||||
This comprehensive guide demonstrates how to effectively use the SwarmRouter in various scenarios, making it easier to manage and orchestrate multiple agents for complex tasks.
|
Loading…
Reference in new issue