structured outputs example

pull/798/head
Kye Gomez 1 month ago
parent a16b815bde
commit 9c78b39291

@ -325,6 +325,84 @@ agent.run(
``` ```
## Structured Outputs
1. Create a tool schema
2. Create a function schema
3. Create a tool list dictionary
4. Initialize the agent
5. Run the agent
6. Print the output
7. Convert the output to a dictionary
```python
from dotenv import load_dotenv
from swarms import Agent
from swarms.prompts.finance_agent_sys_prompt import (
FINANCIAL_AGENT_SYS_PROMPT,
)
from swarms.utils.str_to_dict import str_to_dict
load_dotenv()
tools = [
{
"type": "function",
"function": {
"name": "get_stock_price",
"description": "Retrieve the current stock price and related information for a specified company.",
"parameters": {
"type": "object",
"properties": {
"ticker": {
"type": "string",
"description": "The stock ticker symbol of the company, e.g. AAPL for Apple Inc.",
},
"include_history": {
"type": "boolean",
"description": "Indicates whether to include historical price data along with the current price.",
},
"time": {
"type": "string",
"format": "date-time",
"description": "Optional parameter to specify the time for which the stock data is requested, in ISO 8601 format.",
},
},
"required": [
"ticker",
"include_history",
"time",
],
},
},
}
]
# Initialize the agent
agent = Agent(
agent_name="Financial-Analysis-Agent",
agent_description="Personal finance advisor agent",
system_prompt=FINANCIAL_AGENT_SYS_PROMPT,
max_loops=1,
tools_list_dictionary=tools,
)
out = agent.run(
"What is the current stock price for Apple Inc. (AAPL)? Include historical price data.",
)
print(out)
print(type(out))
print(str_to_dict(out))
print(type(str_to_dict(out)))
```
------- -------
### Misc Agent Settings ### Misc Agent Settings

@ -294,18 +294,18 @@ nav:
- Agent Marketplace: "swarms_platform/share_discover.md" - Agent Marketplace: "swarms_platform/share_discover.md"
- Swarm Platform API Keys: "swarms_platform/apikeys.md" - Swarm Platform API Keys: "swarms_platform/apikeys.md"
- Account Management: "swarms_platform/account_management.md" - Account Management: "swarms_platform/account_management.md"
- Prompts API: # - Prompts API:
- Add Prompts: "swarms_platform/prompts/add_prompt.md" # - Add Prompts: "swarms_platform/prompts/add_prompt.md"
- Edit Prompts: "swarms_platform/prompts/edit_prompt.md" # - Edit Prompts: "swarms_platform/prompts/edit_prompt.md"
- Query Prompts: "swarms_platform/prompts/fetch_prompts.md" # - Query Prompts: "swarms_platform/prompts/fetch_prompts.md"
- Agents API: # - Agents API:
- Add Agents: "swarms_platform/agents/agents_api.md" # - Add Agents: "swarms_platform/agents/agents_api.md"
- Query Agents: "swarms_platform/agents/fetch_agents.md" # - Query Agents: "swarms_platform/agents/fetch_agents.md"
- Edit Agents: "swarms_platform/agents/edit_agent.md" # - Edit Agents: "swarms_platform/agents/edit_agent.md"
- Telemetry API: # - Telemetry API:
- PUT: "swarms_platform/telemetry/index.md" # - PUT: "swarms_platform/telemetry/index.md"
- Swarms Wallet API: # - Swarms Wallet API:
- Overview: "swarms/wallet/api.md" # - Overview: "swarms/wallet/api.md"
# - Tools API: # - Tools API:
# - Overview: "swarms_platform/tools_api.md" # - Overview: "swarms_platform/tools_api.md"
# - Add Tools: "swarms_platform/fetch_tools.md" # - Add Tools: "swarms_platform/fetch_tools.md"

@ -5,7 +5,6 @@
**Base URL**: `https://api.swarms.world` **Base URL**: `https://api.swarms.world`
**API Key Management**: [https://swarms.world/platform/api-keys](https://swarms.world/platform/api-keys) **API Key Management**: [https://swarms.world/platform/api-keys](https://swarms.world/platform/api-keys)
## Overview ## Overview
The Swarms API provides a robust, scalable infrastructure for deploying and managing intelligent agent swarms in the cloud. This enterprise-grade API enables organizations to create, execute, and orchestrate sophisticated AI agent workflows without managing the underlying infrastructure. The Swarms API provides a robust, scalable infrastructure for deploying and managing intelligent agent swarms in the cloud. This enterprise-grade API enables organizations to create, execute, and orchestrate sophisticated AI agent workflows without managing the underlying infrastructure.

@ -0,0 +1,12 @@
from swarms.structs.deep_research_swarm import DeepResearchSwarm
swarm = DeepResearchSwarm(
name="Deep Research Swarm",
description="A swarm that conducts comprehensive research across multiple domains",
max_loops=1,
)
swarm.run(
"What are the biggest gas and oil companies in russia? Only provide 3 queries"
)

@ -0,0 +1,262 @@
import requests
from dotenv import load_dotenv
from swarms import Agent, SequentialWorkflow
load_dotenv()
# Technical Analysis Agent
TECHNICAL_ANALYST_PROMPT = """
You are an expert Technical Analysis agent specializing in cryptocurrency markets. Your role is to:
1. Analyze price patterns, trends, and indicators with specific numerical data.
2. Identify key support and resistance levels with exact price points.
3. Evaluate market momentum and volume patterns using quantitative metrics.
4. Provide detailed technical insights based on chart patterns, including Fibonacci retracement levels and moving averages.
5. Monitor and interpret trading indicators (RSI, MACD, Bollinger Bands) with specific values.
When analyzing data, focus on:
- Price action and volume analysis, including percentage changes and volume spikes.
- Chart pattern recognition, such as head and shoulders, double tops/bottoms, and triangles.
- Indicator divergences and confluences, providing specific indicator values.
- Market structure and trend analysis, including bullish/bearish trends with defined price ranges.
- Support/resistance levels and price zones, specifying exact price levels.
Provide your analysis in a clear, structured format with bullet points for key findings, including numerical data.
Emphasize objective technical analysis without making direct price predictions.
"""
technical_agent = Agent(
agent_name="Technical-Analyst",
system_prompt=TECHNICAL_ANALYST_PROMPT,
model_name="gpt-4o",
max_loops=1,
verbose=True,
dynamic_temperature_enabled=True,
)
# Market Sentiment Agent
SENTIMENT_ANALYST_PROMPT = """
You are a Market Sentiment Analysis specialist focusing on social and market psychology. Your tasks:
1. Analyze social media sentiment across platforms with specific sentiment scores.
2. Monitor community engagement metrics, including likes, shares, and comments.
3. Track market fear/greed indicators with numerical values.
4. Evaluate news impact on market sentiment, providing specific examples.
5. Assess institutional interest and whale activity, detailing transaction sizes.
Focus areas:
- Social media sentiment trends, providing percentage changes.
- Community growth and engagement metrics, including follower counts.
- News sentiment analysis, quantifying positive/negative impacts.
- Institutional investment flows, detailing specific amounts.
- Whale wallet activity monitoring, providing transaction details.
Provide objective sentiment analysis using multiple data sources.
Emphasize data-driven insights rather than speculation.
"""
# Risk Management Agent
RISK_MANAGER_PROMPT = """
You are a Risk Management specialist focused on market risk assessment. Your role involves:
1. Identifying potential market risks and vulnerabilities with specific examples.
2. Analyzing market volatility and liquidity using quantitative measures.
3. Evaluating correlation with broader markets, providing correlation coefficients.
4. Assessing regulatory and operational risks, detailing specific regulations.
5. Monitoring market manipulation indicators with defined thresholds.
Key focus areas:
- Volatility analysis and risk metrics, including standard deviation and beta values.
- Liquidity depth assessment, providing order book metrics.
- Correlation analysis with major assets, detailing specific correlations.
- Regulatory compliance risks, specifying relevant regulations.
- Smart contract and protocol risks, detailing potential vulnerabilities.
Provide comprehensive risk assessment with clear risk ratings and mitigation strategies.
Focus on identifying both obvious and subtle risk factors.
"""
risk_agent = Agent(
agent_name="Risk-Manager",
system_prompt=RISK_MANAGER_PROMPT,
model_name="gpt-4o",
max_loops=1,
verbose=True,
dynamic_temperature_enabled=True,
)
# Macro Analysis Agent
MACRO_ANALYST_PROMPT = """
You are a Macro Analysis specialist focusing on broader market context. Your role involves:
1. Analyzing global economic trends with specific indicators.
2. Evaluating crypto market cycles, providing cycle duration and phases.
3. Monitoring regulatory developments, detailing specific changes.
4. Assessing cross-market correlations with numerical data.
5. Analyzing institutional trends, providing investment amounts.
Key focus areas:
- Global economic indicators, including GDP growth rates and inflation.
- Crypto market cycle analysis, detailing historical price movements.
- Regulatory landscape changes, specifying impacts on the market.
- Institutional adoption trends, quantifying investment flows.
- Cross-asset correlations, providing correlation coefficients.
Provide macro context and analysis of how broader trends affect the crypto market.
Focus on identifying major market-moving factors and trends.
"""
macro_agent = Agent(
agent_name="Macro-Analyst",
system_prompt=MACRO_ANALYST_PROMPT,
model_name="gpt-4o",
max_loops=1,
verbose=True,
dynamic_temperature_enabled=True,
)
# Create group chat with all agents
agents = [technical_agent, risk_agent, technical_agent]
def fetch_htx_data(coin_name: str):
base_url = "https://api.huobi.pro"
# Fetch market ticker data for the coin
ticker_endpoint = "/market/detail/merged"
ticker_params = {
"symbol": f"{coin_name.lower()}usdt"
} # Assuming USDT pairing
try:
ticker_response = requests.get(
base_url + ticker_endpoint, params=ticker_params
)
ticker_data = ticker_response.json()
if ticker_data["status"] != "ok":
return {
"error": "Unable to fetch ticker data",
"details": ticker_data,
}
# Fetch order book data for the coin
order_book_endpoint = "/market/depth"
order_book_params = {
"symbol": f"{coin_name.lower()}usdt",
"type": "step0",
}
order_book_response = requests.get(
base_url + order_book_endpoint, params=order_book_params
)
order_book_data = order_book_response.json()
if order_book_data["status"] != "ok":
return {
"error": "Unable to fetch order book data",
"details": order_book_data,
}
# Fetch recent trades for the coin
trades_endpoint = "/market/history/trade"
trades_params = {
"symbol": f"{coin_name.lower()}usdt",
"size": 200,
}
trades_response = requests.get(
base_url + trades_endpoint, params=trades_params
)
trades_data = trades_response.json()
if trades_data["status"] != "ok":
return {
"error": "Unable to fetch trade data",
"details": trades_data,
}
# Fetch Kline (Candlestick) data
kline_endpoint = "/market/history/kline"
kline_params = {
"symbol": f"{coin_name.lower()}usdt",
"period": "1day",
"size": 200,
}
kline_response = requests.get(
base_url + kline_endpoint, params=kline_params
)
kline_data = kline_response.json()
if kline_data["status"] != "ok":
return {
"error": "Unable to fetch kline data",
"details": kline_data,
}
# Format and prepare data for a single coin
formatted_data = {
"coin": coin_name.upper(),
"ticker": {
"current_price": ticker_data["tick"].get("close"),
"high": ticker_data["tick"].get("high"),
"low": ticker_data["tick"].get("low"),
"open": ticker_data["tick"].get("open"),
"volume": ticker_data["tick"].get("vol"),
"amount": ticker_data["tick"].get("amount"),
"count": ticker_data["tick"].get("count"),
},
"order_book": {
"bids": [
{"price": bid[0], "amount": bid[1]}
for bid in order_book_data["tick"].get("bids", [])
],
"asks": [
{"price": ask[0], "amount": ask[1]}
for ask in order_book_data["tick"].get("asks", [])
],
},
"recent_trades": [
{
"price": trade["data"][0].get("price"),
"amount": trade["data"][0].get("amount"),
"direction": trade["data"][0].get("direction"),
"trade_id": trade["data"][0].get("id"),
"timestamp": trade["data"][0].get("ts"),
}
for trade in trades_data.get("data", [])
],
"kline_data": [
{
"timestamp": kline["id"],
"open": kline["open"],
"close": kline["close"],
"high": kline["high"],
"low": kline["low"],
"volume": kline["vol"],
"amount": kline.get("amount"),
}
for kline in kline_data.get("data", [])
],
}
return formatted_data
except requests.exceptions.RequestException as e:
return {"error": "HTTP request failed", "details": str(e)}
data = fetch_htx_data("eth")
swarm = SequentialWorkflow(
name="htx-swarm",
description="Swarm that analyzes data from HTX",
agents=agents,
max_loops=1,
)
out = swarm.run(
f"Analyze the price action of the swarms coin over the past week. {str(data)} Conduct an analysis of the coin and provide a detailed report."
)
print(out)

@ -278,6 +278,7 @@ research_agent = Agent(
system_prompt=RESEARCH_AGENT_PROMPT, system_prompt=RESEARCH_AGENT_PROMPT,
max_loops=1, # Allow multiple iterations for thorough research max_loops=1, # Allow multiple iterations for thorough research
tools_list_dictionary=tools, tools_list_dictionary=tools,
model_name="gpt-4o-mini",
) )
@ -298,6 +299,7 @@ class DeepResearchSwarm:
max_workers: int = os.cpu_count() max_workers: int = os.cpu_count()
* 2, # Let the system decide optimal thread count * 2, # Let the system decide optimal thread count
token_count: bool = False, token_count: bool = False,
research_model_name: str = "gpt-4o-mini",
): ):
self.name = name self.name = name
self.description = description self.description = description
@ -306,6 +308,7 @@ class DeepResearchSwarm:
self.nice_print = nice_print self.nice_print = nice_print
self.output_type = output_type self.output_type = output_type
self.max_workers = max_workers self.max_workers = max_workers
self.research_model_name = research_model_name
self.reliability_check() self.reliability_check()
self.conversation = Conversation(token_count=token_count) self.conversation = Conversation(token_count=token_count)
@ -448,6 +451,9 @@ class DeepResearchSwarm:
self.conversation, type=self.output_type self.conversation, type=self.output_type
) )
def run(self, task: str):
return self.step(task)
# # Example usage # # Example usage
# if __name__ == "__main__": # if __name__ == "__main__":

