commit
3197b3a4b6
@ -0,0 +1,28 @@
|
|||||||
|
# Meme Agent Builder
|
||||||
|
|
||||||
|
- `pip3 install -U swarms`
|
||||||
|
- Add your OpenAI API key to the `.env` file with `OPENAI_API_KEY=your_api_key`
|
||||||
|
- Run the script
|
||||||
|
- Multiple agents will be created and saved to the `meme_agents` folder
|
||||||
|
- A swarm architecture will be selected autonomously and executed
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms.structs.meme_agent_persona_generator import (
|
||||||
|
MemeAgentGenerator,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
example = MemeAgentGenerator(
|
||||||
|
name="Meme-Swarm",
|
||||||
|
description="A swarm of specialized AI agents collaborating on generating and sharing memes around cool media from 2001s",
|
||||||
|
max_loops=1,
|
||||||
|
)
|
||||||
|
|
||||||
|
print(
|
||||||
|
example.run(
|
||||||
|
"Generate funny meme agents around cool media from 2001s"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
```
|
@ -0,0 +1,37 @@
|
|||||||
|
# Swarms Tools Example with HTX + CoinGecko
|
||||||
|
|
||||||
|
- `pip3 install swarms swarms-tools`
|
||||||
|
- Add `OPENAI_API_KEY` to your `.env` file
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent
|
||||||
|
from swarms.prompts.finance_agent_sys_prompt import (
|
||||||
|
FINANCIAL_AGENT_SYS_PROMPT,
|
||||||
|
)
|
||||||
|
from swarms_tools import (
|
||||||
|
coin_gecko_coin_api,
|
||||||
|
fetch_htx_data,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# Initialize the agent
|
||||||
|
agent = Agent(
|
||||||
|
agent_name="Financial-Analysis-Agent",
|
||||||
|
agent_description="Personal finance advisor agent",
|
||||||
|
system_prompt=FINANCIAL_AGENT_SYS_PROMPT,
|
||||||
|
max_loops=1,
|
||||||
|
model_name="gpt-4o",
|
||||||
|
dynamic_temperature_enabled=True,
|
||||||
|
user_name="swarms_corp",
|
||||||
|
return_step_meta=False,
|
||||||
|
output_type="str", # "json", "dict", "csv" OR "string" "yaml" and
|
||||||
|
auto_generate_prompt=False, # Auto generate prompt for the agent based on name, description, and system prompt, task
|
||||||
|
max_tokens=4000, # max output tokens
|
||||||
|
saved_state_path="agent_00.json",
|
||||||
|
interactive=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
agent.run(
|
||||||
|
f"Analyze the $swarms token on HTX with data: {fetch_htx_data('swarms')}. Additionally, consider the following CoinGecko data: {coin_gecko_coin_api('swarms')}"
|
||||||
|
)
|
||||||
|
```
|
@ -0,0 +1,43 @@
|
|||||||
|
# Swarms Tools Example with HTX + CoinGecko
|
||||||
|
|
||||||
|
- `pip3 install swarms swarms-tools`
|
||||||
|
- Add `OPENAI_API_KEY` to your `.env` file
|
||||||
|
- Run `swarms_tools_htx_gecko.py`
|
||||||
|
- Agent will make a function call to the desired tool
|
||||||
|
- The tool will be executed and the result will be returned to the agent
|
||||||
|
- The agent will then analyze the result and return the final output
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent
|
||||||
|
from swarms.prompts.finance_agent_sys_prompt import (
|
||||||
|
FINANCIAL_AGENT_SYS_PROMPT,
|
||||||
|
)
|
||||||
|
from swarms_tools import (
|
||||||
|
fetch_stock_news,
|
||||||
|
coin_gecko_coin_api,
|
||||||
|
fetch_htx_data,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Initialize the agent
|
||||||
|
agent = Agent(
|
||||||
|
agent_name="Financial-Analysis-Agent",
|
||||||
|
agent_description="Personal finance advisor agent",
|
||||||
|
system_prompt=FINANCIAL_AGENT_SYS_PROMPT,
|
||||||
|
max_loops=1,
|
||||||
|
model_name="gpt-4o",
|
||||||
|
dynamic_temperature_enabled=True,
|
||||||
|
user_name="swarms_corp",
|
||||||
|
retry_attempts=3,
|
||||||
|
context_length=8192,
|
||||||
|
return_step_meta=False,
|
||||||
|
output_type="str", # "json", "dict", "csv" OR "string" "yaml" and
|
||||||
|
auto_generate_prompt=False, # Auto generate prompt for the agent based on name, description, and system prompt, task
|
||||||
|
max_tokens=4000, # max output tokens
|
||||||
|
saved_state_path="agent_00.json",
|
||||||
|
interactive=False,
|
||||||
|
tools=[fetch_stock_news, coin_gecko_coin_api, fetch_htx_data],
|
||||||
|
)
|
||||||
|
|
||||||
|
agent.run("Analyze the $swarms token on htx")
|
||||||
|
```
|
@ -0,0 +1,42 @@
|
|||||||
|
# Swarms Tools Example with Yahoo Finance
|
||||||
|
|
||||||
|
- `pip3 install swarms swarms-tools`
|
||||||
|
- Add `OPENAI_API_KEY` to your `.env` file
|
||||||
|
- Run `yahoo_finance_agent.py`
|
||||||
|
- Agent will make a function call to the desired tool
|
||||||
|
- The tool will be executed and the result will be returned to the agent
|
||||||
|
- The agent will then analyze the result and return the final output
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent
|
||||||
|
from swarms.prompts.finance_agent_sys_prompt import (
|
||||||
|
FINANCIAL_AGENT_SYS_PROMPT,
|
||||||
|
)
|
||||||
|
from swarms_tools import (
|
||||||
|
yahoo_finance_api,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Initialize the agent
|
||||||
|
agent = Agent(
|
||||||
|
agent_name="Financial-Analysis-Agent",
|
||||||
|
agent_description="Personal finance advisor agent",
|
||||||
|
system_prompt=FINANCIAL_AGENT_SYS_PROMPT,
|
||||||
|
max_loops=1,
|
||||||
|
model_name="gpt-4o",
|
||||||
|
dynamic_temperature_enabled=True,
|
||||||
|
user_name="swarms_corp",
|
||||||
|
retry_attempts=3,
|
||||||
|
context_length=8192,
|
||||||
|
return_step_meta=False,
|
||||||
|
output_type="str", # "json", "dict", "csv" OR "string" "yaml" and
|
||||||
|
auto_generate_prompt=False, # Auto generate prompt for the agent based on name, description, and system prompt, task
|
||||||
|
max_tokens=4000, # max output tokens
|
||||||
|
saved_state_path="agent_00.json",
|
||||||
|
interactive=False,
|
||||||
|
tools=[yahoo_finance_api],
|
||||||
|
)
|
||||||
|
|
||||||
|
agent.run("Analyze the latest metrics for nvidia")
|
||||||
|
# Less than 30 lines of code....
|
||||||
|
```
|
@ -0,0 +1,247 @@
|
|||||||
|
# MatrixSwarm
|
||||||
|
|
||||||
|
The `MatrixSwarm` class provides a framework for managing and operating on matrices of AI agents, enabling matrix-like operations similar to linear algebra. This allows for complex agent interactions and parallel processing capabilities.
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
`MatrixSwarm` treats AI agents as elements in a matrix, allowing for operations like addition, multiplication, and transposition. This approach enables sophisticated agent orchestration and parallel processing patterns.
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pip3 install -U swarms
|
||||||
|
```
|
||||||
|
|
||||||
|
## Basic Usage
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent
|
||||||
|
from swarms.matrix import MatrixSwarm
|
||||||
|
|
||||||
|
# Create a 2x2 matrix of agents
|
||||||
|
agents = [
|
||||||
|
[Agent(agent_name="Agent-0-0"), Agent(agent_name="Agent-0-1")],
|
||||||
|
[Agent(agent_name="Agent-1-0"), Agent(agent_name="Agent-1-1")]
|
||||||
|
]
|
||||||
|
|
||||||
|
# Initialize the matrix
|
||||||
|
matrix = MatrixSwarm(agents)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Class Constructor
|
||||||
|
|
||||||
|
```python
|
||||||
|
def __init__(self, agents: List[List[Agent]])
|
||||||
|
```
|
||||||
|
|
||||||
|
### Parameters
|
||||||
|
- `agents` (`List[List[Agent]]`): A 2D list of Agent instances representing the matrix.
|
||||||
|
|
||||||
|
### Raises
|
||||||
|
- `ValueError`: If the input is not a valid 2D list of Agent instances.
|
||||||
|
|
||||||
|
## Methods
|
||||||
|
|
||||||
|
### transpose()
|
||||||
|
|
||||||
|
Transposes the matrix of agents by swapping rows and columns.
|
||||||
|
|
||||||
|
```python
|
||||||
|
def transpose(self) -> MatrixSwarm
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Returns
|
||||||
|
- `MatrixSwarm`: A new MatrixSwarm instance with transposed dimensions.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### add(other)
|
||||||
|
|
||||||
|
Performs element-wise addition of two agent matrices.
|
||||||
|
|
||||||
|
```python
|
||||||
|
def add(self, other: MatrixSwarm) -> MatrixSwarm
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Parameters
|
||||||
|
- `other` (`MatrixSwarm`): Another MatrixSwarm instance to add.
|
||||||
|
|
||||||
|
#### Returns
|
||||||
|
- `MatrixSwarm`: A new MatrixSwarm resulting from the addition.
|
||||||
|
|
||||||
|
#### Raises
|
||||||
|
- `ValueError`: If matrix dimensions are incompatible.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### scalar_multiply(scalar)
|
||||||
|
|
||||||
|
Scales the matrix by duplicating agents along rows.
|
||||||
|
|
||||||
|
```python
|
||||||
|
def scalar_multiply(self, scalar: int) -> MatrixSwarm
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Parameters
|
||||||
|
- `scalar` (`int`): The multiplication factor.
|
||||||
|
|
||||||
|
#### Returns
|
||||||
|
- `MatrixSwarm`: A new MatrixSwarm with scaled dimensions.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### multiply(other, inputs)
|
||||||
|
|
||||||
|
Performs matrix multiplication (dot product) between two agent matrices.
|
||||||
|
|
||||||
|
```python
|
||||||
|
def multiply(self, other: MatrixSwarm, inputs: List[str]) -> List[List[AgentOutput]]
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Parameters
|
||||||
|
- `other` (`MatrixSwarm`): The second MatrixSwarm for multiplication.
|
||||||
|
- `inputs` (`List[str]`): Input queries for the agents.
|
||||||
|
|
||||||
|
#### Returns
|
||||||
|
- `List[List[AgentOutput]]`: Matrix of operation results.
|
||||||
|
|
||||||
|
#### Raises
|
||||||
|
- `ValueError`: If matrix dimensions are incompatible for multiplication.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### subtract(other)
|
||||||
|
|
||||||
|
Performs element-wise subtraction of two agent matrices.
|
||||||
|
|
||||||
|
```python
|
||||||
|
def subtract(self, other: MatrixSwarm) -> MatrixSwarm
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Parameters
|
||||||
|
- `other` (`MatrixSwarm`): Another MatrixSwarm to subtract.
|
||||||
|
|
||||||
|
#### Returns
|
||||||
|
- `MatrixSwarm`: A new MatrixSwarm resulting from the subtraction.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### identity(size)
|
||||||
|
|
||||||
|
Creates an identity matrix of agents.
|
||||||
|
|
||||||
|
```python
|
||||||
|
def identity(self, size: int) -> MatrixSwarm
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Parameters
|
||||||
|
- `size` (`int`): Size of the identity matrix (NxN).
|
||||||
|
|
||||||
|
#### Returns
|
||||||
|
- `MatrixSwarm`: An identity MatrixSwarm.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### determinant()
|
||||||
|
|
||||||
|
Computes the determinant of a square agent matrix.
|
||||||
|
|
||||||
|
```python
|
||||||
|
def determinant(self) -> Any
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Returns
|
||||||
|
- `Any`: The determinant result.
|
||||||
|
|
||||||
|
#### Raises
|
||||||
|
- `ValueError`: If the matrix is not square.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### save_to_file(path)
|
||||||
|
|
||||||
|
Saves the matrix structure and metadata to a JSON file.
|
||||||
|
|
||||||
|
```python
|
||||||
|
def save_to_file(self, path: str) -> None
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Parameters
|
||||||
|
- `path` (`str`): File path for saving the matrix data.
|
||||||
|
|
||||||
|
## Extended Example
|
||||||
|
|
||||||
|
Here's a comprehensive example demonstrating various MatrixSwarm operations:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent
|
||||||
|
from swarms.matrix import MatrixSwarm
|
||||||
|
|
||||||
|
# Create agents with specific configurations
|
||||||
|
agents = [
|
||||||
|
[
|
||||||
|
Agent(
|
||||||
|
agent_name=f"Agent-{i}-{j}",
|
||||||
|
system_prompt="Your system prompt here",
|
||||||
|
model_name="gpt-4",
|
||||||
|
max_loops=1,
|
||||||
|
verbose=True
|
||||||
|
) for j in range(2)
|
||||||
|
] for i in range(2)
|
||||||
|
]
|
||||||
|
|
||||||
|
# Initialize matrix
|
||||||
|
matrix = MatrixSwarm(agents)
|
||||||
|
|
||||||
|
# Example operations
|
||||||
|
transposed = matrix.transpose()
|
||||||
|
scaled = matrix.scalar_multiply(2)
|
||||||
|
|
||||||
|
# Run operations with inputs
|
||||||
|
inputs = ["Query 1", "Query 2"]
|
||||||
|
results = matrix.multiply(transposed, inputs)
|
||||||
|
|
||||||
|
# Save results
|
||||||
|
matrix.save_to_file("matrix_results.json")
|
||||||
|
```
|
||||||
|
|
||||||
|
## Output Schema
|
||||||
|
|
||||||
|
The `AgentOutput` class defines the structure for operation results:
|
||||||
|
|
||||||
|
```python
|
||||||
|
class AgentOutput(BaseModel):
|
||||||
|
agent_name: str
|
||||||
|
input_query: str
|
||||||
|
output_result: Any
|
||||||
|
metadata: dict
|
||||||
|
```
|
||||||
|
|
||||||
|
## Best Practices
|
||||||
|
|
||||||
|
1. **Initialization**
|
||||||
|
- Ensure all agents in the matrix are properly configured before initialization
|
||||||
|
- Validate matrix dimensions for your use case
|
||||||
|
|
||||||
|
2. **Operation Performance**
|
||||||
|
- Consider computational costs for large matrices
|
||||||
|
- Use appropriate batch sizes for inputs
|
||||||
|
|
||||||
|
3. **Error Handling**
|
||||||
|
- Implement proper error handling for agent operations
|
||||||
|
- Validate inputs before matrix operations
|
||||||
|
|
||||||
|
4. **Resource Management**
|
||||||
|
- Monitor agent resource usage in large matrices
|
||||||
|
- Implement proper cleanup procedures
|
||||||
|
|
||||||
|
## Limitations
|
||||||
|
|
||||||
|
- Matrix operations are constrained by the underlying agent capabilities
|
||||||
|
- Performance may vary based on agent configuration and complexity
|
||||||
|
- Resource usage scales with matrix dimensions
|
||||||
|
|
||||||
|
## See Also
|
||||||
|
|
||||||
|
- [Swarms Documentation](https://github.com/kyegomez/swarms)
|
||||||
|
- [Agent Class Reference](https://github.com/kyegomez/swarms/tree/main/swarms)
|
@ -0,0 +1,178 @@
|
|||||||
|
# Swarms Wallet API Documentation
|
||||||
|
|
||||||
|
This documentation covers the Swarms Wallet API routes for managing wallets, sending tokens, and checking transactions in the Swarms Platform.
|
||||||
|
|
||||||
|
## Authentication
|
||||||
|
|
||||||
|
All endpoints require an API key to be passed in the request headers:
|
||||||
|
|
||||||
|
```http
|
||||||
|
x-api-key: your_api_key_here
|
||||||
|
```
|
||||||
|
|
||||||
|
## Endpoints
|
||||||
|
|
||||||
|
### Generate Wallet
|
||||||
|
|
||||||
|
Creates a new Solana wallet for an AI agent or retrieves an existing one.
|
||||||
|
|
||||||
|
```http
|
||||||
|
POST https://swarms.world/api/solana/generate-wallet
|
||||||
|
```
|
||||||
|
|
||||||
|
**Response**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": true,
|
||||||
|
"data": {
|
||||||
|
"public_key": "string",
|
||||||
|
"wallet_type": "solana",
|
||||||
|
"swarms_token_address": "string"
|
||||||
|
},
|
||||||
|
"code": "SUCCESS_001"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Send Tokens
|
||||||
|
Sends SWARMS tokens with automatic tax handling.
|
||||||
|
|
||||||
|
```http
|
||||||
|
POST https://swarms.world/api/solana/send-tokens
|
||||||
|
```
|
||||||
|
|
||||||
|
**Request Body**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"recipientAddress": "string",
|
||||||
|
"amount": "number",
|
||||||
|
"solanaFee": "number" // Optional, default: 0.009
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Response**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": true,
|
||||||
|
"data": {
|
||||||
|
"signature": "string",
|
||||||
|
"details": {
|
||||||
|
"sender": "string",
|
||||||
|
"recipient": "string",
|
||||||
|
"daoAddress": "string",
|
||||||
|
"requestedSendAmount": "number",
|
||||||
|
"totalNeededFromAccount": "number",
|
||||||
|
"accountTax": "number",
|
||||||
|
"receivedTax": "number",
|
||||||
|
"recipientReceives": "number",
|
||||||
|
"taxBreakdown": "string",
|
||||||
|
"computeUnits": "number",
|
||||||
|
"priorityFee": "number"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"code": "SUCCESS_001"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Check Receipt
|
||||||
|
Verifies token receipt and checks balances.
|
||||||
|
|
||||||
|
```http
|
||||||
|
GET https://swarms.world/api/solana/check-receipt?amount={amount}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Response**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": true,
|
||||||
|
"data": {
|
||||||
|
"solana_address": "string",
|
||||||
|
"received": "number",
|
||||||
|
"expected": "number",
|
||||||
|
"matches": "boolean",
|
||||||
|
"balances": {
|
||||||
|
"sol": "number",
|
||||||
|
"swarms": "number"
|
||||||
|
},
|
||||||
|
"swarms_address": "string"
|
||||||
|
},
|
||||||
|
"code": "SUCCESS_001"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Get Metrics
|
||||||
|
Retrieves transaction metrics and history.
|
||||||
|
|
||||||
|
```http
|
||||||
|
GET https://swarms.world/api/solana/get-metrics
|
||||||
|
```
|
||||||
|
|
||||||
|
**Query Parameters**
|
||||||
|
- `page`: Page number (default: 1)
|
||||||
|
- `limit`: Items per page (default: 10, max: 100)
|
||||||
|
- `startDate`: Filter start date
|
||||||
|
- `endDate`: Filter end date
|
||||||
|
- `status`: Transaction status filter
|
||||||
|
- `type`: Transaction type filter
|
||||||
|
|
||||||
|
**Response**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": true,
|
||||||
|
"data": {
|
||||||
|
"transactions": [{
|
||||||
|
"id": "string",
|
||||||
|
"agent_id": "string",
|
||||||
|
"transaction_hash": "string",
|
||||||
|
"amount": "number",
|
||||||
|
"recipient": "string",
|
||||||
|
"status": "string",
|
||||||
|
"transaction_type": "string",
|
||||||
|
"created_at": "string"
|
||||||
|
}],
|
||||||
|
"pagination": {
|
||||||
|
"currentPage": "number",
|
||||||
|
"totalPages": "number",
|
||||||
|
"totalItems": "number",
|
||||||
|
"itemsPerPage": "number",
|
||||||
|
"hasMore": "boolean"
|
||||||
|
},
|
||||||
|
"metrics": {
|
||||||
|
"totalTransactions": "number",
|
||||||
|
"totalAmountSent": "number",
|
||||||
|
"totalSuccessfulTransactions": "number",
|
||||||
|
"totalFailedTransactions": "number"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"code": "SUCCESS_001"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Error Codes
|
||||||
|
|
||||||
|
| Code | Description |
|
||||||
|
|------|-------------|
|
||||||
|
| AUTH_001 | Missing API key |
|
||||||
|
| AUTH_002 | Invalid API key |
|
||||||
|
| BAL_001 | Insufficient SOL balance |
|
||||||
|
| BAL_002 | Insufficient token balance |
|
||||||
|
| WAL_001 | Wallet not found |
|
||||||
|
| REQ_001 | Missing required parameters |
|
||||||
|
| DB_001 | Database error |
|
||||||
|
| ERR_001 | Internal server error |
|
||||||
|
|
||||||
|
## Transaction Details
|
||||||
|
|
||||||
|
- Default SOL fee: 0.009 SOL
|
||||||
|
- SWARMS token tax: 2% from sender + 2% from sent amount
|
||||||
|
- All taxes are sent to the DAO treasury
|
||||||
|
- Token accounts are automatically created for new recipients
|
||||||
|
- Transactions use 'processed' commitment level
|
||||||
|
|
||||||
|
|
||||||
|
## Implementation Notes
|
||||||
|
|
||||||
|
- All token amounts should be provided in their natural units (not in lamports/raw units)
|
||||||
|
- SOL balances are returned in SOL (not lamports)
|
||||||
|
- Token accounts are automatically created for recipients if they don't exist
|
||||||
|
- All transactions include automatic tax handling for the DAO treasury
|
||||||
|
- Compute budget and priority fees are automatically managed for optimal transaction processing
|
@ -0,0 +1,204 @@
|
|||||||
|
# CreateNow API Documentation
|
||||||
|
|
||||||
|
Welcome to the CreateNow API documentation! This API enables developers to generate AI-powered content, including images, music, videos, and speech, using natural language prompts. Use the endpoints below to start generating content.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## **1. Claim Your API Key**
|
||||||
|
To use the API, you must first claim your API key. Visit the following link to create an account and get your API key:
|
||||||
|
|
||||||
|
### **Claim Your Key**
|
||||||
|
```
|
||||||
|
https://createnow.xyz/account
|
||||||
|
```
|
||||||
|
|
||||||
|
After signing up, your API key will be available in your account dashboard. Keep it secure and include it in your API requests as a Bearer token.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## **2. Generation Endpoint**
|
||||||
|
The generation endpoint allows you to create AI-generated content using natural language prompts.
|
||||||
|
|
||||||
|
### **Endpoint**
|
||||||
|
```
|
||||||
|
POST https://createnow.xyz/api/v1/generate
|
||||||
|
```
|
||||||
|
|
||||||
|
### **Authentication**
|
||||||
|
Include a Bearer token in the `Authorization` header for all requests:
|
||||||
|
```
|
||||||
|
Authorization: Bearer YOUR_API_KEY
|
||||||
|
```
|
||||||
|
|
||||||
|
### **Basic Usage**
|
||||||
|
The simplest way to use the API is to send a prompt. The system will automatically detect the appropriate media type.
|
||||||
|
|
||||||
|
#### **Example Request (Basic)**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"prompt": "a beautiful sunset over the ocean"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### **Advanced Options**
|
||||||
|
You can specify additional parameters for finer control over the output.
|
||||||
|
|
||||||
|
#### **Parameters**
|
||||||
|
| Parameter | Type | Description | Default |
|
||||||
|
|----------------|-----------|---------------------------------------------------------------------------------------------------|--------------|
|
||||||
|
| `prompt` | `string` | The natural language description of the content to generate. | Required |
|
||||||
|
| `type` | `string` | The type of content to generate (`image`, `music`, `video`, `speech`). | Auto-detect |
|
||||||
|
| `count` | `integer` | The number of outputs to generate (1-4). | 1 |
|
||||||
|
| `duration` | `integer` | Duration of audio or video content in seconds (applicable to `music` and `speech`). | N/A |
|
||||||
|
|
||||||
|
#### **Example Request (Advanced)**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"prompt": "create an upbeat jazz melody",
|
||||||
|
"type": "music",
|
||||||
|
"count": 2,
|
||||||
|
"duration": 30
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### **Response Format**
|
||||||
|
|
||||||
|
#### **Success Response**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": true,
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"url": "https://createnow.xyz/storage/image1.png",
|
||||||
|
"creation_id": "12345",
|
||||||
|
"share_url": "https://createnow.xyz/share/12345"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"mediaType": "image",
|
||||||
|
"confidence": 0.95,
|
||||||
|
"detected": true
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### **Error Response**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"error": "Invalid API Key",
|
||||||
|
"status": 401
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## **3. Examples in Multiple Languages**
|
||||||
|
|
||||||
|
### **Python**
|
||||||
|
```python
|
||||||
|
import requests
|
||||||
|
|
||||||
|
url = "https://createnow.xyz/api/v1/generate"
|
||||||
|
headers = {
|
||||||
|
"Authorization": "Bearer YOUR_API_KEY",
|
||||||
|
"Content-Type": "application/json"
|
||||||
|
}
|
||||||
|
|
||||||
|
payload = {
|
||||||
|
"prompt": "a futuristic cityscape at night",
|
||||||
|
"type": "image",
|
||||||
|
"count": 2
|
||||||
|
}
|
||||||
|
|
||||||
|
response = requests.post(url, json=payload, headers=headers)
|
||||||
|
print(response.json())
|
||||||
|
```
|
||||||
|
|
||||||
|
### **Node.js**
|
||||||
|
```javascript
|
||||||
|
const axios = require('axios');
|
||||||
|
|
||||||
|
const url = "https://createnow.xyz/api/v1/generate";
|
||||||
|
const headers = {
|
||||||
|
Authorization: "Bearer YOUR_API_KEY",
|
||||||
|
"Content-Type": "application/json"
|
||||||
|
};
|
||||||
|
|
||||||
|
const payload = {
|
||||||
|
prompt: "a futuristic cityscape at night",
|
||||||
|
type: "image",
|
||||||
|
count: 2
|
||||||
|
};
|
||||||
|
|
||||||
|
axios.post(url, payload, { headers })
|
||||||
|
.then(response => {
|
||||||
|
console.log(response.data);
|
||||||
|
})
|
||||||
|
.catch(error => {
|
||||||
|
console.error(error.response.data);
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
### **cURL**
|
||||||
|
```bash
|
||||||
|
curl -X POST https://createnow.xyz/api/v1/generate \
|
||||||
|
-H "Authorization: Bearer YOUR_API_KEY" \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{
|
||||||
|
"prompt": "a futuristic cityscape at night",
|
||||||
|
"type": "image",
|
||||||
|
"count": 2
|
||||||
|
}'
|
||||||
|
```
|
||||||
|
|
||||||
|
### **Java**
|
||||||
|
```java
|
||||||
|
import java.net.HttpURLConnection;
|
||||||
|
import java.net.URL;
|
||||||
|
import java.io.OutputStream;
|
||||||
|
|
||||||
|
public class CreateNowAPI {
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
URL url = new URL("https://createnow.xyz/api/v1/generate");
|
||||||
|
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
|
||||||
|
conn.setRequestMethod("POST");
|
||||||
|
conn.setRequestProperty("Authorization", "Bearer YOUR_API_KEY");
|
||||||
|
conn.setRequestProperty("Content-Type", "application/json");
|
||||||
|
conn.setDoOutput(true);
|
||||||
|
|
||||||
|
String jsonPayload = "{" +
|
||||||
|
"\"prompt\": \"a futuristic cityscape at night\", " +
|
||||||
|
"\"type\": \"image\", " +
|
||||||
|
"\"count\": 2}";
|
||||||
|
|
||||||
|
OutputStream os = conn.getOutputStream();
|
||||||
|
os.write(jsonPayload.getBytes());
|
||||||
|
os.flush();
|
||||||
|
|
||||||
|
int responseCode = conn.getResponseCode();
|
||||||
|
System.out.println("Response Code: " + responseCode);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## **4. Error Codes**
|
||||||
|
| Status Code | Meaning | Possible Causes |
|
||||||
|
|-------------|----------------------------------|----------------------------------------|
|
||||||
|
| 400 | Bad Request | Invalid parameters or payload. |
|
||||||
|
| 401 | Unauthorized | Invalid or missing API key. |
|
||||||
|
| 402 | Payment Required | Insufficient credits for the request. |
|
||||||
|
| 500 | Internal Server Error | Issue on the server side. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## **5. Notes and Limitations**
|
||||||
|
- **Maximum Prompt Length:** 1000 characters.
|
||||||
|
- **Maximum Outputs per Request:** 4.
|
||||||
|
- **Supported Media Types:** `image`, `music`, `video`, `speech`.
|
||||||
|
- **Content Shareability:** Every output includes a unique creation ID and shareable URL.
|
||||||
|
- **Auto-Detection:** Uses advanced natural language processing to determine the most appropriate media type.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
For further support or questions, please contact our support team at [support@createnow.xyz](mailto:support@createnow.xyz).
|
||||||
|
|
@ -0,0 +1,239 @@
|
|||||||
|
# Swarms Tools
|
||||||
|
|
||||||
|
|
||||||
|
Welcome to **Swarms Tools**, the ultimate package for integrating **cutting-edge APIs** into Python functions with seamless multi-agent system compatibility. Designed for enterprises at the forefront of innovation, **Swarms Tools** is your key to simplifying complexity and unlocking operational excellence.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🚀 Features
|
||||||
|
|
||||||
|
- **Unified API Integration**: Ready-to-use Python functions for financial data, social media, IoT, and more.
|
||||||
|
- **Enterprise-Grade Design**: Comprehensive type hints, structured outputs, and robust documentation.
|
||||||
|
- **Agent-Ready Framework**: Optimized for seamless integration into Swarms' multi-agent orchestration systems.
|
||||||
|
- **Expandable Architecture**: Easily extend functionality with a standardized schema for new tools.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🔧 Installation
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pip3 install -U swarms-tools
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📂 Directory Structure
|
||||||
|
|
||||||
|
```plaintext
|
||||||
|
swarms-tools/
|
||||||
|
├── swarms_tools/
|
||||||
|
│ ├── finance/
|
||||||
|
│ │ ├── htx_tool.py
|
||||||
|
│ │ ├── eodh_api.py
|
||||||
|
│ │ └── coingecko_tool.py
|
||||||
|
│ ├── social_media/
|
||||||
|
│ │ ├── telegram_tool.py
|
||||||
|
│ ├── utilities/
|
||||||
|
│ │ └── logging.py
|
||||||
|
├── tests/
|
||||||
|
│ ├── test_financial_data.py
|
||||||
|
│ └── test_social_media.py
|
||||||
|
└── README.md
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 💼 Use Cases
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## Finance
|
||||||
|
|
||||||
|
Explore our diverse range of financial tools, designed to streamline your operations. If you need a tool not listed, feel free to submit an issue or accelerate integration by contributing a pull request with your tool of choice.
|
||||||
|
|
||||||
|
| **Tool Name** | **Function** | **Description** |
|
||||||
|
|---------------------------|--------------------------|---------------------------------------------------------------------------------|
|
||||||
|
| `fetch_stock_news` | `fetch_stock_news` | Fetches the latest stock news and updates. |
|
||||||
|
| `fetch_htx_data` | `fetch_htx_data` | Retrieves financial data from the HTX platform. |
|
||||||
|
| `yahoo_finance_api` | `yahoo_finance_api` | Fetches comprehensive stock data from Yahoo Finance, including prices and trends. |
|
||||||
|
| `coin_gecko_coin_api` | `coin_gecko_coin_api` | Fetches cryptocurrency data from CoinGecko, including market and price information. |
|
||||||
|
| `helius_api_tool` | `helius_api_tool` | Retrieves blockchain account, transaction, or token data using the Helius API. |
|
||||||
|
| `okx_api_tool` | `okx_api_tool` | Fetches detailed cryptocurrency data for coins from the OKX exchange. |
|
||||||
|
|
||||||
|
|
||||||
|
### Financial Data Retrieval
|
||||||
|
Enable precise and actionable financial insights:
|
||||||
|
|
||||||
|
#### Example 1: Fetch Historical Data
|
||||||
|
```python
|
||||||
|
from swarms_tools import fetch_htx_data
|
||||||
|
|
||||||
|
# Fetch historical trading data for "Swarms Corporation"
|
||||||
|
response = fetch_htx_data("swarms")
|
||||||
|
print(response)
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Example 2: Stock News Analysis
|
||||||
|
```python
|
||||||
|
from swarms_tools import fetch_stock_news
|
||||||
|
|
||||||
|
# Retrieve latest stock news for Apple
|
||||||
|
news = fetch_stock_news("AAPL")
|
||||||
|
print(news)
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Example 3: Cryptocurrency Metrics
|
||||||
|
```python
|
||||||
|
from swarms_tools import coin_gecko_coin_api
|
||||||
|
|
||||||
|
# Fetch live data for Bitcoin
|
||||||
|
crypto_data = coin_gecko_coin_api("bitcoin")
|
||||||
|
print(crypto_data)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Social Media Automation
|
||||||
|
Streamline communication and engagement:
|
||||||
|
|
||||||
|
#### Example: Telegram Bot Messaging
|
||||||
|
```python
|
||||||
|
from swarms_tools import telegram_dm_or_tag_api
|
||||||
|
|
||||||
|
def send_alert(response: str):
|
||||||
|
telegram_dm_or_tag_api(response)
|
||||||
|
|
||||||
|
# Send a message to a user or group
|
||||||
|
send_alert("Mission-critical update from Swarms.")
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Dex Screener
|
||||||
|
|
||||||
|
This is a tool that allows you to fetch data from the Dex Screener API. It supports multiple chains and multiple tokens.
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms_tools.finance.dex_screener import (
|
||||||
|
fetch_latest_token_boosts,
|
||||||
|
fetch_dex_screener_profiles,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
fetch_dex_screener_profiles()
|
||||||
|
fetch_latest_token_boosts()
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
|
||||||
|
## Structs
|
||||||
|
The tool chainer enables the execution of multiple tools in a sequence, allowing for the aggregation of their results in either a parallel or sequential manner.
|
||||||
|
|
||||||
|
```python
|
||||||
|
# Example usage
|
||||||
|
from loguru import logger
|
||||||
|
|
||||||
|
from swarms_tools.structs import tool_chainer
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
logger.add("tool_chainer.log", rotation="500 MB", level="INFO")
|
||||||
|
|
||||||
|
# Example tools
|
||||||
|
def tool1():
|
||||||
|
return "Tool1 Result"
|
||||||
|
|
||||||
|
def tool2():
|
||||||
|
return "Tool2 Result"
|
||||||
|
|
||||||
|
# def tool3():
|
||||||
|
# raise ValueError("Simulated error in Tool3")
|
||||||
|
|
||||||
|
tools = [tool1, tool2]
|
||||||
|
|
||||||
|
# Parallel execution
|
||||||
|
parallel_results = tool_chainer(tools, parallel=True)
|
||||||
|
print("Parallel Results:", parallel_results)
|
||||||
|
|
||||||
|
# Sequential execution
|
||||||
|
# sequential_results = tool_chainer(tools, parallel=False)
|
||||||
|
# print("Sequential Results:", sequential_results)
|
||||||
|
|
||||||
|
```
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🧩 Standardized Schema
|
||||||
|
|
||||||
|
Every tool in **Swarms Tools** adheres to a strict schema for maintainability and interoperability:
|
||||||
|
|
||||||
|
### Schema Template
|
||||||
|
|
||||||
|
1. **Functionality**:
|
||||||
|
- Encapsulate API logic into a modular, reusable function.
|
||||||
|
|
||||||
|
2. **Typing**:
|
||||||
|
- Leverage Python type hints for input validation and clarity.
|
||||||
|
|
||||||
|
Example:
|
||||||
|
```python
|
||||||
|
def fetch_data(symbol: str, date_range: str) -> str:
|
||||||
|
"""
|
||||||
|
Fetch financial data for a given symbol and date range.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
symbol (str): Ticker symbol of the asset.
|
||||||
|
date_range (str): Timeframe for the data (e.g., '1d', '1m', '1y').
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
dict: A dictionary containing financial metrics.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **Documentation**:
|
||||||
|
- Include detailed docstrings with parameter explanations and usage examples.
|
||||||
|
|
||||||
|
4. **Output Standardization**:
|
||||||
|
- Ensure consistent outputs (e.g., strings) for easy downstream agent integration.
|
||||||
|
|
||||||
|
5. **API-Key Management**:
|
||||||
|
- All API keys must be fetched with `os.getenv("YOUR_KEY")`
|
||||||
|
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📖 Documentation
|
||||||
|
|
||||||
|
Comprehensive documentation is available to guide developers and enterprises. Visit our [official docs](https://docs.swarms.world) for detailed API references, usage examples, and best practices.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🛠 Contributing
|
||||||
|
|
||||||
|
We welcome contributions from the global developer community. To contribute:
|
||||||
|
|
||||||
|
1. **Fork the Repository**: Start by forking the repository.
|
||||||
|
2. **Create a Feature Branch**: Use a descriptive branch name: `feature/add-new-tool`.
|
||||||
|
3. **Commit Your Changes**: Write meaningful commit messages.
|
||||||
|
4. **Submit a Pull Request**: Open a pull request for review.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🛡️ License
|
||||||
|
|
||||||
|
This project is licensed under the **MIT License**. See the [LICENSE](LICENSE) file for details.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🌠 Join the Future
|
||||||
|
|
||||||
|
Explore the limitless possibilities of agent-based systems. Together, we can build a smarter, faster, and more interconnected world.
|
||||||
|
|
||||||
|
**Visit us:** [Swarms Corporation](https://swarms.ai)
|
||||||
|
**Follow us:** [Twitter](https://twitter.com/swarms_corp)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**"The future belongs to those who dare to automate it."**
|
||||||
|
**— The Swarms Corporation**
|
||||||
|
|
@ -0,0 +1,17 @@
|
|||||||
|
from swarms.structs.meme_agent_persona_generator import (
|
||||||
|
MemeAgentGenerator,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
example = MemeAgentGenerator(
|
||||||
|
name="Meme-Swarm",
|
||||||
|
description="A swarm of specialized AI agents collaborating on generating and sharing memes around cool media from 2001s",
|
||||||
|
max_loops=1,
|
||||||
|
)
|
||||||
|
|
||||||
|
print(
|
||||||
|
example.run(
|
||||||
|
"Generate funny meme agents around cool media from 2001s"
|
||||||
|
)
|
||||||
|
)
|
@ -0,0 +1,23 @@
|
|||||||
|
from swarms import Agent
|
||||||
|
|
||||||
|
from swarms_tools.finance.dex_screener import (
|
||||||
|
fetch_dex_screener_profiles,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Initialize the agent
|
||||||
|
agent = Agent(
|
||||||
|
agent_name="Financial-Analysis-Agent",
|
||||||
|
agent_description="Personal finance advisor agent",
|
||||||
|
max_loops=1,
|
||||||
|
model_name="gpt-4o",
|
||||||
|
dynamic_temperature_enabled=True,
|
||||||
|
user_name="swarms_corp",
|
||||||
|
return_step_meta=False,
|
||||||
|
output_type="str", # "json", "dict", "csv" OR "string" "yaml" and
|
||||||
|
auto_generate_prompt=False, # Auto generate prompt for the agent based on name, description, and system prompt, task
|
||||||
|
interactive=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
token_profiles = fetch_dex_screener_profiles()
|
||||||
|
prompt = f"Using data from DexScreener, analyze the latest tokens and provide a detailed analysis with top 5 tokens based on their potential, considering both their profiles and recent boosts. The token profiles are sourced from DexScreener's token profiles API, while the token boosts are sourced from DexScreener's latest token boosts API. {str(token_profiles)}"
|
||||||
|
agent.run(prompt)
|
@ -0,0 +1,30 @@
|
|||||||
|
from swarms import Agent
|
||||||
|
from swarms.prompts.finance_agent_sys_prompt import (
|
||||||
|
FINANCIAL_AGENT_SYS_PROMPT,
|
||||||
|
)
|
||||||
|
from swarms_tools import (
|
||||||
|
yahoo_finance_api,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Initialize the agent
|
||||||
|
agent = Agent(
|
||||||
|
agent_name="Financial-Analysis-Agent",
|
||||||
|
agent_description="Personal finance advisor agent",
|
||||||
|
system_prompt=FINANCIAL_AGENT_SYS_PROMPT,
|
||||||
|
max_loops=1,
|
||||||
|
model_name="gpt-4o",
|
||||||
|
dynamic_temperature_enabled=True,
|
||||||
|
user_name="swarms_corp",
|
||||||
|
retry_attempts=3,
|
||||||
|
context_length=8192,
|
||||||
|
return_step_meta=False,
|
||||||
|
output_type="str", # "json", "dict", "csv" OR "string" "yaml" and
|
||||||
|
auto_generate_prompt=False, # Auto generate prompt for the agent based on name, description, and system prompt, task
|
||||||
|
max_tokens=4000, # max output tokens
|
||||||
|
saved_state_path="agent_00.json",
|
||||||
|
interactive=False,
|
||||||
|
tools=[yahoo_finance_api],
|
||||||
|
)
|
||||||
|
|
||||||
|
agent.run("Analyze the latest metrics for nvidia")
|
||||||
|
# Less than 30 lines of code....
|
@ -0,0 +1,30 @@
|
|||||||
|
from swarms import Agent
|
||||||
|
from swarms.prompts.finance_agent_sys_prompt import (
|
||||||
|
FINANCIAL_AGENT_SYS_PROMPT,
|
||||||
|
)
|
||||||
|
from swarms_tools import (
|
||||||
|
coin_gecko_coin_api,
|
||||||
|
fetch_htx_data,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# Initialize the agent
|
||||||
|
agent = Agent(
|
||||||
|
agent_name="Financial-Analysis-Agent",
|
||||||
|
agent_description="Personal finance advisor agent",
|
||||||
|
system_prompt=FINANCIAL_AGENT_SYS_PROMPT,
|
||||||
|
max_loops=1,
|
||||||
|
model_name="gpt-4o",
|
||||||
|
dynamic_temperature_enabled=True,
|
||||||
|
user_name="swarms_corp",
|
||||||
|
return_step_meta=False,
|
||||||
|
output_type="str", # "json", "dict", "csv" OR "string" "yaml" and
|
||||||
|
auto_generate_prompt=False, # Auto generate prompt for the agent based on name, description, and system prompt, task
|
||||||
|
max_tokens=4000, # max output tokens
|
||||||
|
saved_state_path="agent_00.json",
|
||||||
|
interactive=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
agent.run(
|
||||||
|
f"Analyze the $swarms token on HTX with data: {fetch_htx_data('swarms')}. Additionally, consider the following CoinGecko data: {coin_gecko_coin_api('swarms')}"
|
||||||
|
)
|
@ -0,0 +1,31 @@
|
|||||||
|
from swarms import Agent
|
||||||
|
from swarms.prompts.finance_agent_sys_prompt import (
|
||||||
|
FINANCIAL_AGENT_SYS_PROMPT,
|
||||||
|
)
|
||||||
|
from swarms_tools import (
|
||||||
|
fetch_stock_news,
|
||||||
|
coin_gecko_coin_api,
|
||||||
|
fetch_htx_data,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Initialize the agent
|
||||||
|
agent = Agent(
|
||||||
|
agent_name="Financial-Analysis-Agent",
|
||||||
|
agent_description="Personal finance advisor agent",
|
||||||
|
system_prompt=FINANCIAL_AGENT_SYS_PROMPT,
|
||||||
|
max_loops=1,
|
||||||
|
model_name="gpt-4o",
|
||||||
|
dynamic_temperature_enabled=True,
|
||||||
|
user_name="swarms_corp",
|
||||||
|
retry_attempts=3,
|
||||||
|
context_length=8192,
|
||||||
|
return_step_meta=False,
|
||||||
|
output_type="str", # "json", "dict", "csv" OR "string" "yaml" and
|
||||||
|
auto_generate_prompt=False, # Auto generate prompt for the agent based on name, description, and system prompt, task
|
||||||
|
max_tokens=4000, # max output tokens
|
||||||
|
saved_state_path="agent_00.json",
|
||||||
|
interactive=False,
|
||||||
|
tools=[fetch_stock_news, coin_gecko_coin_api, fetch_htx_data],
|
||||||
|
)
|
||||||
|
|
||||||
|
agent.run("Analyze the $swarms token on htx")
|
@ -0,0 +1,33 @@
|
|||||||
|
from swarms.utils.formatter import formatter
|
||||||
|
|
||||||
|
|
||||||
|
def agent_print(
|
||||||
|
agent_name: str,
|
||||||
|
response: str = None,
|
||||||
|
loop_count: int = None,
|
||||||
|
streaming_on: bool = False,
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Prints the response from an agent based on the streaming mode.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
agent_name (str): The name of the agent.
|
||||||
|
response (str): The response from the agent.
|
||||||
|
loop_count (int): The maximum number of loops.
|
||||||
|
streaming_on (bool): Indicates if streaming is on or off.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: The response from the agent.
|
||||||
|
"""
|
||||||
|
if streaming_on:
|
||||||
|
formatter.print_panel_token_by_token(
|
||||||
|
f"{agent_name}: {response}",
|
||||||
|
title=f"Agent Name: {agent_name} [Max Loops: {loop_count}]",
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
formatter.print_panel(
|
||||||
|
f"{agent_name}: {response}",
|
||||||
|
f"Agent Name {agent_name} [Max Loops: {loop_count} ]",
|
||||||
|
)
|
||||||
|
|
||||||
|
return response
|
@ -0,0 +1,318 @@
|
|||||||
|
import base64
|
||||||
|
import json
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from typing import Optional, Union, Dict, List
|
||||||
|
|
||||||
|
from cryptography.fernet import Fernet
|
||||||
|
from cryptography.hazmat.primitives import hashes, serialization
|
||||||
|
from cryptography.hazmat.primitives.asymmetric import padding, rsa
|
||||||
|
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class EncryptedMessage:
|
||||||
|
"""Structure for encrypted messages between agents"""
|
||||||
|
|
||||||
|
sender_id: str
|
||||||
|
receiver_id: str
|
||||||
|
encrypted_content: bytes
|
||||||
|
timestamp: float
|
||||||
|
message_id: str
|
||||||
|
session_id: str
|
||||||
|
|
||||||
|
|
||||||
|
class EncryptionSession:
|
||||||
|
"""Represents an encrypted communication session between agents"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
session_id: str,
|
||||||
|
agent_ids: List[str],
|
||||||
|
encrypted_keys: Dict[str, bytes],
|
||||||
|
created_at: datetime,
|
||||||
|
):
|
||||||
|
self.session_id = session_id
|
||||||
|
self.agent_ids = agent_ids
|
||||||
|
self.encrypted_keys = encrypted_keys
|
||||||
|
self.created_at = created_at
|
||||||
|
|
||||||
|
|
||||||
|
class AgentEncryption:
|
||||||
|
"""
|
||||||
|
Handles encryption for agent data both at rest and in transit.
|
||||||
|
Supports both symmetric (for data at rest) and asymmetric (for data in transit) encryption.
|
||||||
|
Also supports secure multi-agent communication.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
agent_id: Optional[str] = None,
|
||||||
|
encryption_key: Optional[str] = None,
|
||||||
|
enable_transit_encryption: bool = False,
|
||||||
|
enable_rest_encryption: bool = False,
|
||||||
|
enable_multi_agent: bool = False,
|
||||||
|
):
|
||||||
|
self.agent_id = agent_id or str(uuid.uuid4())
|
||||||
|
self.enable_transit_encryption = enable_transit_encryption
|
||||||
|
self.enable_rest_encryption = enable_rest_encryption
|
||||||
|
self.enable_multi_agent = enable_multi_agent
|
||||||
|
|
||||||
|
# Multi-agent communication storage
|
||||||
|
self.sessions: Dict[str, EncryptionSession] = {}
|
||||||
|
self.known_agents: Dict[str, "AgentEncryption"] = {}
|
||||||
|
|
||||||
|
if enable_rest_encryption:
|
||||||
|
# Initialize encryption for data at rest
|
||||||
|
if encryption_key:
|
||||||
|
self.encryption_key = base64.urlsafe_b64encode(
|
||||||
|
PBKDF2HMAC(
|
||||||
|
algorithm=hashes.SHA256(),
|
||||||
|
length=32,
|
||||||
|
salt=f"agent_{self.agent_id}".encode(), # Unique salt per agent
|
||||||
|
iterations=100000,
|
||||||
|
).derive(encryption_key.encode())
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
self.encryption_key = Fernet.generate_key()
|
||||||
|
|
||||||
|
self.cipher_suite = Fernet(self.encryption_key)
|
||||||
|
|
||||||
|
if enable_transit_encryption or enable_multi_agent:
|
||||||
|
# Generate RSA key pair for transit encryption
|
||||||
|
self.private_key = rsa.generate_private_key(
|
||||||
|
public_exponent=65537, key_size=2048
|
||||||
|
)
|
||||||
|
self.public_key = self.private_key.public_key()
|
||||||
|
|
||||||
|
def register_agent(
|
||||||
|
self, agent_id: str, agent_encryption: "AgentEncryption"
|
||||||
|
) -> None:
|
||||||
|
"""Register another agent for secure communication"""
|
||||||
|
if not self.enable_multi_agent:
|
||||||
|
raise ValueError("Multi-agent support is not enabled")
|
||||||
|
self.known_agents[agent_id] = agent_encryption
|
||||||
|
|
||||||
|
def create_session(self, agent_ids: List[str]) -> str:
|
||||||
|
"""Create a new encrypted session between multiple agents"""
|
||||||
|
if not self.enable_multi_agent:
|
||||||
|
raise ValueError("Multi-agent support is not enabled")
|
||||||
|
|
||||||
|
session_id = str(uuid.uuid4())
|
||||||
|
|
||||||
|
# Generate a shared session key
|
||||||
|
session_key = Fernet.generate_key()
|
||||||
|
|
||||||
|
# Create encrypted copies of the session key for each agent
|
||||||
|
encrypted_keys = {}
|
||||||
|
for agent_id in agent_ids:
|
||||||
|
if (
|
||||||
|
agent_id not in self.known_agents
|
||||||
|
and agent_id != self.agent_id
|
||||||
|
):
|
||||||
|
raise ValueError(f"Agent {agent_id} not registered")
|
||||||
|
|
||||||
|
if agent_id == self.agent_id:
|
||||||
|
agent_public_key = self.public_key
|
||||||
|
else:
|
||||||
|
agent_public_key = self.known_agents[
|
||||||
|
agent_id
|
||||||
|
].public_key
|
||||||
|
|
||||||
|
encrypted_key = agent_public_key.encrypt(
|
||||||
|
session_key,
|
||||||
|
padding.OAEP(
|
||||||
|
mgf=padding.MGF1(algorithm=hashes.SHA256()),
|
||||||
|
algorithm=hashes.SHA256(),
|
||||||
|
label=None,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
encrypted_keys[agent_id] = encrypted_key
|
||||||
|
|
||||||
|
# Store session information
|
||||||
|
self.sessions[session_id] = EncryptionSession(
|
||||||
|
session_id=session_id,
|
||||||
|
agent_ids=agent_ids,
|
||||||
|
encrypted_keys=encrypted_keys,
|
||||||
|
created_at=datetime.now(),
|
||||||
|
)
|
||||||
|
|
||||||
|
return session_id
|
||||||
|
|
||||||
|
def encrypt_message(
|
||||||
|
self,
|
||||||
|
content: Union[str, dict],
|
||||||
|
receiver_id: str,
|
||||||
|
session_id: str,
|
||||||
|
) -> EncryptedMessage:
|
||||||
|
"""Encrypt a message for another agent within a session"""
|
||||||
|
if not self.enable_multi_agent:
|
||||||
|
raise ValueError("Multi-agent support is not enabled")
|
||||||
|
|
||||||
|
if session_id not in self.sessions:
|
||||||
|
raise ValueError("Invalid session ID")
|
||||||
|
|
||||||
|
session = self.sessions[session_id]
|
||||||
|
if (
|
||||||
|
self.agent_id not in session.agent_ids
|
||||||
|
or receiver_id not in session.agent_ids
|
||||||
|
):
|
||||||
|
raise ValueError("Sender or receiver not in session")
|
||||||
|
|
||||||
|
# Serialize content if it's a dictionary
|
||||||
|
if isinstance(content, dict):
|
||||||
|
content = json.dumps(content)
|
||||||
|
|
||||||
|
# Get the session key
|
||||||
|
encrypted_session_key = session.encrypted_keys[self.agent_id]
|
||||||
|
session_key = self.decrypt_session_key(encrypted_session_key)
|
||||||
|
|
||||||
|
# Create Fernet cipher with session key
|
||||||
|
cipher = Fernet(session_key)
|
||||||
|
|
||||||
|
# Encrypt the message
|
||||||
|
encrypted_content = cipher.encrypt(content.encode())
|
||||||
|
|
||||||
|
return EncryptedMessage(
|
||||||
|
sender_id=self.agent_id,
|
||||||
|
receiver_id=receiver_id,
|
||||||
|
encrypted_content=encrypted_content,
|
||||||
|
timestamp=datetime.now().timestamp(),
|
||||||
|
message_id=str(uuid.uuid4()),
|
||||||
|
session_id=session_id,
|
||||||
|
)
|
||||||
|
|
||||||
|
def decrypt_message(
|
||||||
|
self, message: EncryptedMessage
|
||||||
|
) -> Union[str, dict]:
|
||||||
|
"""Decrypt a message from another agent"""
|
||||||
|
if not self.enable_multi_agent:
|
||||||
|
raise ValueError("Multi-agent support is not enabled")
|
||||||
|
|
||||||
|
if message.session_id not in self.sessions:
|
||||||
|
raise ValueError("Invalid session ID")
|
||||||
|
|
||||||
|
if self.agent_id != message.receiver_id:
|
||||||
|
raise ValueError("Message not intended for this agent")
|
||||||
|
|
||||||
|
session = self.sessions[message.session_id]
|
||||||
|
|
||||||
|
# Get the session key
|
||||||
|
encrypted_session_key = session.encrypted_keys[self.agent_id]
|
||||||
|
session_key = self.decrypt_session_key(encrypted_session_key)
|
||||||
|
|
||||||
|
# Create Fernet cipher with session key
|
||||||
|
cipher = Fernet(session_key)
|
||||||
|
|
||||||
|
# Decrypt the message
|
||||||
|
decrypted_content = cipher.decrypt(
|
||||||
|
message.encrypted_content
|
||||||
|
).decode()
|
||||||
|
|
||||||
|
# Try to parse as JSON
|
||||||
|
try:
|
||||||
|
return json.loads(decrypted_content)
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
return decrypted_content
|
||||||
|
|
||||||
|
def decrypt_session_key(self, encrypted_key: bytes) -> bytes:
|
||||||
|
"""Decrypt a session key using the agent's private key"""
|
||||||
|
return self.private_key.decrypt(
|
||||||
|
encrypted_key,
|
||||||
|
padding.OAEP(
|
||||||
|
mgf=padding.MGF1(algorithm=hashes.SHA256()),
|
||||||
|
algorithm=hashes.SHA256(),
|
||||||
|
label=None,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
# Original methods preserved below
|
||||||
|
def encrypt_at_rest(self, data: Union[str, dict, bytes]) -> bytes:
|
||||||
|
"""Encrypts data for storage"""
|
||||||
|
if not self.enable_rest_encryption:
|
||||||
|
return (
|
||||||
|
data
|
||||||
|
if isinstance(data, bytes)
|
||||||
|
else str(data).encode()
|
||||||
|
)
|
||||||
|
|
||||||
|
if isinstance(data, dict):
|
||||||
|
data = json.dumps(data)
|
||||||
|
if isinstance(data, str):
|
||||||
|
data = data.encode()
|
||||||
|
|
||||||
|
return self.cipher_suite.encrypt(data)
|
||||||
|
|
||||||
|
def decrypt_at_rest(
|
||||||
|
self, encrypted_data: bytes
|
||||||
|
) -> Union[str, dict]:
|
||||||
|
"""Decrypts stored data"""
|
||||||
|
if not self.enable_rest_encryption:
|
||||||
|
return encrypted_data.decode()
|
||||||
|
|
||||||
|
decrypted_data = self.cipher_suite.decrypt(encrypted_data)
|
||||||
|
|
||||||
|
try:
|
||||||
|
return json.loads(decrypted_data)
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
return decrypted_data.decode()
|
||||||
|
|
||||||
|
def encrypt_for_transit(self, data: Union[str, dict]) -> bytes:
|
||||||
|
"""Encrypts data for transmission"""
|
||||||
|
if not self.enable_transit_encryption:
|
||||||
|
return str(data).encode()
|
||||||
|
|
||||||
|
if isinstance(data, dict):
|
||||||
|
data = json.dumps(data)
|
||||||
|
|
||||||
|
return self.public_key.encrypt(
|
||||||
|
data.encode(),
|
||||||
|
padding.OAEP(
|
||||||
|
mgf=padding.MGF1(algorithm=hashes.SHA256()),
|
||||||
|
algorithm=hashes.SHA256(),
|
||||||
|
label=None,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
def decrypt_from_transit(
|
||||||
|
self, data: Union[bytes, str]
|
||||||
|
) -> Union[str, dict]:
|
||||||
|
"""Decrypts received data, handling both encrypted and unencrypted inputs"""
|
||||||
|
if not self.enable_transit_encryption:
|
||||||
|
return data.decode() if isinstance(data, bytes) else data
|
||||||
|
|
||||||
|
try:
|
||||||
|
if isinstance(data, bytes) and len(data) == 256:
|
||||||
|
decrypted_data = self.private_key.decrypt(
|
||||||
|
data,
|
||||||
|
padding.OAEP(
|
||||||
|
mgf=padding.MGF1(algorithm=hashes.SHA256()),
|
||||||
|
algorithm=hashes.SHA256(),
|
||||||
|
label=None,
|
||||||
|
),
|
||||||
|
).decode()
|
||||||
|
else:
|
||||||
|
return (
|
||||||
|
data.decode() if isinstance(data, bytes) else data
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
return json.loads(decrypted_data)
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
return decrypted_data
|
||||||
|
except ValueError:
|
||||||
|
return data.decode() if isinstance(data, bytes) else data
|
||||||
|
|
||||||
|
def get_public_key_pem(self) -> bytes:
|
||||||
|
"""Returns the public key in PEM format for sharing"""
|
||||||
|
if (
|
||||||
|
not self.enable_transit_encryption
|
||||||
|
and not self.enable_multi_agent
|
||||||
|
):
|
||||||
|
return b""
|
||||||
|
|
||||||
|
return self.public_key.public_bytes(
|
||||||
|
encoding=serialization.Encoding.PEM,
|
||||||
|
format=serialization.PublicFormat.SubjectPublicKeyInfo,
|
||||||
|
)
|
@ -0,0 +1,306 @@
|
|||||||
|
import json
|
||||||
|
from typing import Any, List
|
||||||
|
|
||||||
|
from loguru import logger
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
from swarms import Agent
|
||||||
|
|
||||||
|
|
||||||
|
class AgentOutput(BaseModel):
|
||||||
|
"""
|
||||||
|
Schema for capturing metadata and results of an agent run.
|
||||||
|
"""
|
||||||
|
|
||||||
|
agent_name: str = Field(..., description="Name of the agent.")
|
||||||
|
input_query: str = Field(
|
||||||
|
..., description="Input query provided to the agent."
|
||||||
|
)
|
||||||
|
output_result: Any = Field(
|
||||||
|
..., description="Result produced by the agent."
|
||||||
|
)
|
||||||
|
metadata: dict = Field(
|
||||||
|
..., description="Additional metadata about the agent run."
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class MatrixSwarm:
|
||||||
|
"""
|
||||||
|
A class to manage a matrix of agents and perform matrix operations similar to linear algebra.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, agents: List[List[Agent]]):
|
||||||
|
"""
|
||||||
|
Initializes the MatrixSwarm with a 2D list of agents.
|
||||||
|
Args:
|
||||||
|
agents (List[List[Agent]]): 2D list of agents representing the matrix.
|
||||||
|
"""
|
||||||
|
if not agents or not all(
|
||||||
|
isinstance(row, list) for row in agents
|
||||||
|
):
|
||||||
|
raise ValueError("Agents must be provided as a 2D list.")
|
||||||
|
if not all(
|
||||||
|
isinstance(agent, Agent)
|
||||||
|
for row in agents
|
||||||
|
for agent in row
|
||||||
|
):
|
||||||
|
raise ValueError(
|
||||||
|
"All elements of the matrix must be instances of `Agent`."
|
||||||
|
)
|
||||||
|
self.agents = agents
|
||||||
|
self.outputs = [] # List to store outputs as AgentOutput
|
||||||
|
|
||||||
|
def validate_dimensions(self, other: "MatrixSwarm") -> None:
|
||||||
|
"""
|
||||||
|
Validates that two matrices have compatible dimensions for operations.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
other (MatrixSwarm): Another MatrixSwarm.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ValueError: If dimensions are incompatible.
|
||||||
|
"""
|
||||||
|
if len(self.agents) != len(other.agents) or len(
|
||||||
|
self.agents[0]
|
||||||
|
) != len(other.agents[0]):
|
||||||
|
raise ValueError(
|
||||||
|
"Matrix dimensions are incompatible for this operation."
|
||||||
|
)
|
||||||
|
|
||||||
|
def transpose(self) -> "MatrixSwarm":
|
||||||
|
"""
|
||||||
|
Transposes the matrix of agents (swap rows and columns).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
MatrixSwarm: A new transposed MatrixSwarm.
|
||||||
|
"""
|
||||||
|
transposed_agents = [
|
||||||
|
[self.agents[j][i] for j in range(len(self.agents))]
|
||||||
|
for i in range(len(self.agents[0]))
|
||||||
|
]
|
||||||
|
return MatrixSwarm(transposed_agents)
|
||||||
|
|
||||||
|
def add(self, other: "MatrixSwarm") -> "MatrixSwarm":
|
||||||
|
"""
|
||||||
|
Adds two matrices element-wise.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
other (MatrixSwarm): Another MatrixSwarm to add.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
MatrixSwarm: A new MatrixSwarm resulting from the addition.
|
||||||
|
"""
|
||||||
|
self.validate_dimensions(other)
|
||||||
|
added_agents = [
|
||||||
|
[self.agents[i][j] for j in range(len(self.agents[i]))]
|
||||||
|
for i in range(len(self.agents))
|
||||||
|
]
|
||||||
|
return MatrixSwarm(added_agents)
|
||||||
|
|
||||||
|
def scalar_multiply(self, scalar: int) -> "MatrixSwarm":
|
||||||
|
"""
|
||||||
|
Scales the agents by duplicating them scalar times along the row.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
scalar (int): The scalar multiplier.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
MatrixSwarm: A new MatrixSwarm where each agent is repeated scalar times along the row.
|
||||||
|
"""
|
||||||
|
scaled_agents = [
|
||||||
|
[agent for _ in range(scalar) for agent in row]
|
||||||
|
for row in self.agents
|
||||||
|
]
|
||||||
|
return MatrixSwarm(scaled_agents)
|
||||||
|
|
||||||
|
def multiply(
|
||||||
|
self, other: "MatrixSwarm", inputs: List[str]
|
||||||
|
) -> List[List[AgentOutput]]:
|
||||||
|
"""
|
||||||
|
Multiplies two matrices (dot product between rows and columns).
|
||||||
|
|
||||||
|
Args:
|
||||||
|
other (MatrixSwarm): Another MatrixSwarm for multiplication.
|
||||||
|
inputs (List[str]): A list of input queries for the agents.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
List[List[AgentOutput]]: A resulting matrix of outputs after multiplication.
|
||||||
|
"""
|
||||||
|
if len(self.agents[0]) != len(other.agents):
|
||||||
|
raise ValueError(
|
||||||
|
"Matrix dimensions are incompatible for multiplication."
|
||||||
|
)
|
||||||
|
|
||||||
|
results = []
|
||||||
|
for i, row in enumerate(self.agents):
|
||||||
|
row_results = []
|
||||||
|
for col_idx in range(len(other.agents[0])):
|
||||||
|
col = [
|
||||||
|
other.agents[row_idx][col_idx]
|
||||||
|
for row_idx in range(len(other.agents))
|
||||||
|
]
|
||||||
|
query = inputs[
|
||||||
|
i
|
||||||
|
] # Input query for the corresponding row
|
||||||
|
intermediate_result = []
|
||||||
|
|
||||||
|
for agent_r, agent_c in zip(row, col):
|
||||||
|
try:
|
||||||
|
result = agent_r.run(query)
|
||||||
|
intermediate_result.append(result)
|
||||||
|
except Exception as e:
|
||||||
|
intermediate_result.append(f"Error: {e}")
|
||||||
|
|
||||||
|
# Aggregate outputs from dot product
|
||||||
|
combined_result = " ".join(
|
||||||
|
intermediate_result
|
||||||
|
) # Example aggregation
|
||||||
|
row_results.append(
|
||||||
|
AgentOutput(
|
||||||
|
agent_name=f"DotProduct-{i}-{col_idx}",
|
||||||
|
input_query=query,
|
||||||
|
output_result=combined_result,
|
||||||
|
metadata={"row": i, "col": col_idx},
|
||||||
|
)
|
||||||
|
)
|
||||||
|
results.append(row_results)
|
||||||
|
return results
|
||||||
|
|
||||||
|
def subtract(self, other: "MatrixSwarm") -> "MatrixSwarm":
|
||||||
|
"""
|
||||||
|
Subtracts two matrices element-wise.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
other (MatrixSwarm): Another MatrixSwarm to subtract.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
MatrixSwarm: A new MatrixSwarm resulting from the subtraction.
|
||||||
|
"""
|
||||||
|
self.validate_dimensions(other)
|
||||||
|
subtracted_agents = [
|
||||||
|
[self.agents[i][j] for j in range(len(self.agents[i]))]
|
||||||
|
for i in range(len(self.agents))
|
||||||
|
]
|
||||||
|
return MatrixSwarm(subtracted_agents)
|
||||||
|
|
||||||
|
def identity(self, size: int) -> "MatrixSwarm":
|
||||||
|
"""
|
||||||
|
Creates an identity matrix of agents with size `size`.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
size (int): Size of the identity matrix (NxN).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
MatrixSwarm: An identity MatrixSwarm.
|
||||||
|
"""
|
||||||
|
identity_agents = [
|
||||||
|
[
|
||||||
|
(
|
||||||
|
self.agents[i][j]
|
||||||
|
if i == j
|
||||||
|
else Agent(
|
||||||
|
agent_name=f"Zero-Agent-{i}-{j}",
|
||||||
|
system_prompt="",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
for j in range(size)
|
||||||
|
]
|
||||||
|
for i in range(size)
|
||||||
|
]
|
||||||
|
return MatrixSwarm(identity_agents)
|
||||||
|
|
||||||
|
def determinant(self) -> Any:
|
||||||
|
"""
|
||||||
|
Computes the determinant of a square MatrixSwarm.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Any: Determinant of the matrix (as agent outputs).
|
||||||
|
"""
|
||||||
|
if len(self.agents) != len(self.agents[0]):
|
||||||
|
raise ValueError(
|
||||||
|
"Determinant can only be computed for square matrices."
|
||||||
|
)
|
||||||
|
|
||||||
|
# Recursive determinant calculation (example using placeholder logic)
|
||||||
|
if len(self.agents) == 1:
|
||||||
|
return self.agents[0][0].run("Compute determinant")
|
||||||
|
|
||||||
|
det_result = 0
|
||||||
|
for i in range(len(self.agents)):
|
||||||
|
submatrix = MatrixSwarm(
|
||||||
|
[row[:i] + row[i + 1 :] for row in self.agents[1:]]
|
||||||
|
)
|
||||||
|
cofactor = ((-1) ** i) * self.agents[0][i].run(
|
||||||
|
"Compute determinant"
|
||||||
|
)
|
||||||
|
det_result += cofactor * submatrix.determinant()
|
||||||
|
return det_result
|
||||||
|
|
||||||
|
def save_to_file(self, path: str) -> None:
|
||||||
|
"""
|
||||||
|
Saves the agent matrix structure and metadata to a file.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
path (str): File path to save the matrix.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
matrix_data = {
|
||||||
|
"agents": [
|
||||||
|
[agent.agent_name for agent in row]
|
||||||
|
for row in self.agents
|
||||||
|
],
|
||||||
|
"outputs": [output.dict() for output in self.outputs],
|
||||||
|
}
|
||||||
|
with open(path, "w") as f:
|
||||||
|
json.dump(matrix_data, f, indent=4)
|
||||||
|
logger.info(f"MatrixSwarm saved to {path}")
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Error saving MatrixSwarm: {e}")
|
||||||
|
|
||||||
|
|
||||||
|
# # Example usage
|
||||||
|
# if __name__ == "__main__":
|
||||||
|
# from swarms.prompts.finance_agent_sys_prompt import (
|
||||||
|
# FINANCIAL_AGENT_SYS_PROMPT,
|
||||||
|
# )
|
||||||
|
|
||||||
|
# # Create a 3x3 matrix of agents
|
||||||
|
# agents = [
|
||||||
|
# [
|
||||||
|
# Agent(
|
||||||
|
# agent_name=f"Agent-{i}-{j}",
|
||||||
|
# system_prompt=FINANCIAL_AGENT_SYS_PROMPT,
|
||||||
|
# model_name="gpt-4o-mini",
|
||||||
|
# max_loops=1,
|
||||||
|
# autosave=True,
|
||||||
|
# dashboard=False,
|
||||||
|
# verbose=True,
|
||||||
|
# dynamic_temperature_enabled=True,
|
||||||
|
# saved_state_path=f"agent_{i}_{j}.json",
|
||||||
|
# user_name="swarms_corp",
|
||||||
|
# retry_attempts=1,
|
||||||
|
# context_length=200000,
|
||||||
|
# return_step_meta=False,
|
||||||
|
# output_type="string",
|
||||||
|
# streaming_on=False,
|
||||||
|
# )
|
||||||
|
# for j in range(3)
|
||||||
|
# ]
|
||||||
|
# for i in range(3)
|
||||||
|
# ]
|
||||||
|
|
||||||
|
# # Initialize the matrix
|
||||||
|
# agent_matrix = MatrixSwarm(agents)
|
||||||
|
|
||||||
|
# # Example queries
|
||||||
|
# inputs = [
|
||||||
|
# "Explain Roth IRA benefits",
|
||||||
|
# "Differences between ETFs and mutual funds",
|
||||||
|
# "How to create a diversified portfolio",
|
||||||
|
# ]
|
||||||
|
|
||||||
|
# # Run agents
|
||||||
|
# outputs = agent_matrix.multiply(agent_matrix.transpose(), inputs)
|
||||||
|
|
||||||
|
# # Save results
|
||||||
|
# agent_matrix.save_to_file("agent_matrix_results.json")
|
@ -0,0 +1,429 @@
|
|||||||
|
import json
|
||||||
|
import os
|
||||||
|
import subprocess
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
try:
|
||||||
|
import openai
|
||||||
|
except ImportError:
|
||||||
|
print(
|
||||||
|
"OpenAI is not installed. Please install it using 'pip install openai'."
|
||||||
|
)
|
||||||
|
import sys
|
||||||
|
|
||||||
|
subprocess.run([sys.executable, "-m", "pip", "install", "openai"])
|
||||||
|
exit(1)
|
||||||
|
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
from loguru import logger
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
from swarms.structs.agent import Agent
|
||||||
|
from swarms.structs.swarm_router import SwarmRouter
|
||||||
|
|
||||||
|
load_dotenv()
|
||||||
|
|
||||||
|
|
||||||
|
class OpenAIFunctionCaller:
|
||||||
|
"""
|
||||||
|
A class that represents a caller for OpenAI chat completions.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
system_prompt (str): The system prompt to be used in the chat completion.
|
||||||
|
model_name (str): The name of the OpenAI model to be used.
|
||||||
|
max_tokens (int): The maximum number of tokens in the generated completion.
|
||||||
|
temperature (float): The temperature parameter for randomness in the completion.
|
||||||
|
base_model (BaseModel): The base model to be used for the completion.
|
||||||
|
openai_api_key (str): The API key for accessing the OpenAI service.
|
||||||
|
parallel_tool_calls (bool): Whether to make parallel tool calls.
|
||||||
|
top_p (float): The top-p parameter for nucleus sampling in the completion.
|
||||||
|
|
||||||
|
Attributes:
|
||||||
|
system_prompt (str): The system prompt to be used in the chat completion.
|
||||||
|
model_name (str): The name of the OpenAI model to be used.
|
||||||
|
max_tokens (int): The maximum number of tokens in the generated completion.
|
||||||
|
temperature (float): The temperature parameter for randomness in the completion.
|
||||||
|
base_model (BaseModel): The base model to be used for the completion.
|
||||||
|
parallel_tool_calls (bool): Whether to make parallel tool calls.
|
||||||
|
top_p (float): The top-p parameter for nucleus sampling in the completion.
|
||||||
|
client (openai.OpenAI): The OpenAI client for making API calls.
|
||||||
|
|
||||||
|
Methods:
|
||||||
|
check_api_key: Checks if the API key is provided and retrieves it from the environment if not.
|
||||||
|
run: Runs the chat completion with the given task and returns the generated completion.
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
system_prompt: str = None,
|
||||||
|
model_name: str = "gpt-4o-2024-08-06",
|
||||||
|
max_tokens: int = 4000,
|
||||||
|
temperature: float = 0.4,
|
||||||
|
base_model: BaseModel = None,
|
||||||
|
openai_api_key: str = None,
|
||||||
|
parallel_tool_calls: bool = False,
|
||||||
|
top_p: float = 0.9,
|
||||||
|
*args,
|
||||||
|
**kwargs,
|
||||||
|
):
|
||||||
|
super().__init__()
|
||||||
|
self.system_prompt = system_prompt
|
||||||
|
self.model_name = model_name
|
||||||
|
self.max_tokens = max_tokens
|
||||||
|
self.temperature = temperature
|
||||||
|
self.openai_api_key = openai_api_key
|
||||||
|
self.base_model = base_model
|
||||||
|
self.parallel_tool_calls = parallel_tool_calls
|
||||||
|
self.top_p = top_p
|
||||||
|
self.client = openai.OpenAI(api_key=self.check_api_key())
|
||||||
|
|
||||||
|
def check_api_key(self) -> str:
|
||||||
|
"""
|
||||||
|
Checks if the API key is provided and retrieves it from the environment if not.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: The API key.
|
||||||
|
|
||||||
|
"""
|
||||||
|
self.openai_api_key = os.getenv("OPENAI_API_KEY")
|
||||||
|
|
||||||
|
return self.openai_api_key
|
||||||
|
|
||||||
|
def run(self, task: str, *args, **kwargs) -> dict:
|
||||||
|
"""
|
||||||
|
Runs the chat completion with the given task and returns the generated completion.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
task (str): The user's task for the chat completion.
|
||||||
|
*args: Additional positional arguments to be passed to the OpenAI API.
|
||||||
|
**kwargs: Additional keyword arguments to be passed to the OpenAI API.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: The generated completion.
|
||||||
|
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
completion = self.client.beta.chat.completions.parse(
|
||||||
|
model=self.model_name,
|
||||||
|
messages=[
|
||||||
|
{"role": "system", "content": self.system_prompt},
|
||||||
|
{"role": "user", "content": task},
|
||||||
|
],
|
||||||
|
max_tokens=self.max_tokens,
|
||||||
|
temperature=self.temperature,
|
||||||
|
response_format=self.base_model,
|
||||||
|
tools=(
|
||||||
|
[openai.pydantic_function_tool(self.base_model)]
|
||||||
|
),
|
||||||
|
*args,
|
||||||
|
**kwargs,
|
||||||
|
)
|
||||||
|
|
||||||
|
out = completion.choices[0].message.content
|
||||||
|
return out
|
||||||
|
except Exception as error:
|
||||||
|
logger.error(
|
||||||
|
f"Error in running OpenAI chat completion: {error}"
|
||||||
|
)
|
||||||
|
return None
|
||||||
|
|
||||||
|
def convert_to_dict_from_base_model(
|
||||||
|
self, base_model: BaseModel
|
||||||
|
) -> dict:
|
||||||
|
return openai.pydantic_function_tool(base_model)
|
||||||
|
|
||||||
|
def convert_list_of_base_models(
|
||||||
|
self, base_models: List[BaseModel]
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Converts a list of BaseModels to a list of dictionaries.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
base_models (List[BaseModel]): A list of BaseModels to be converted.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
List[Dict]: A list of dictionaries representing the converted BaseModels.
|
||||||
|
"""
|
||||||
|
return [
|
||||||
|
self.convert_to_dict_from_base_model(base_model)
|
||||||
|
for base_model in base_models
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
class MemeAgentConfig(BaseModel):
|
||||||
|
"""Configuration for an individual meme agent in a swarm"""
|
||||||
|
|
||||||
|
name: str = Field(
|
||||||
|
description="The name of the meme agent",
|
||||||
|
example="Meme-Generator-Agent",
|
||||||
|
)
|
||||||
|
description: str = Field(
|
||||||
|
description="A description of the meme agent's purpose and capabilities",
|
||||||
|
example="Agent responsible for generating and sharing memes",
|
||||||
|
)
|
||||||
|
system_prompt: str = Field(
|
||||||
|
description="The system prompt that defines the meme agent's behavior. Make this prompt as detailed and as extensive as possible.",
|
||||||
|
example="You are a meme generator agent. Your role is to create and share funny memes...",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class MemeSwarmConfig(BaseModel):
|
||||||
|
"""Configuration for a swarm of cooperative meme agents"""
|
||||||
|
|
||||||
|
name: str = Field(
|
||||||
|
description="The name of the meme swarm",
|
||||||
|
example="Meme-Creation-Swarm",
|
||||||
|
)
|
||||||
|
description: str = Field(
|
||||||
|
description="The description of the meme swarm's purpose and capabilities",
|
||||||
|
example="A swarm of agents that work together to generate and share memes",
|
||||||
|
)
|
||||||
|
agents: List[MemeAgentConfig] = Field(
|
||||||
|
description="The list of meme agents that make up the swarm",
|
||||||
|
example=[
|
||||||
|
MemeAgentConfig(
|
||||||
|
name="Meme-Generator-Agent",
|
||||||
|
description="Generates memes",
|
||||||
|
system_prompt="You are a meme generator agent...",
|
||||||
|
),
|
||||||
|
MemeAgentConfig(
|
||||||
|
name="Meme-Sharer-Agent",
|
||||||
|
description="Shares memes",
|
||||||
|
system_prompt="You are a meme sharer agent...",
|
||||||
|
),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
max_loops: int = Field(
|
||||||
|
description="The maximum number of meme generation loops to run the swarm",
|
||||||
|
example=1,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
BOSS_SYSTEM_PROMPT = """
|
||||||
|
You are the Meme Generator Boss, responsible for creating and managing a swarm of agents that generate funny, weird, and cool personas. Your goal is to ensure that each agent is uniquely suited to create hilarious and entertaining content.
|
||||||
|
|
||||||
|
### Instructions:
|
||||||
|
|
||||||
|
1. **Persona Generation**:
|
||||||
|
- Analyze the type of meme or content required.
|
||||||
|
- Assign tasks to existing agents with a fitting persona, ensuring they understand the tone and style needed.
|
||||||
|
- If no suitable agent exists, create a new agent with a persona tailored to the task, including a system prompt that outlines their role, objectives, and creative liberties.
|
||||||
|
|
||||||
|
2. **Agent Persona Creation**:
|
||||||
|
- Name agents based on their persona or the type of content they generate (e.g., "Dank Meme Lord" or "Surreal Humor Specialist").
|
||||||
|
- Provide each new agent with a system prompt that outlines their persona, including their tone, style, and any specific themes or topics they should focus on.
|
||||||
|
|
||||||
|
3. **Creativity and Originality**:
|
||||||
|
- Encourage agents to think outside the box and come up with unique, humorous, and entertaining content.
|
||||||
|
- Foster an environment where agents can experiment with different styles and formats to keep content fresh and engaging.
|
||||||
|
|
||||||
|
4. **Communication and Feedback**:
|
||||||
|
- Clearly communicate the requirements and expectations for each task to ensure agents understand what is needed.
|
||||||
|
- Encourage agents to provide feedback on their creative process and suggest new ideas or directions for future content.
|
||||||
|
|
||||||
|
5. **Transparency and Accountability**:
|
||||||
|
- Maintain transparency in the selection or creation of agents for specific tasks, ensuring that the reasoning behind each decision is clear.
|
||||||
|
- Hold agents accountable for the content they generate, ensuring it meets the required standards of humor and creativity.
|
||||||
|
|
||||||
|
# Output Format
|
||||||
|
|
||||||
|
Present your plan in a clear, bullet-point format or short concise paragraphs, outlining persona generation, agent creation, creativity strategies, and communication protocols.
|
||||||
|
|
||||||
|
# Notes
|
||||||
|
|
||||||
|
- Ensure that agents understand the importance of originality and creativity in their content.
|
||||||
|
- Foster a culture of experimentation and continuous improvement to keep the content generated by agents fresh and engaging.
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class MemeAgentGenerator:
|
||||||
|
"""A class that automatically builds and manages swarms of AI agents.
|
||||||
|
|
||||||
|
This class handles the creation, coordination and execution of multiple AI agents working
|
||||||
|
together as a swarm to accomplish complex tasks. It uses a boss agent to delegate work
|
||||||
|
and create new specialized agents as needed.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
name (str): The name of the swarm
|
||||||
|
description (str): A description of the swarm's purpose
|
||||||
|
verbose (bool, optional): Whether to output detailed logs. Defaults to True.
|
||||||
|
max_loops (int, optional): Maximum number of execution loops. Defaults to 1.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
name: str = None,
|
||||||
|
description: str = None,
|
||||||
|
verbose: bool = True,
|
||||||
|
max_loops: int = 1,
|
||||||
|
):
|
||||||
|
self.name = name
|
||||||
|
self.description = description
|
||||||
|
self.verbose = verbose
|
||||||
|
self.max_loops = max_loops
|
||||||
|
self.agents_pool = []
|
||||||
|
logger.info(
|
||||||
|
f"Initialized AutoSwarmBuilder: {name} {description}"
|
||||||
|
)
|
||||||
|
|
||||||
|
def run(self, task: str, image_url: str = None, *args, **kwargs):
|
||||||
|
"""Run the swarm on a given task.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
task (str): The task to be accomplished
|
||||||
|
image_url (str, optional): URL of an image input if needed. Defaults to None.
|
||||||
|
*args: Variable length argument list
|
||||||
|
**kwargs: Arbitrary keyword arguments
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The output from the swarm's execution
|
||||||
|
"""
|
||||||
|
logger.info(f"Running swarm on task: {task}")
|
||||||
|
agents = self._create_agents(task, image_url, *args, **kwargs)
|
||||||
|
logger.info(f"Agents created {len(agents)}")
|
||||||
|
logger.info("Routing task through swarm")
|
||||||
|
output = self.swarm_router(agents, task, image_url)
|
||||||
|
logger.info(f"Swarm execution complete with output: {output}")
|
||||||
|
return output
|
||||||
|
|
||||||
|
def _create_agents(self, task: str, *args, **kwargs):
|
||||||
|
"""Create the necessary agents for a task.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
task (str): The task to create agents for
|
||||||
|
*args: Variable length argument list
|
||||||
|
**kwargs: Arbitrary keyword arguments
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
list: List of created agents
|
||||||
|
"""
|
||||||
|
logger.info("Creating agents for task")
|
||||||
|
model = OpenAIFunctionCaller(
|
||||||
|
system_prompt=BOSS_SYSTEM_PROMPT,
|
||||||
|
api_key=os.getenv("OPENAI_API_KEY"),
|
||||||
|
temperature=0.1,
|
||||||
|
base_model=MemeSwarmConfig,
|
||||||
|
)
|
||||||
|
|
||||||
|
agents_dictionary = model.run(task)
|
||||||
|
print(agents_dictionary)
|
||||||
|
|
||||||
|
agents_dictionary = json.loads(agents_dictionary)
|
||||||
|
|
||||||
|
if isinstance(agents_dictionary, dict):
|
||||||
|
agents_dictionary = MemeSwarmConfig(**agents_dictionary)
|
||||||
|
else:
|
||||||
|
raise ValueError(
|
||||||
|
"Agents dictionary is not a valid dictionary"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Set swarm config
|
||||||
|
self.name = agents_dictionary.name
|
||||||
|
self.description = agents_dictionary.description
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
f"Swarm config: {self.name}, {self.description}, {self.max_loops}"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Create agents from config
|
||||||
|
agents = []
|
||||||
|
for agent_config in agents_dictionary.agents:
|
||||||
|
# Convert dict to AgentConfig if needed
|
||||||
|
if isinstance(agent_config, dict):
|
||||||
|
agent_config = MemeAgentConfig(**agent_config)
|
||||||
|
|
||||||
|
agent = self.build_agent(
|
||||||
|
agent_name=agent_config.name,
|
||||||
|
agent_description=agent_config.description,
|
||||||
|
agent_system_prompt=agent_config.system_prompt,
|
||||||
|
)
|
||||||
|
agents.append(agent)
|
||||||
|
|
||||||
|
return agents
|
||||||
|
|
||||||
|
def build_agent(
|
||||||
|
self,
|
||||||
|
agent_name: str,
|
||||||
|
agent_description: str,
|
||||||
|
agent_system_prompt: str,
|
||||||
|
max_loops: int = 1,
|
||||||
|
):
|
||||||
|
"""Build a single agent with the given specifications.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
agent_name (str): Name of the agent
|
||||||
|
agent_description (str): Description of the agent's purpose
|
||||||
|
agent_system_prompt (str): The system prompt for the agent
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Agent: The constructed agent instance
|
||||||
|
"""
|
||||||
|
logger.info(f"Building agent: {agent_name}")
|
||||||
|
agent = Agent(
|
||||||
|
agent_name=agent_name,
|
||||||
|
description=agent_description,
|
||||||
|
system_prompt=agent_system_prompt,
|
||||||
|
model_name="gpt-4o-mini",
|
||||||
|
max_loops=max_loops,
|
||||||
|
autosave=True,
|
||||||
|
dashboard=False,
|
||||||
|
verbose=True,
|
||||||
|
dynamic_temperature_enabled=True,
|
||||||
|
saved_state_path=f"{agent_name}.json",
|
||||||
|
user_name="swarms_corp",
|
||||||
|
retry_attempts=1,
|
||||||
|
context_length=200000,
|
||||||
|
return_step_meta=False,
|
||||||
|
output_type="str", # "json", "dict", "csv" OR "string" soon "yaml" and
|
||||||
|
streaming_on=False,
|
||||||
|
# auto_generate_prompt=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
return agent
|
||||||
|
|
||||||
|
def swarm_router(
|
||||||
|
self,
|
||||||
|
agents: List[Agent],
|
||||||
|
task: str,
|
||||||
|
*args,
|
||||||
|
**kwargs,
|
||||||
|
):
|
||||||
|
"""Route tasks between agents in the swarm.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
agents (List[Agent]): List of available agents
|
||||||
|
task (str): The task to route
|
||||||
|
image_url (str, optional): URL of an image input if needed. Defaults to None.
|
||||||
|
*args: Variable length argument list
|
||||||
|
**kwargs: Arbitrary keyword arguments
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The output from the routed task execution
|
||||||
|
"""
|
||||||
|
logger.info("Routing task through swarm")
|
||||||
|
swarm_router_instance = SwarmRouter(
|
||||||
|
name=self.name,
|
||||||
|
description=self.description,
|
||||||
|
agents=agents,
|
||||||
|
swarm_type="auto",
|
||||||
|
max_loops=1,
|
||||||
|
)
|
||||||
|
|
||||||
|
return swarm_router_instance.run(
|
||||||
|
self.name + " " + self.description + " " + task,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
example = MemeAgentGenerator(
|
||||||
|
name="Meme-Swarm",
|
||||||
|
description="A swarm of specialized AI agents collaborating on generating and sharing memes around cool media from 2001s",
|
||||||
|
max_loops=1,
|
||||||
|
)
|
||||||
|
|
||||||
|
print(
|
||||||
|
example.run(
|
||||||
|
"Generate funny meme agents around cool media from 2001s"
|
||||||
|
)
|
||||||
|
)
|
@ -0,0 +1,216 @@
|
|||||||
|
from swarms.structs.matrix_swarm import AgentMatrix, AgentOutput
|
||||||
|
from swarms import Agent
|
||||||
|
|
||||||
|
|
||||||
|
def create_test_matrix(rows: int, cols: int) -> AgentMatrix:
|
||||||
|
"""Helper function to create a test agent matrix"""
|
||||||
|
agents = [
|
||||||
|
[
|
||||||
|
Agent(
|
||||||
|
agent_name=f"TestAgent-{i}-{j}",
|
||||||
|
system_prompt="Test prompt",
|
||||||
|
)
|
||||||
|
for j in range(cols)
|
||||||
|
]
|
||||||
|
for i in range(rows)
|
||||||
|
]
|
||||||
|
return AgentMatrix(agents)
|
||||||
|
|
||||||
|
|
||||||
|
def test_init():
|
||||||
|
"""Test AgentMatrix initialization"""
|
||||||
|
# Test valid initialization
|
||||||
|
matrix = create_test_matrix(2, 2)
|
||||||
|
assert isinstance(matrix, AgentMatrix)
|
||||||
|
assert len(matrix.agents) == 2
|
||||||
|
assert len(matrix.agents[0]) == 2
|
||||||
|
|
||||||
|
# Test invalid initialization
|
||||||
|
try:
|
||||||
|
AgentMatrix([[1, 2], [3, 4]]) # Non-agent elements
|
||||||
|
assert False, "Should raise ValueError"
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
try:
|
||||||
|
AgentMatrix([]) # Empty matrix
|
||||||
|
assert False, "Should raise ValueError"
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def test_transpose():
|
||||||
|
"""Test matrix transpose operation"""
|
||||||
|
matrix = create_test_matrix(2, 3)
|
||||||
|
transposed = matrix.transpose()
|
||||||
|
|
||||||
|
assert len(transposed.agents) == 3 # Original cols become rows
|
||||||
|
assert len(transposed.agents[0]) == 2 # Original rows become cols
|
||||||
|
|
||||||
|
# Verify agent positions
|
||||||
|
for i in range(2):
|
||||||
|
for j in range(3):
|
||||||
|
assert (
|
||||||
|
matrix.agents[i][j].agent_name
|
||||||
|
== transposed.agents[j][i].agent_name
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_add():
|
||||||
|
"""Test matrix addition"""
|
||||||
|
matrix1 = create_test_matrix(2, 2)
|
||||||
|
matrix2 = create_test_matrix(2, 2)
|
||||||
|
|
||||||
|
result = matrix1.add(matrix2)
|
||||||
|
assert len(result.agents) == 2
|
||||||
|
assert len(result.agents[0]) == 2
|
||||||
|
|
||||||
|
# Test incompatible dimensions
|
||||||
|
matrix3 = create_test_matrix(2, 3)
|
||||||
|
try:
|
||||||
|
matrix1.add(matrix3)
|
||||||
|
assert False, "Should raise ValueError"
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def test_scalar_multiply():
|
||||||
|
"""Test scalar multiplication"""
|
||||||
|
matrix = create_test_matrix(2, 2)
|
||||||
|
scalar = 3
|
||||||
|
result = matrix.scalar_multiply(scalar)
|
||||||
|
|
||||||
|
assert len(result.agents) == 2
|
||||||
|
assert len(result.agents[0]) == 2 * scalar
|
||||||
|
|
||||||
|
# Verify agent duplication
|
||||||
|
for i in range(len(result.agents)):
|
||||||
|
for j in range(0, len(result.agents[0]), scalar):
|
||||||
|
original_agent = matrix.agents[i][j // scalar]
|
||||||
|
for k in range(scalar):
|
||||||
|
assert (
|
||||||
|
result.agents[i][j + k].agent_name
|
||||||
|
== original_agent.agent_name
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_multiply():
|
||||||
|
"""Test matrix multiplication"""
|
||||||
|
matrix1 = create_test_matrix(2, 3)
|
||||||
|
matrix2 = create_test_matrix(3, 2)
|
||||||
|
inputs = ["test query 1", "test query 2"]
|
||||||
|
|
||||||
|
result = matrix1.multiply(matrix2, inputs)
|
||||||
|
assert len(result) == 2 # Number of rows in first matrix
|
||||||
|
assert len(result[0]) == 2 # Number of columns in second matrix
|
||||||
|
|
||||||
|
# Verify output structure
|
||||||
|
for row in result:
|
||||||
|
for output in row:
|
||||||
|
assert isinstance(output, AgentOutput)
|
||||||
|
assert isinstance(output.input_query, str)
|
||||||
|
assert isinstance(output.metadata, dict)
|
||||||
|
|
||||||
|
|
||||||
|
def test_subtract():
|
||||||
|
"""Test matrix subtraction"""
|
||||||
|
matrix1 = create_test_matrix(2, 2)
|
||||||
|
matrix2 = create_test_matrix(2, 2)
|
||||||
|
|
||||||
|
result = matrix1.subtract(matrix2)
|
||||||
|
assert len(result.agents) == 2
|
||||||
|
assert len(result.agents[0]) == 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_identity():
|
||||||
|
"""Test identity matrix creation"""
|
||||||
|
matrix = create_test_matrix(3, 3)
|
||||||
|
identity = matrix.identity(3)
|
||||||
|
|
||||||
|
assert len(identity.agents) == 3
|
||||||
|
assert len(identity.agents[0]) == 3
|
||||||
|
|
||||||
|
# Verify diagonal elements are from original matrix
|
||||||
|
for i in range(3):
|
||||||
|
assert (
|
||||||
|
identity.agents[i][i].agent_name
|
||||||
|
== matrix.agents[i][i].agent_name
|
||||||
|
)
|
||||||
|
|
||||||
|
# Verify non-diagonal elements are zero agents
|
||||||
|
for j in range(3):
|
||||||
|
if i != j:
|
||||||
|
assert identity.agents[i][j].agent_name.startswith(
|
||||||
|
"Zero-Agent"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_determinant():
|
||||||
|
"""Test determinant calculation"""
|
||||||
|
# Test 1x1 matrix
|
||||||
|
matrix1 = create_test_matrix(1, 1)
|
||||||
|
det1 = matrix1.determinant()
|
||||||
|
assert det1 is not None
|
||||||
|
|
||||||
|
# Test 2x2 matrix
|
||||||
|
matrix2 = create_test_matrix(2, 2)
|
||||||
|
det2 = matrix2.determinant()
|
||||||
|
assert det2 is not None
|
||||||
|
|
||||||
|
# Test non-square matrix
|
||||||
|
matrix3 = create_test_matrix(2, 3)
|
||||||
|
try:
|
||||||
|
matrix3.determinant()
|
||||||
|
assert False, "Should raise ValueError"
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def test_save_to_file(tmp_path):
|
||||||
|
"""Test saving matrix to file"""
|
||||||
|
import os
|
||||||
|
|
||||||
|
matrix = create_test_matrix(2, 2)
|
||||||
|
file_path = os.path.join(tmp_path, "test_matrix.json")
|
||||||
|
|
||||||
|
matrix.save_to_file(file_path)
|
||||||
|
assert os.path.exists(file_path)
|
||||||
|
|
||||||
|
# Verify file contents
|
||||||
|
import json
|
||||||
|
|
||||||
|
with open(file_path, "r") as f:
|
||||||
|
data = json.load(f)
|
||||||
|
assert "agents" in data
|
||||||
|
assert "outputs" in data
|
||||||
|
assert len(data["agents"]) == 2
|
||||||
|
assert len(data["agents"][0]) == 2
|
||||||
|
|
||||||
|
|
||||||
|
def run_all_tests():
|
||||||
|
"""Run all test functions"""
|
||||||
|
test_functions = [
|
||||||
|
test_init,
|
||||||
|
test_transpose,
|
||||||
|
test_add,
|
||||||
|
test_scalar_multiply,
|
||||||
|
test_multiply,
|
||||||
|
test_subtract,
|
||||||
|
test_identity,
|
||||||
|
test_determinant,
|
||||||
|
]
|
||||||
|
|
||||||
|
for test_func in test_functions:
|
||||||
|
try:
|
||||||
|
test_func()
|
||||||
|
print(f"✅ {test_func.__name__} passed")
|
||||||
|
except AssertionError as e:
|
||||||
|
print(f"❌ {test_func.__name__} failed: {str(e)}")
|
||||||
|
except Exception as e:
|
||||||
|
print(
|
||||||
|
f"❌ {test_func.__name__} failed with exception: {str(e)}"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
run_all_tests()
|
@ -0,0 +1,92 @@
|
|||||||
|
# Define a simple testing framework
|
||||||
|
from swarms.tools.tool_parse_exec import parse_and_execute_json
|
||||||
|
|
||||||
|
|
||||||
|
def run_test(test_name, test_func):
|
||||||
|
print(f"Running test: {test_name}")
|
||||||
|
print("------------------------------------------------")
|
||||||
|
try:
|
||||||
|
test_func()
|
||||||
|
print(f"✓ {test_name} passed")
|
||||||
|
print("------------------------------------------------")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"✗ {test_name} failed: {str(e)}")
|
||||||
|
print("------------------------------------------------")
|
||||||
|
|
||||||
|
|
||||||
|
# Mock functions for testing
|
||||||
|
def mock_function_a(param1, param2):
|
||||||
|
return param1 + param2
|
||||||
|
|
||||||
|
|
||||||
|
def mock_function_b(param1):
|
||||||
|
if param1 < 0:
|
||||||
|
raise ValueError("Negative value not allowed")
|
||||||
|
return param1 * 2
|
||||||
|
|
||||||
|
|
||||||
|
# Test cases
|
||||||
|
def test_parse_and_execute_json_success():
|
||||||
|
functions = [mock_function_a, mock_function_b]
|
||||||
|
json_string = '{"functions": [{"name": "mock_function_a", "parameters": {"param1": 1, "param2": 2}}, {"name": "mock_function_b", "parameters": {"param1": 3}}]}'
|
||||||
|
|
||||||
|
result = parse_and_execute_json(functions, json_string)
|
||||||
|
expected_result = {
|
||||||
|
"results": {"mock_function_a": "3", "mock_function_b": "6"},
|
||||||
|
"summary": "mock_function_a: 3\nmock_function_b: 6",
|
||||||
|
}
|
||||||
|
|
||||||
|
assert (
|
||||||
|
result == expected_result
|
||||||
|
), f"Expected {expected_result}, but got {result}"
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_and_execute_json_function_not_found():
|
||||||
|
functions = [mock_function_a]
|
||||||
|
json_string = '{"functions": [{"name": "non_existent_function", "parameters": {}}]}'
|
||||||
|
|
||||||
|
result = parse_and_execute_json(functions, json_string)
|
||||||
|
expected_result = {
|
||||||
|
"results": {
|
||||||
|
"non_existent_function": "Error: Function non_existent_function not found"
|
||||||
|
},
|
||||||
|
"summary": "non_existent_function: Error: Function non_existent_function not found",
|
||||||
|
}
|
||||||
|
|
||||||
|
assert (
|
||||||
|
result == expected_result
|
||||||
|
), f"Expected {expected_result}, but got {result}"
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_and_execute_json_error_handling():
|
||||||
|
functions = [mock_function_b]
|
||||||
|
json_string = '{"functions": [{"name": "mock_function_b", "parameters": {"param1": -1}}]}'
|
||||||
|
|
||||||
|
result = parse_and_execute_json(functions, json_string)
|
||||||
|
expected_result = {
|
||||||
|
"results": {
|
||||||
|
"mock_function_b": "Error: Negative value not allowed"
|
||||||
|
},
|
||||||
|
"summary": "mock_function_b: Error: Negative value not allowed",
|
||||||
|
}
|
||||||
|
|
||||||
|
assert (
|
||||||
|
result == expected_result
|
||||||
|
), f"Expected {expected_result}, but got {result}"
|
||||||
|
|
||||||
|
|
||||||
|
# Run tests
|
||||||
|
run_test(
|
||||||
|
"Test parse_and_execute_json success",
|
||||||
|
test_parse_and_execute_json_success,
|
||||||
|
)
|
||||||
|
print("------------------------------------------------")
|
||||||
|
run_test(
|
||||||
|
"Test parse_and_execute_json function not found",
|
||||||
|
test_parse_and_execute_json_function_not_found,
|
||||||
|
)
|
||||||
|
print("------------------------------------------------")
|
||||||
|
run_test(
|
||||||
|
"Test parse_and_execute_json error handling",
|
||||||
|
test_parse_and_execute_json_error_handling,
|
||||||
|
)
|
Loading…
Reference in new issue