[DOCS][Swarm Tools example]

pull/758/head
Kye Gomez 2 weeks ago
parent 4979e6947a
commit 5e4a600d47

@ -208,6 +208,8 @@ nav:
- Ollama: "swarms/examples/ollama.md" - Ollama: "swarms/examples/ollama.md"
- OpenRouter: "swarms/examples/openrouter.md" - OpenRouter: "swarms/examples/openrouter.md"
- XAI: "swarms/examples/xai.md" - XAI: "swarms/examples/xai.md"
- Swarms Tools:
- Agent with HTX + CoinGecko: "swarms/examples/swarms_tools_htx.md"
- Swarm Models: - Swarm Models:
- Overview: "swarms/models/index.md" - Overview: "swarms/models/index.md"
# - Models Available: "swarms/models/index.md" # - Models Available: "swarms/models/index.md"
@ -226,6 +228,8 @@ nav:
- BaseMultiModalModel: "swarms/models/base_multimodal_model.md" - BaseMultiModalModel: "swarms/models/base_multimodal_model.md"
- Multi Modal Models Available: "swarms/models/multimodal_models.md" - Multi Modal Models Available: "swarms/models/multimodal_models.md"
- GPT4VisionAPI: "swarms/models/gpt4v.md" - GPT4VisionAPI: "swarms/models/gpt4v.md"
- Swarms Tools:
- Overview: "swarms_tools/overview.md"
- Swarms Cloud API: - Swarms Cloud API:
# - Overview: "swarms_cloud/main.md" # - Overview: "swarms_cloud/main.md"
- Overview: "swarms_cloud/vision.md" - Overview: "swarms_cloud/vision.md"

@ -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,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**