@ -1,63 +0,0 @@
# 🚀 Latest Updates to Swarms - Twitter Thread
🧵 Thread: Exciting new features in Swarms - the powerful AI agent framework! #AI #AGI #Development
1/9 🤖 Introducing the ReasoningDuo - a revolutionary dual-agent system that combines reasoning and execution agents for more robust and reliable outputs! Perfect for complex problem-solving tasks.
2/9 🔄 New Self-Consistency Agent with parallel processing:
- Generates multiple independent responses
- Uses ThreadPoolExecutor for concurrent execution
- Aggregates results for higher accuracy
#AI #ParallelProcessing
3/9 🎯 The ReasoningAgentRouter is here! Dynamically select and execute different reasoning strategies:
- ReasoningDuo
- Self-Consistency
- Iterative Reflective Expansion (IRE)
#AIAgents
4/9 💡 Advanced Reasoning Capabilities:
- Structured problem analysis
- Multiple solution exploration
- Bias detection and transparency
- Error handling strategies
#ArtificialIntelligence
5/9 ⚡️ Performance Improvements:
- Concurrent response generation
- Batched task processing
- Optimized thread management
- Improved error handling
#Performance
6/9 🎛️ Customization Options:
- Adjustable sample sizes
- Flexible model selection
- Customizable system prompts
- Multiple output formats
#Flexibility
7/9 🔍 Enhanced Evaluation Features:
- Response validation
- Answer checking
- Majority voting system
- Comprehensive logging
#QualityAssurance
8/9 📊 New Output Types:
- Dictionary format
- List format
- Conversation history
- Structured analysis
#DataScience
9/9 🌟 Coming Soon:
- More agent types
- Enhanced routing strategies
- Advanced aggregation methods
- Expanded model support
Stay tuned! #FutureOfAI
---
Follow for more updates on Swarms! 🚀
#AI #MachineLearning #AGI #Development
Loading…
Cancel
Save