diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml index bc32c5be..476e51dd 100644 --- a/docs/mkdocs.yml +++ b/docs/mkdocs.yml @@ -207,6 +207,7 @@ nav: - Swarms API Examples: - Medical Swarm: "swarms/examples/swarms_api_medical.md" + - Finance Swarm: "swarms/examples/swarms_api_finance.md" - ML Model Code Generation Swarm: "swarms/examples/swarms_api_ml_model.md" - Various Model Providers: - OpenAI: "swarms/examples/openai_example.md" diff --git a/docs/swarms/examples/swarms_api_finance.md b/docs/swarms/examples/swarms_api_finance.md new file mode 100644 index 00000000..8d7452ac --- /dev/null +++ b/docs/swarms/examples/swarms_api_finance.md @@ -0,0 +1,127 @@ + +# Finance Swarm Example + +1. Get your API key from the Swarms API dashboard [HERE](https://swarms.world/platform/api-keys) +2. Create a `.env` file in the root directory and add your API key: + +```bash +SWARMS_API_KEY= +``` + +3. Create a Python script to create and trigger the financial swarm: + + +```python +import os +import requests +from dotenv import load_dotenv +import json + +load_dotenv() + +# Retrieve API key securely from .env +API_KEY = os.getenv("SWARMS_API_KEY") +BASE_URL = "https://swarms-api-285321057562.us-east1.run.app" + +# Headers for secure API communication +headers = {"x-api-key": API_KEY, "Content-Type": "application/json"} + +def create_financial_swarm(equity_data: str): + """ + Constructs and triggers a full-stack financial swarm consisting of three agents: + Equity Analyst, Risk Assessor, and Market Advisor. + Each agent is provided with a comprehensive, detailed system prompt to ensure high reliability. + """ + + payload = { + "swarm_name": "Enhanced Financial Analysis Swarm", + "description": "A swarm of agents specialized in performing comprehensive financial analysis, risk assessment, and market recommendations.", + "agents": [ + { + "agent_name": "Equity Analyst", + "description": "Agent specialized in analyzing equities data to provide insights on stock performance and valuation.", + "system_prompt": ( + "You are an experienced equity analyst with expertise in financial markets and stock valuation. " + "Your role is to analyze the provided equities data, including historical performance, financial statements, and market trends. " + "Provide a detailed analysis of the stock's potential, including valuation metrics and growth prospects. " + "Consider macroeconomic factors, industry trends, and company-specific news. Your analysis should be clear, actionable, and well-supported by data." + ), + "model_name": "openai/gpt-4o", + "role": "worker", + "max_loops": 1, + "max_tokens": 4000, + "temperature": 0.3, + "auto_generate_prompt": False + }, + { + "agent_name": "Risk Assessor", + "description": "Agent responsible for evaluating the risks associated with equity investments.", + "system_prompt": ( + "You are a certified risk management professional with expertise in financial risk assessment. " + "Your task is to evaluate the risks associated with the provided equities data, including market risk, credit risk, and operational risk. " + "Provide a comprehensive risk analysis, including potential scenarios and their impact on investment performance. " + "Your output should be detailed, reliable, and compliant with current risk management standards." + ), + "model_name": "openai/gpt-4o", + "role": "worker", + "max_loops": 1, + "max_tokens": 3000, + "temperature": 0.2, + "auto_generate_prompt": False + }, + { + "agent_name": "Market Advisor", + "description": "Agent dedicated to suggesting investment strategies based on market conditions and equity analysis.", + "system_prompt": ( + "You are a knowledgeable market advisor with expertise in investment strategies and portfolio management. " + "Based on the analysis provided by the Equity Analyst and the risk assessment, your task is to recommend a comprehensive investment strategy. " + "Your suggestions should include asset allocation, diversification strategies, and considerations for market conditions. " + "Explain the rationale behind each recommendation and reference relevant market data where applicable. " + "Your recommendations should be reliable, detailed, and clearly prioritized based on risk and return." + ), + "model_name": "openai/gpt-4o", + "role": "worker", + "max_loops": 1, + "max_tokens": 5000, + "temperature": 0.3, + "auto_generate_prompt": False + } + ], + "max_loops": 1, + "swarm_type": "SequentialWorkflow", + "task": equity_data, + } + + # Payload includes the equity data as the task to be processed by the swarm + + response = requests.post( + f"{BASE_URL}/v1/swarm/completions", + headers=headers, + json=payload, + ) + + if response.status_code == 200: + print("Swarm successfully executed!") + return json.dumps(response.json(), indent=4) + else: + print(f"Error {response.status_code}: {response.text}") + return None + + +# Example Equity Data for the Swarm to analyze +if __name__ == "__main__": + equity_data = ( + "Analyze the equity data for Company XYZ, which has shown a 15% increase in revenue over the last quarter, " + "with a P/E ratio of 20 and a market cap of $1 billion. Consider the current market conditions and potential risks." + ) + + financial_output = create_financial_swarm(equity_data) + print(financial_output) +``` + +4. Run the script: + +```bash +python financial_swarm.py +``` + diff --git a/docs/swarms/examples/swarms_api_medical.md b/docs/swarms/examples/swarms_api_medical.md index 6482f219..3ac7f47b 100644 --- a/docs/swarms/examples/swarms_api_medical.md +++ b/docs/swarms/examples/swarms_api_medical.md @@ -48,7 +48,7 @@ def create_medical_swarm(patient_case: str): ), "model_name": "openai/gpt-4o", "role": "worker", - "max_loops": 2, + "max_loops": 1, "max_tokens": 4000, "temperature": 0.3, "auto_generate_prompt": False @@ -88,18 +88,15 @@ def create_medical_swarm(patient_case: str): "auto_generate_prompt": False } ], - "max_loops": 3, - "swarm_type": "SequentialWorkflow" - } - - # Payload includes the patient case as the task to be processed by the swarm - payload = { + "max_loops": 1, + "swarm_type": "SequentialWorkflow", "task": patient_case, - "swarm": payload } + # Payload includes the patient case as the task to be processed by the swar + response = requests.post( - f"{BASE_URL}/swarm/completion", + f"{BASE_URL}/v1/swarm/completions", headers=headers, json=payload, ) @@ -122,4 +119,10 @@ if __name__ == "__main__": diagnostic_output = create_medical_swarm(patient_case) print(diagnostic_output) +``` + +4. Run the script: + +```bash +python medical_swarm.py ``` \ No newline at end of file diff --git a/medical_swarm.py b/medical_swarm.py new file mode 100644 index 00000000..0defe510 --- /dev/null +++ b/medical_swarm.py @@ -0,0 +1,105 @@ +import os +import requests +from dotenv import load_dotenv +import json + +load_dotenv() + +# Retrieve API key securely from .env +API_KEY = os.getenv("SWARMS_API_KEY") +BASE_URL = "https://swarms-api-285321057562.us-east1.run.app" + +# Headers for secure API communication +headers = {"x-api-key": API_KEY, "Content-Type": "application/json"} + +def create_financial_swarm(equity_data: str): + """ + Constructs and triggers a full-stack financial swarm consisting of three agents: + Equity Analyst, Risk Assessor, and Market Advisor. + Each agent is provided with a comprehensive, detailed system prompt to ensure high reliability. + """ + + payload = { + "swarm_name": "Enhanced Financial Analysis Swarm", + "description": "A swarm of agents specialized in performing comprehensive financial analysis, risk assessment, and market recommendations.", + "agents": [ + { + "agent_name": "Equity Analyst", + "description": "Agent specialized in analyzing equities data to provide insights on stock performance and valuation.", + "system_prompt": ( + "You are an experienced equity analyst with expertise in financial markets and stock valuation. " + "Your role is to analyze the provided equities data, including historical performance, financial statements, and market trends. " + "Provide a detailed analysis of the stock's potential, including valuation metrics and growth prospects. " + "Consider macroeconomic factors, industry trends, and company-specific news. Your analysis should be clear, actionable, and well-supported by data." + ), + "model_name": "openai/gpt-4o", + "role": "worker", + "max_loops": 1, + "max_tokens": 4000, + "temperature": 0.3, + "auto_generate_prompt": False + }, + { + "agent_name": "Risk Assessor", + "description": "Agent responsible for evaluating the risks associated with equity investments.", + "system_prompt": ( + "You are a certified risk management professional with expertise in financial risk assessment. " + "Your task is to evaluate the risks associated with the provided equities data, including market risk, credit risk, and operational risk. " + "Provide a comprehensive risk analysis, including potential scenarios and their impact on investment performance. " + "Your output should be detailed, reliable, and compliant with current risk management standards." + ), + "model_name": "openai/gpt-4o", + "role": "worker", + "max_loops": 1, + "max_tokens": 3000, + "temperature": 0.2, + "auto_generate_prompt": False + }, + { + "agent_name": "Market Advisor", + "description": "Agent dedicated to suggesting investment strategies based on market conditions and equity analysis.", + "system_prompt": ( + "You are a knowledgeable market advisor with expertise in investment strategies and portfolio management. " + "Based on the analysis provided by the Equity Analyst and the risk assessment, your task is to recommend a comprehensive investment strategy. " + "Your suggestions should include asset allocation, diversification strategies, and considerations for market conditions. " + "Explain the rationale behind each recommendation and reference relevant market data where applicable. " + "Your recommendations should be reliable, detailed, and clearly prioritized based on risk and return." + ), + "model_name": "openai/gpt-4o", + "role": "worker", + "max_loops": 1, + "max_tokens": 5000, + "temperature": 0.3, + "auto_generate_prompt": False + } + ], + "max_loops": 1, + "swarm_type": "SequentialWorkflow", + "task": equity_data, + } + + # Payload includes the equity data as the task to be processed by the swarm + + response = requests.post( + f"{BASE_URL}/v1/swarm/completions", + headers=headers, + json=payload, + ) + + if response.status_code == 200: + print("Swarm successfully executed!") + return json.dumps(response.json(), indent=4) + else: + print(f"Error {response.status_code}: {response.text}") + return None + + +# Example Equity Data for the Swarm to analyze +if __name__ == "__main__": + equity_data = ( + "Analyze the equity data for Company XYZ, which has shown a 15% increase in revenue over the last quarter, " + "with a P/E ratio of 20 and a market cap of $1 billion. Consider the current market conditions and potential risks." + ) + + financial_output = create_financial_swarm(equity_data) + print(financial_output) \ No newline at end of file diff --git a/swarms/agents/consistency_agent.py b/swarms/agents/consistency_agent.py index 5ed38c10..71094644 100644 --- a/swarms/agents/consistency_agent.py +++ b/swarms/agents/consistency_agent.py @@ -15,7 +15,9 @@ You are a reasoning agent designed for complex problem-solving and decision-maki def aggregation_agent( - responses: List[str], prompt: str = majority_voting_prompt + responses: List[str], + prompt: str = majority_voting_prompt, + model_name: str = "gpt-4o-mini", ) -> str: """ Aggregates a list of responses into a single final answer. @@ -25,7 +27,7 @@ def aggregation_agent( agent = Agent( agent_name="Aggregation-Agent", description="An agent that aggregates a list of responses into a single final answer.", - model_name="gpt-4o-mini", + model_name=model_name, system_prompt=prompt, max_loops=1, ) @@ -38,6 +40,8 @@ def aggregation_agent( class SelfConsistencyAgent(Agent): def __init__( self, + name: str = "Self-Consistency-Agent", + description: str = "An agent that uses self consistency to generate a final answer.", num_samples: int = 5, return_list: bool = False, max_loops: int = 1, @@ -54,7 +58,10 @@ class SelfConsistencyAgent(Agent): **kwargs: Other keyword arguments passed to the base Agent. """ super().__init__( - **kwargs, system_prompt=CONSISTENCY_SYSTEM_PROMPT + name=name, + description=description, + system_prompt=CONSISTENCY_SYSTEM_PROMPT, + **kwargs, ) self.num_samples = num_samples self.conversation = Conversation() diff --git a/swarms/agents/i_agent.py b/swarms/agents/i_agent.py index 8bbfb63a..0fabff17 100644 --- a/swarms/agents/i_agent.py +++ b/swarms/agents/i_agent.py @@ -43,11 +43,12 @@ class IterativeReflectiveExpansion: def __init__( self, - agent: Agent, + agent: Agent = None, max_iterations: int = 5, return_list: bool = False, return_dict: bool = False, prompt: str = GENERAL_REASONING_AGENT_SYS_PROMPT, + model_name: str = "gpt-4o-mini", ) -> None: """ Initialize the Iterative Reflective Expansion engine. @@ -57,30 +58,30 @@ class IterativeReflectiveExpansion: """ self.agent = agent self.max_iterations = max_iterations - self.conversation = Conversation() self.return_list = return_list self.return_dict = return_dict + self.conversation = Conversation() + self.agent = Agent( agent_name="General-Reasoning-Agent", system_prompt=prompt, - model_name="gpt-4o-mini", + model_name=model_name, max_loops=1, + dynamic_temperature_enabled=True, ) - def generate_initial_hypotheses( - self, problem_input: str - ) -> List[str]: + def generate_initial_hypotheses(self, task: str) -> List[str]: """ Generate an initial set of reasoning hypotheses based on the problem input. - :param problem_input: The problem statement. + :param task: The problem statement. :return: A list of candidate reasoning paths/hypotheses. """ logger.info("Generating initial hypotheses for the problem.") prompt = ( f"Given the following problem:\n\n" - f"'{problem_input}'\n\n" + f"'{task}'\n\n" "Generate a list of possible approaches and strategies to solve it. " "Present each approach on a new line." ) @@ -235,19 +236,17 @@ class IterativeReflectiveExpansion: logger.debug(f"Synthesized solution: {solution}") return solution - def run(self, problem_input: str) -> str: + def run(self, task: str) -> str: """ Execute the Iterative Reflective Expansion process on the provided problem. - :param problem_input: The problem statement. + :param task: The problem statement. :return: The final solution generated after iterative reasoning. """ logger.info( - f"Starting iterative reflective expansion for problem: {problem_input}" - ) - candidate_paths = self.generate_initial_hypotheses( - problem_input + f"Starting iterative reflective expansion for problem: {task}" ) + candidate_paths = self.generate_initial_hypotheses(task) memory_pool: List[str] = [] for iteration in range(self.max_iterations):