@ -191,7 +191,9 @@ def create_agents_from_yaml(
"Please add at least one agent under the 'agents' section." "Please add at least one agent under the 'agents' section."
) )
logger.info(f"Found {len(config['agents'])} agent(s) to create") logger.info(
f"Found {len(config['agents'])} agent(s) to create"
)
# Create agents with retry logic # Create agents with retry logic
for idx, agent_config in enumerate(config["agents"], 1): for idx, agent_config in enumerate(config["agents"], 1):
@ -203,13 +205,17 @@ def create_agents_from_yaml(
) )
if "model_name" in agent_config: if "model_name" in agent_config:
logger.info(f"Using specified model: {agent_config['model_name']}") logger.info(
f"Using specified model: {agent_config['model_name']}"
)
model_instance = LiteLLM( model_instance = LiteLLM(
model_name=agent_config["model_name"] model_name=agent_config["model_name"]
) )
else: else:
model_name = "gpt-4" model_name = "gpt-4"
logger.info(f"No model specified, using default: {model_name}") logger.info(
f"No model specified, using default: {model_name}"
)
model_instance = LiteLLM(model_name=model_name) model_instance = LiteLLM(model_name=model_name)
agent = create_agent_with_retry( agent = create_agent_with_retry(
@ -231,8 +237,14 @@ def create_agents_from_yaml(
"swarm_architecture must be a dictionary containing swarm configuration" "swarm_architecture must be a dictionary containing swarm configuration"
) )
required_fields = {"name", "description", "swarm_type"} required_fields = {
missing_fields = required_fields - set(config["swarm_architecture"].keys()) "name",
"description",
"swarm_type",
}
missing_fields = required_fields - set(
config["swarm_architecture"].keys()
)
if missing_fields: if missing_fields:
raise ValueError( raise ValueError(
f"SwarmRouter creation failed: Missing required fields in swarm_architecture: {', '.join(missing_fields)}" f"SwarmRouter creation failed: Missing required fields in swarm_architecture: {', '.join(missing_fields)}"
@ -242,7 +254,9 @@ def create_agents_from_yaml(
**config["swarm_architecture"] **config["swarm_architecture"]
) )
logger.info(f"Creating SwarmRouter with type: {swarm_config.swarm_type}") logger.info(
f"Creating SwarmRouter with type: {swarm_config.swarm_type}"
)
swarm_router = SwarmRouter( swarm_router = SwarmRouter(
name=swarm_config.name, name=swarm_config.name,
description=swarm_config.description, description=swarm_config.description,
@ -306,7 +320,9 @@ def create_agents_from_yaml(
"No task specified in swarm_architecture. Please add a 'task' field " "No task specified in swarm_architecture. Please add a 'task' field "
"to define what the swarm should do." "to define what the swarm should do."
) )
logger.info(f"Running swarm with task: {config['swarm_architecture']['task']}") logger.info(
f"Running swarm with task: {config['swarm_architecture']['task']}"
)
return swarm_router.run( return swarm_router.run(
config["swarm_architecture"]["task"] config["swarm_architecture"]["task"]
) )
@ -331,8 +347,12 @@ def create_agents_from_yaml(
result = agents[0] if len(agents) == 1 else agents result = agents[0] if len(agents) == 1 else agents
elif return_type == "both": elif return_type == "both":
result = ( result = (
(swarm_router if swarm_router else agents[0] if len(agents) == 1 else agents), (
agents swarm_router
if swarm_router
else agents[0] if len(agents) == 1 else agents
),
agents,
) )
elif return_type == "tasks": elif return_type == "tasks":
result = task_results result = task_results

@ -277,7 +277,9 @@ def main():
check_login() check_login()
elif args.command == "run-agents": elif args.command == "run-agents":
try: try:
console.print(f"[yellow]Loading agents from {args.yaml_file}...[/yellow]") console.print(
f"[yellow]Loading agents from {args.yaml_file}...[/yellow]"
)
if not os.path.exists(args.yaml_file): if not os.path.exists(args.yaml_file):
raise FileNotFoundError( raise FileNotFoundError(
@ -288,47 +290,78 @@ def main():
# Create progress display # Create progress display
progress = Progress( progress = Progress(
SpinnerColumn(), SpinnerColumn(),
TextColumn("[progress.description]{task.description}"), TextColumn(
"[progress.description]{task.description}"
),
console=console, console=console,
) )
with progress: with progress:
# Add initial task # Add initial task
init_task = progress.add_task("Initializing...", total=None) init_task = progress.add_task(
"Initializing...", total=None
)
# Load and validate YAML # Load and validate YAML
progress.update(init_task, description="Loading YAML configuration...") progress.update(
init_task,
description="Loading YAML configuration...",
)
# Create agents # Create agents
progress.update(init_task, description="Creating agents...") progress.update(
init_task,
description="Creating agents...",
)
result = create_agents_from_yaml( result = create_agents_from_yaml(
yaml_file=args.yaml_file, yaml_file=args.yaml_file,
return_type="run_swarm" return_type="run_swarm",
) )
# Update progress on completion # Update progress on completion
progress.update(init_task, description="Processing complete!", completed=True) progress.update(
init_task,
description="Processing complete!",
completed=True,
)
if result: if result:
# Format and display the results # Format and display the results
if isinstance(result, str): if isinstance(result, str):
console.print("\n[bold green]Results:[/bold green]") console.print(
console.print(Panel(result, title="Agent Output", border_style="green")) "\n[bold green]Results:[/bold green]"
)
console.print(
Panel(
result,
title="Agent Output",
border_style="green",
)
)
elif isinstance(result, dict): elif isinstance(result, dict):
console.print("\n[bold green]Results:[/bold green]") console.print(
"\n[bold green]Results:[/bold green]"
)
for key, value in result.items(): for key, value in result.items():
console.print(f"[cyan]{key}:[/cyan] {value}") console.print(
f"[cyan]{key}:[/cyan] {value}"
)
else: else:
console.print("[green]✓ Agents completed their tasks successfully![/green]") console.print(
"[green]✓ Agents completed their tasks successfully![/green]"
)
else: else:
console.print("[yellow]⚠ Agents completed but returned no results.[/yellow]") console.print(
"[yellow]⚠ Agents completed but returned no results.[/yellow]"
)
except FileNotFoundError as e: except FileNotFoundError as e:
show_error("File Error", str(e)) show_error("File Error", str(e))
except ValueError as e: except ValueError as e:
show_error( show_error(
"Configuration Error", "Configuration Error",
str(e) + "\n\nPlease check your agents.yaml file format." str(e)
+ "\n\nPlease check your agents.yaml file format.",
) )
except Exception as e: except Exception as e:
# Enhanced error handling # Enhanced error handling
@ -339,7 +372,7 @@ def main():
"The model's context length was exceeded. Try:\n" "The model's context length was exceeded. Try:\n"
"1. Reducing max_tokens in your YAML config\n" "1. Reducing max_tokens in your YAML config\n"
"2. Reducing context_length in your YAML config\n" "2. Reducing context_length in your YAML config\n"
"3. Using a model with larger context window" "3. Using a model with larger context window",
) )
elif "api_key" in error_msg.lower(): elif "api_key" in error_msg.lower():
show_error( show_error(
@ -347,7 +380,7 @@ def main():
"There seems to be an issue with the API key. Please:\n" "There seems to be an issue with the API key. Please:\n"
"1. Check if your API key is set correctly\n" "1. Check if your API key is set correctly\n"
"2. Verify the API key is valid\n" "2. Verify the API key is valid\n"
"3. Run 'swarms get-api-key' to get a new key" "3. Run 'swarms get-api-key' to get a new key",
) )
else: else:
show_error( show_error(
@ -355,7 +388,7 @@ def main():
f"An unexpected error occurred: {error_msg}\n" f"An unexpected error occurred: {error_msg}\n"
"1. Check your YAML configuration\n" "1. Check your YAML configuration\n"
"2. Verify your API keys are set\n" "2. Verify your API keys are set\n"
"3. Check network connectivity" "3. Check network connectivity",
) )
elif args.command == "book-call": elif args.command == "book-call":
webbrowser.open( webbrowser.open(

@ -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')}"
)
Loading…
Cancel
Save