diff --git a/README.md b/README.md index 2064c281..0f2b21da 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml index 49c3038f..0c7bcb6f 100644 --- a/docs/mkdocs.yml +++ b/docs/mkdocs.yml @@ -294,18 +294,18 @@ nav: - Agent Marketplace: "swarms_platform/share_discover.md" - Swarm Platform API Keys: "swarms_platform/apikeys.md" - Account Management: "swarms_platform/account_management.md" - - Prompts API: - - Add Prompts: "swarms_platform/prompts/add_prompt.md" - - Edit Prompts: "swarms_platform/prompts/edit_prompt.md" - - Query Prompts: "swarms_platform/prompts/fetch_prompts.md" - - Agents API: - - Add Agents: "swarms_platform/agents/agents_api.md" - - Query Agents: "swarms_platform/agents/fetch_agents.md" - - Edit Agents: "swarms_platform/agents/edit_agent.md" - - Telemetry API: - - PUT: "swarms_platform/telemetry/index.md" - - Swarms Wallet API: - - Overview: "swarms/wallet/api.md" + # - Prompts API: + # - Add Prompts: "swarms_platform/prompts/add_prompt.md" + # - Edit Prompts: "swarms_platform/prompts/edit_prompt.md" + # - Query Prompts: "swarms_platform/prompts/fetch_prompts.md" + # - Agents API: + # - Add Agents: "swarms_platform/agents/agents_api.md" + # - Query Agents: "swarms_platform/agents/fetch_agents.md" + # - Edit Agents: "swarms_platform/agents/edit_agent.md" + # - Telemetry API: + # - PUT: "swarms_platform/telemetry/index.md" + # - Swarms Wallet API: + # - Overview: "swarms/wallet/api.md" # - Tools API: # - Overview: "swarms_platform/tools_api.md" # - Add Tools: "swarms_platform/fetch_tools.md" diff --git a/docs/swarms_cloud/swarms_api.md b/docs/swarms_cloud/swarms_api.md index 48ebc824..e8ee56c7 100644 --- a/docs/swarms_cloud/swarms_api.md +++ b/docs/swarms_cloud/swarms_api.md @@ -5,7 +5,6 @@ **Base URL**: `https://api.swarms.world` **API Key Management**: [https://swarms.world/platform/api-keys](https://swarms.world/platform/api-keys) - ## 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. diff --git a/consistency_agent.py b/examples/consistency_agent.py similarity index 100% rename from consistency_agent.py rename to examples/consistency_agent.py diff --git a/examples/deep_research_example.py b/examples/deep_research_example.py new file mode 100644 index 00000000..c575cb42 --- /dev/null +++ b/examples/deep_research_example.py @@ -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" +) diff --git a/examples/htx_swarm.py b/examples/htx_swarm.py new file mode 100644 index 00000000..8a461c8f --- /dev/null +++ b/examples/htx_swarm.py @@ -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) diff --git a/iterative_agent.py b/examples/iterative_agent.py similarity index 100% rename from iterative_agent.py rename to examples/iterative_agent.py diff --git a/malt_example.py b/examples/malt_example.py similarity index 100% rename from malt_example.py rename to examples/malt_example.py diff --git a/reasoning_agent_router.py b/examples/reasoning_agent_router.py similarity index 100% rename from reasoning_agent_router.py rename to examples/reasoning_agent_router.py diff --git a/reasoning_duo_example.py b/examples/reasoning_duo_example.py similarity index 100% rename from reasoning_duo_example.py rename to examples/reasoning_duo_example.py diff --git a/medical_swarm.py b/examples/swarms_api_examples/medical_swarm.py similarity index 100% rename from medical_swarm.py rename to examples/swarms_api_examples/medical_swarm.py diff --git a/swarms/structs/deep_research_swarm.py b/swarms/structs/deep_research_swarm.py index 37f121a7..0dfa4aaa 100644 --- a/swarms/structs/deep_research_swarm.py +++ b/swarms/structs/deep_research_swarm.py @@ -278,6 +278,7 @@ research_agent = Agent( system_prompt=RESEARCH_AGENT_PROMPT, max_loops=1, # Allow multiple iterations for thorough research tools_list_dictionary=tools, + model_name="gpt-4o-mini", ) @@ -298,6 +299,7 @@ class DeepResearchSwarm: max_workers: int = os.cpu_count() * 2, # Let the system decide optimal thread count token_count: bool = False, + research_model_name: str = "gpt-4o-mini", ): self.name = name self.description = description @@ -306,6 +308,7 @@ class DeepResearchSwarm: self.nice_print = nice_print self.output_type = output_type self.max_workers = max_workers + self.research_model_name = research_model_name self.reliability_check() self.conversation = Conversation(token_count=token_count) @@ -448,6 +451,9 @@ class DeepResearchSwarm: self.conversation, type=self.output_type ) + def run(self, task: str): + return self.step(task) + # # Example usage # if __name__ == "__main__": diff --git a/swarms_updates.md b/swarms_updates.md deleted file mode 100644 index ab94c147..00000000 --- a/swarms_updates.md +++ /dev/null @@ -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 \ No newline at end of file