From a58a8d418de435d7f275b1d4564c5a5936aa50b9 Mon Sep 17 00:00:00 2001 From: Your Name Date: Sat, 12 Oct 2024 23:28:02 -0400 Subject: [PATCH] [README] --- README.md | 224 +++++++++++++++- new_swarms_docs.md | 638 --------------------------------------------- 2 files changed, 215 insertions(+), 647 deletions(-) diff --git a/README.md b/README.md index b66c8aff4..ef74cd51c 100644 --- a/README.md +++ b/README.md @@ -655,8 +655,30 @@ graph LR E --> F[End] ``` + + +### Methods + +| Method | Description | Parameters | Return Value | +|--------|-------------|------------|--------------| +| `__init__` | Initialize the SequentialWorkflow | `agents`: List of Agent objects
`max_loops`: Maximum number of iterations
`verbose`: Boolean for verbose output | None | +| `run` | Execute the workflow | `input_data`: Initial input for the first agent | Final output after all agents have processed | + +### Inputs + +| Input | Type | Description | +|-------|------|-------------| +| `agents` | List[Agent] | List of Agent objects to be executed sequentially | +| `max_loops` | int | Maximum number of times the entire sequence will be repeated | +| `verbose` | bool | If True, print detailed information during execution | + +### Output + +The `run` method returns the final output after all agents have processed the input sequentially. + In this example, each `Agent` represents a task that is executed sequentially. The output of each agent is passed to the next agent in the sequence until the maximum number of loops is reached. This workflow is particularly useful for tasks that require a series of steps to be executed in a specific order, such as data processing pipelines or complex calculations that rely on the output of previous steps. + ```python from swarms import Agent, SequentialWorkflow @@ -702,6 +724,29 @@ workflow.run( The `AgentRearrange` orchestration technique, inspired by Einops and einsum, allows you to define and map out the relationships between various agents. It provides a powerful tool for orchestrating complex workflows, enabling you to specify linear and sequential relationships such as `a -> a1 -> a2 -> a3`, or concurrent relationships where the first agent sends a message to 3 agents simultaneously: `a -> a1, a2, a3`. This level of customization allows for the creation of highly efficient and dynamic workflows, where agents can work in parallel or in sequence as needed. The `AgentRearrange` technique is a valuable addition to the swarms library, providing a new level of flexibility and control over the orchestration of agents. For more detailed information and examples, please refer to the [official documentation](https://docs.swarms.world/en/latest/swarms/structs/agent_rearrange/). + + +### Methods + +| Method | Description | Parameters | Return Value | +|--------|-------------|------------|--------------| +| `__init__` | Initialize the AgentRearrange | `agents`: List of Agent objects
`flow`: String describing the agent flow | None | +| `run` | Execute the workflow | `input_data`: Initial input for the first agent | Final output after all agents have processed | + +### Inputs + +| Input | Type | Description | +|-------|------|-------------| +| `agents` | List[Agent] | List of Agent objects to be orchestrated | +| `flow` | str | String describing the flow of agents (e.g., "A -> B, C") | + +### Output + +The `run` method returns the final output after all agents have processed the input according to the specified flow. + + + + ```python from swarms import Agent, AgentRearrange @@ -799,6 +844,33 @@ The `GraphSwarm` offers several benefits, including: By leveraging the `GraphSwarm`, complex workflows can be efficiently managed, and tasks can be executed in a coordinated and scalable manner. + +### Methods + +| Method | Description | Parameters | Return Value | +|--------|-------------|------------|--------------| +| `add_node` | Add a node to the graph | `node`: Node object | None | +| `add_edge` | Add an edge to the graph | `edge`: Edge object | None | +| `set_entry_points` | Set the entry points of the graph | `entry_points`: List of node IDs | None | +| `set_end_points` | Set the end points of the graph | `end_points`: List of node IDs | None | +| `visualize` | Generate a visual representation of the graph | None | String representation of the graph | +| `run` | Execute the workflow | None | Dictionary of execution results | + +### Inputs + +| Input | Type | Description | +|-------|------|-------------| +| `Node` | Object | Represents a node in the graph (agent or task) | +| `Edge` | Object | Represents an edge connecting two nodes | +| `entry_points` | List[str] | List of node IDs where the workflow starts | +| `end_points` | List[str] | List of node IDs where the workflow ends | + +### Output + +The `run` method returns a dictionary containing the execution results of all nodes in the graph. + + + ```python import os @@ -846,6 +918,29 @@ print("Execution results:", results) ## `MixtureOfAgents` This is an implementation based on the paper: "Mixture-of-Agents Enhances Large Language Model Capabilities" by together.ai, available at [https://arxiv.org/abs/2406.04692](https://arxiv.org/abs/2406.04692). It achieves state-of-the-art (SOTA) results on AlpacaEval 2.0, MT-Bench, and FLASK, surpassing GPT-4 Omni. This architecture is particularly suitable for tasks that require parallelization followed by sequential processing in another loop. + + +### Methods + +| Method | Description | Parameters | Return Value | +|--------|-------------|------------|--------------| +| `__init__` | Initialize the MixtureOfAgents | `name`: Name of the swarm
`agents`: List of Agent objects
`layers`: Number of processing layers
`final_agent`: Agent for final processing | None | +| `run` | Execute the swarm | `task`: Input task for the swarm | Final output after all agents have processed | + +### Inputs + +| Input | Type | Description | +|-------|------|-------------| +| `name` | str | Name of the swarm | +| `agents` | List[Agent] | List of Agent objects to be used in the swarm | +| `layers` | int | Number of processing layers in the swarm | +| `final_agent` | Agent | Agent responsible for final processing | + +### Output + +The `run` method returns the final output after all agents have processed the input according to the specified layers and final agent. + + ```python from swarms import Agent, OpenAIChat, MixtureOfAgents @@ -911,7 +1006,7 @@ print(out) ## SpreadSheetSwarm -A revolutionary swarm architecture designed for concurrent management and oversight of thousands of agents, facilitating a one-to-many approach for efficient task processing and output analysis. +The `SpreadSheetSwarm` is designed for concurrent management and oversight of thousands of agents, facilitating a one-to-many approach for efficient task processing and output analysis. ### Key Features @@ -920,6 +1015,30 @@ A revolutionary swarm architecture designed for concurrent management and oversi * **Scalability**: Supports the integration of thousands of agents, making it an ideal solution for large-scale task processing and data analysis. +### Methods + +| Method | Description | Parameters | Return Value | +|--------|-------------|------------|--------------| +| `__init__` | Initialize the SpreadSheetSwarm | `name`: Name of the swarm
`description`: Description of the swarm
`agents`: List of Agent objects
`autosave_on`: Boolean to enable autosave
`save_file_path`: Path to save the spreadsheet
`run_all_agents`: Boolean to run all agents or not
`max_loops`: Maximum number of loops | None | +| `run` | Execute the swarm | `task`: Input task for the swarm | Dictionary of agent outputs | + +### Inputs + +| Input | Type | Description | +|-------|------|-------------| +| `name` | str | Name of the swarm | +| `description` | str | Description of the swarm's purpose | +| `agents` | List[Agent] | List of Agent objects to be used in the swarm | +| `autosave_on` | bool | Enable autosaving of results | +| `save_file_path` | str | Path to save the spreadsheet results | +| `run_all_agents` | bool | Whether to run all agents or select based on relevance | +| `max_loops` | int | Maximum number of processing loops | + +### Output + +The `run` method returns a dictionary containing the outputs of each agent that processed the task. + + [Learn more at the docs here:](https://docs.swarms.world/en/latest/swarms/structs/spreadsheet_swarm/) ```python @@ -1089,37 +1208,123 @@ swarm.run( ## `ForestSwarm` The `ForestSwarm` architecture is designed for efficient task assignment by dynamically selecting the most suitable agent from a collection of trees. This is achieved through asynchronous task processing, where agents are chosen based on their relevance to the task at hand. The relevance is determined by calculating the similarity between the system prompts associated with each agent and the keywords present in the task itself. For a more in-depth understanding of how `ForestSwarm` works, please refer to the [official documentation](https://docs.swarms.world/en/latest/swarms/structs/forest_swarm/). + + +### Methods + +| Method | Description | Parameters | Return Value | +|--------|-------------|------------|--------------| +| `__init__` | Initialize the ForestSwarm | `trees`: List of Tree objects | None | +| `run` | Execute the ForestSwarm | `task`: Input task for the swarm | Output from the most relevant agent | + +### Inputs + +| Input | Type | Description | +|-------|------|-------------| +| `trees` | List[Tree] | List of Tree objects, each containing TreeAgent objects | +| `task` | str | The task to be processed by the ForestSwarm | + +### Output + +The `run` method returns the output from the most relevant agent selected based on the input task. + + ```python from swarms.structs.tree_swarm import TreeAgent, Tree, ForestSwarm -# Example Usage: # Create agents with varying system prompts and dynamically generated distances/keywords agents_tree1 = [ TreeAgent( - system_prompt="Stock Analysis Agent", + system_prompt="""You are an expert Stock Analysis Agent with deep knowledge of financial markets, technical analysis, and fundamental analysis. Your primary function is to analyze stock performance, market trends, and provide actionable insights. When analyzing stocks: + +1. Always start with a brief overview of the current market conditions. +2. Use a combination of technical indicators (e.g., moving averages, RSI, MACD) and fundamental metrics (e.g., P/E ratio, EPS growth, debt-to-equity). +3. Consider both short-term and long-term perspectives in your analysis. +4. Provide clear buy, hold, or sell recommendations with supporting rationale. +5. Highlight potential risks and opportunities specific to each stock or sector. +6. Use bullet points for clarity when listing key points or metrics. +7. If relevant, compare the stock to its peers or sector benchmarks. + +Remember to maintain objectivity and base your analysis on factual data. If asked about future performance, always include a disclaimer about market unpredictability. Your goal is to provide comprehensive, accurate, and actionable stock analysis to inform investment decisions.""", agent_name="Stock Analysis Agent", ), TreeAgent( - system_prompt="Financial Planning Agent", + system_prompt="""You are a highly skilled Financial Planning Agent, specializing in personal and corporate financial strategies. Your role is to provide comprehensive financial advice tailored to each client's unique situation. When creating financial plans: + +1. Begin by asking key questions about the client's financial goals, current situation, and risk tolerance. +2. Develop a holistic view of the client's finances, including income, expenses, assets, and liabilities. +3. Create detailed, step-by-step action plans to achieve financial goals. +4. Provide specific recommendations for budgeting, saving, and investing. +5. Consider tax implications and suggest tax-efficient strategies. +6. Incorporate risk management and insurance planning into your recommendations. +7. Use charts or tables to illustrate financial projections and scenarios. +8. Regularly suggest reviewing and adjusting the plan as circumstances change. + +Always prioritize the client's best interests and adhere to fiduciary standards. Explain complex financial concepts in simple terms, and be prepared to justify your recommendations with data and reasoning.""", agent_name="Financial Planning Agent", ), TreeAgent( agent_name="Retirement Strategy Agent", - system_prompt="Retirement Strategy Agent", + system_prompt="""You are a specialized Retirement Strategy Agent, focused on helping individuals and couples plan for a secure and comfortable retirement. Your expertise covers various aspects of retirement planning, including savings strategies, investment allocation, and income generation during retirement. When developing retirement strategies: + +1. Start by assessing the client's current age, desired retirement age, and expected lifespan. +2. Calculate retirement savings goals based on desired lifestyle and projected expenses. +3. Analyze current retirement accounts (e.g., 401(k), IRA) and suggest optimization strategies. +4. Provide guidance on asset allocation and rebalancing as retirement approaches. +5. Explain various retirement income sources (e.g., Social Security, pensions, annuities). +6. Discuss healthcare costs and long-term care planning. +7. Offer strategies for tax-efficient withdrawals during retirement. +8. Consider estate planning and legacy goals in your recommendations. + +Use Monte Carlo simulations or other statistical tools to illustrate the probability of retirement success. Always emphasize the importance of starting early and the power of compound interest. Be prepared to adjust strategies based on changing market conditions or personal circumstances.""", ), ] agents_tree2 = [ TreeAgent( - system_prompt="Tax Filing Agent", + system_prompt="""You are a knowledgeable Tax Filing Agent, specializing in personal and business tax preparation and strategy. Your role is to ensure accurate tax filings while maximizing legitimate deductions and credits. When assisting with tax matters: + +1. Start by gathering all necessary financial information and documents. +2. Stay up-to-date with the latest tax laws and regulations, including state-specific rules. +3. Identify all applicable deductions and credits based on the client's situation. +4. Provide step-by-step guidance for completing tax forms accurately. +5. Explain tax implications of various financial decisions. +6. Offer strategies for tax-efficient investing and income management. +7. Assist with estimated tax payments for self-employed individuals or businesses. +8. Advise on record-keeping practices for tax purposes. + +Always prioritize compliance with tax laws while ethically minimizing tax liability. Be prepared to explain complex tax concepts in simple terms and provide rationale for your recommendations. If a situation is beyond your expertise, advise consulting a certified tax professional or IRS resources.""", agent_name="Tax Filing Agent", ), TreeAgent( - system_prompt="Investment Strategy Agent", + system_prompt="""You are a sophisticated Investment Strategy Agent, adept at creating and managing investment portfolios to meet diverse financial goals. Your expertise covers various asset classes, market analysis, and risk management techniques. When developing investment strategies: + +1. Begin by assessing the client's investment goals, time horizon, and risk tolerance. +2. Provide a comprehensive overview of different asset classes and their risk-return profiles. +3. Create diversified portfolio recommendations based on modern portfolio theory. +4. Explain the benefits and risks of various investment vehicles (e.g., stocks, bonds, ETFs, mutual funds). +5. Incorporate both passive and active investment strategies as appropriate. +6. Discuss the importance of regular portfolio rebalancing and provide a rebalancing strategy. +7. Consider tax implications of investment decisions and suggest tax-efficient strategies. +8. Provide ongoing market analysis and suggest portfolio adjustments as needed. + +Use historical data and forward-looking projections to illustrate potential outcomes. Always emphasize the importance of long-term investing and the risks of market timing. Be prepared to explain complex investment concepts in clear, accessible language.""", agent_name="Investment Strategy Agent", ), TreeAgent( - system_prompt="ROTH IRA Agent", agent_name="ROTH IRA Agent" + system_prompt="""You are a specialized ROTH IRA Agent, focusing on the intricacies of Roth Individual Retirement Accounts. Your role is to provide expert guidance on Roth IRA rules, benefits, and strategies to maximize their value for retirement planning. When advising on Roth IRAs: + +1. Explain the fundamental differences between traditional and Roth IRAs. +2. Clarify Roth IRA contribution limits and income eligibility requirements. +3. Discuss the tax advantages of Roth IRAs, including tax-free growth and withdrawals. +4. Provide guidance on Roth IRA conversion strategies and their tax implications. +5. Explain the five-year rule and how it affects Roth IRA withdrawals. +6. Offer strategies for maximizing Roth IRA contributions, such as the backdoor Roth IRA method. +7. Discuss how Roth IRAs fit into overall retirement and estate planning strategies. +8. Provide insights on investment choices within a Roth IRA to maximize tax-free growth. + +Always stay current with IRS regulations regarding Roth IRAs. Be prepared to provide numerical examples to illustrate the long-term benefits of Roth IRAs. Emphasize the importance of considering individual financial situations when making Roth IRA decisions.""", + agent_name="ROTH IRA Agent", ), ] @@ -1131,9 +1336,10 @@ tree2 = Tree(tree_name="Investment Tree", agents=agents_tree2) multi_agent_structure = ForestSwarm(trees=[tree1, tree2]) # Run a task -task = "Our company is incorporated in delaware, how do we do our taxes for free?" +task = "What are the best platforms to do our taxes on" output = multi_agent_structure.run(task) print(output) + ``` ---------- diff --git a/new_swarms_docs.md b/new_swarms_docs.md index a522c8f3b..91f9419ac 100644 --- a/new_swarms_docs.md +++ b/new_swarms_docs.md @@ -43,641 +43,3 @@ Swarm architectures are designed to establish and manage communication between a Swarm architectures leverage these communication patterns to ensure that agents work together efficiently, adapting to the specific requirements of the task at hand. By defining clear communication protocols and interaction models, swarm architectures enable the seamless orchestration of multiple agents, leading to enhanced performance and problem-solving capabilities. - -## Table of Contents -1. [Sequential Workflow](#sequential-workflow) -2. [Agent Rearrange](#agent-rearrange) -3. [Graph Swarm](#graph-swarm) -4. [Mixture of Agents](#mixture-of-agents) -5. [Spreadsheet Swarm](#spreadsheet-swarm) -6. [Forest Swarm](#forest-swarm) - -## Sequential Workflow - -The `SequentialWorkflow` allows you to execute tasks with agents in a sequential manner, passing the output of one agent to the next until a specified maximum number of loops is reached. - -### Diagram - -```mermaid -graph LR - A[Agent 1] --> B[Agent 2] - B --> C[Agent 3] - C --> D[Agent 4] - D --> E{Max Loops Reached?} - E -->|Yes| F[End] - E -->|No| A -``` - -### Example Usage - -```python -from swarms import Agent, SequentialWorkflow -from swarm_models import Anthropic - -# Initialize the language model -llm = Anthropic() - -# Initialize agents for individual tasks -agent1 = Agent( - agent_name="Blog generator", - system_prompt="Generate a blog post like Stephen King", - llm=llm, - max_loops=1, - dashboard=False, - tools=[], -) -agent2 = Agent( - agent_name="Summarizer", - system_prompt="Summarize the blog post", - llm=llm, - max_loops=1, - dashboard=False, - tools=[], -) - -# Create the Sequential workflow -workflow = SequentialWorkflow( - agents=[agent1, agent2], - max_loops=1, - verbose=False -) - -# Run the workflow -result = workflow.run( - "Generate a blog post on how swarms of agents can help businesses grow." -) -print(result) -``` - -### Methods - -| Method | Description | Parameters | Return Value | -|--------|-------------|------------|--------------| -| `__init__` | Initialize the SequentialWorkflow | `agents`: List of Agent objects
`max_loops`: Maximum number of iterations
`verbose`: Boolean for verbose output | None | -| `run` | Execute the workflow | `input_data`: Initial input for the first agent | Final output after all agents have processed | - -### Inputs - -| Input | Type | Description | -|-------|------|-------------| -| `agents` | List[Agent] | List of Agent objects to be executed sequentially | -| `max_loops` | int | Maximum number of times the entire sequence will be repeated | -| `verbose` | bool | If True, print detailed information during execution | - -### Output - -The `run` method returns the final output after all agents have processed the input sequentially. - -## Agent Rearrange - -The `AgentRearrange` orchestration technique allows you to define and map out relationships between various agents, enabling both linear and concurrent workflows. - -### Diagram - -```mermaid -graph TD - A[Director] --> B[Worker1] - A --> C[Worker2] - B --> D[Final Output] - C --> D -``` - -### Example Usage - -```python -from swarms import Agent, AgentRearrange -from swarm_models import Anthropic - -# Initialize the director agent -director = Agent( - agent_name="Director", - system_prompt="Directs the tasks for the workers", - llm=Anthropic(), - max_loops=1, - dashboard=False, - streaming_on=True, - verbose=True, - stopping_token="", - state_save_file_type="json", - saved_state_path="director.json", -) - -# Initialize worker 1 -worker1 = Agent( - agent_name="Worker1", - system_prompt="Generates a transcript for a YouTube video on what swarms are", - llm=Anthropic(), - max_loops=1, - dashboard=False, - streaming_on=True, - verbose=True, - stopping_token="", - state_save_file_type="json", - saved_state_path="worker1.json", -) - -# Initialize worker 2 -worker2 = Agent( - agent_name="Worker2", - system_prompt="Summarizes the transcript generated by Worker1", - llm=Anthropic(), - max_loops=1, - dashboard=False, - streaming_on=True, - verbose=True, - stopping_token="", - state_save_file_type="json", - saved_state_path="worker2.json", -) - -# Create a list of agents -agents = [director, worker1, worker2] - -# Define the flow pattern -flow = "Director -> Worker1 -> Worker2" - -# Using AgentRearrange class -agent_system = AgentRearrange(agents=agents, flow=flow) -output = agent_system.run( - "Create a format to express and communicate swarms of LLMs in a structured manner for YouTube" -) -print(output) -``` - -### Methods - -| Method | Description | Parameters | Return Value | -|--------|-------------|------------|--------------| -| `__init__` | Initialize the AgentRearrange | `agents`: List of Agent objects
`flow`: String describing the agent flow | None | -| `run` | Execute the workflow | `input_data`: Initial input for the first agent | Final output after all agents have processed | - -### Inputs - -| Input | Type | Description | -|-------|------|-------------| -| `agents` | List[Agent] | List of Agent objects to be orchestrated | -| `flow` | str | String describing the flow of agents (e.g., "A -> B, C") | - -### Output - -The `run` method returns the final output after all agents have processed the input according to the specified flow. - -## Graph Swarm - -The `GraphSwarm` is a workflow management system that uses a directed acyclic graph (DAG) to model dependencies between tasks and agents, allowing for efficient task assignment and execution. - -### Diagram - -```mermaid -graph TD - A[Agent 1] --> C[Task 1] - B[Agent 2] --> C - C --> D[End] -``` - -### Example Usage - -```python -import os -from dotenv import load_dotenv -from swarms import Agent, Edge, GraphWorkflow, Node, NodeType -from swarm_models import OpenAIChat - -load_dotenv() - -api_key = os.environ.get("OPENAI_API_KEY") - -llm = OpenAIChat( - temperature=0.5, openai_api_key=api_key, max_tokens=4000 -) -agent1 = Agent(llm=llm, max_loops=1, autosave=True, dashboard=True) -agent2 = Agent(llm=llm, max_loops=1, autosave=True, dashboard=True) - -def sample_task(): - print("Running sample task") - return "Task completed" - -wf_graph = GraphWorkflow() -wf_graph.add_node(Node(id="agent1", type=NodeType.AGENT, agent=agent1)) -wf_graph.add_node(Node(id="agent2", type=NodeType.AGENT, agent=agent2)) -wf_graph.add_node( - Node(id="task1", type=NodeType.TASK, callable=sample_task) -) -wf_graph.add_edge(Edge(source="agent1", target="task1")) -wf_graph.add_edge(Edge(source="agent2", target="task1")) - -wf_graph.set_entry_points(["agent1", "agent2"]) -wf_graph.set_end_points(["task1"]) - -print(wf_graph.visualize()) - -# Run the workflow -results = wf_graph.run() -print("Execution results:", results) -``` - -### Methods - -| Method | Description | Parameters | Return Value | -|--------|-------------|------------|--------------| -| `add_node` | Add a node to the graph | `node`: Node object | None | -| `add_edge` | Add an edge to the graph | `edge`: Edge object | None | -| `set_entry_points` | Set the entry points of the graph | `entry_points`: List of node IDs | None | -| `set_end_points` | Set the end points of the graph | `end_points`: List of node IDs | None | -| `visualize` | Generate a visual representation of the graph | None | String representation of the graph | -| `run` | Execute the workflow | None | Dictionary of execution results | - -### Inputs - -| Input | Type | Description | -|-------|------|-------------| -| `Node` | Object | Represents a node in the graph (agent or task) | -| `Edge` | Object | Represents an edge connecting two nodes | -| `entry_points` | List[str] | List of node IDs where the workflow starts | -| `end_points` | List[str] | List of node IDs where the workflow ends | - -### Output - -The `run` method returns a dictionary containing the execution results of all nodes in the graph. - -## Mixture of Agents - -The `MixtureOfAgents` is an implementation based on the paper "Mixture-of-Agents Enhances Large Language Model Capabilities". It allows for parallelization followed by sequential processing in another loop. - -### Diagram - -```mermaid -graph TD - A[Director] --> B[Accountant 1] - A --> C[Accountant 2] - B --> D[Final Agent] - C --> D - D --> E[Output] -``` - -### Example Usage - -```python -from swarms import Agent, OpenAIChat, MixtureOfAgents - -# Initialize the director agent -director = Agent( - agent_name="Director", - system_prompt="Directs the tasks for the accountants", - llm=OpenAIChat(), - max_loops=1, - dashboard=False, - streaming_on=True, - verbose=True, - stopping_token="", - state_save_file_type="json", - saved_state_path="director.json", -) - -# Initialize accountant 1 -accountant1 = Agent( - agent_name="Accountant1", - system_prompt="Prepares financial statements", - llm=OpenAIChat(), - max_loops=1, - dashboard=False, - streaming_on=True, - verbose=True, - stopping_token="", - state_save_file_type="json", - saved_state_path="accountant1.json", -) - -# Initialize accountant 2 -accountant2 = Agent( - agent_name="Accountant2", - system_prompt="Audits financial records", - llm=OpenAIChat(), - max_loops=1, - dashboard=False, - streaming_on=True, - verbose=True, - stopping_token="", - state_save_file_type="json", - saved_state_path="accountant2.json", -) - -# Create a list of agents -agents = [director, accountant1, accountant2] - -# Swarm -swarm = MixtureOfAgents( - name="Mixture of Accountants", - agents=agents, - layers=3, - final_agent=director, -) - -# Run the swarm -out = swarm.run("Prepare financial statements and audit financial records") -print(out) -``` - -### Methods - -| Method | Description | Parameters | Return Value | -|--------|-------------|------------|--------------| -| `__init__` | Initialize the MixtureOfAgents | `name`: Name of the swarm
`agents`: List of Agent objects
`layers`: Number of processing layers
`final_agent`: Agent for final processing | None | -| `run` | Execute the swarm | `task`: Input task for the swarm | Final output after all agents have processed | - -### Inputs - -| Input | Type | Description | -|-------|------|-------------| -| `name` | str | Name of the swarm | -| `agents` | List[Agent] | List of Agent objects to be used in the swarm | -| `layers` | int | Number of processing layers in the swarm | -| `final_agent` | Agent | Agent responsible for final processing | - -### Output - -The `run` method returns the final output after all agents have processed the input according to the specified layers and final agent. - -## Spreadsheet Swarm - -The `SpreadSheetSwarm` is designed for concurrent management and oversight of thousands of agents, facilitating a one-to-many approach for efficient task processing and output analysis. - -### Diagram - -```mermaid -graph LR - A[Task] -->|Distributed| B[Agent 1] - A -->|Distributed| C[Agent 2] - A -->|Distributed| D[Agent 3] - B -->|Output| E[SpreadSheetSwarm] - C -->|Output| E - D -->|Output| E - E -->|Aggregated Output| F[User] -``` - -### Example Usage - -```python -import os -from swarms import Agent -from swarm_models import OpenAIChat -from swarms.structs.spreadsheet_swarm import SpreadSheetSwarm - -# Define custom system prompts for each social media platform -TWITTER_AGENT_SYS_PROMPT = """ -You are a Twitter marketing expert specializing in real estate. Your task is to create engaging, concise tweets to promote properties, analyze trends to maximize engagement, and use appropriate hashtags and timing to reach potential buyers. -""" - -INSTAGRAM_AGENT_SYS_PROMPT = """ -You are an Instagram marketing expert focusing on real estate. Your task is to create visually appealing posts with engaging captions and hashtags to showcase properties, targeting specific demographics interested in real estate. -""" - -FACEBOOK_AGENT_SYS_PROMPT = """ -You are a Facebook marketing expert for real estate. Your task is to craft posts optimized for engagement and reach on Facebook, including using images, links, and targeted messaging to attract potential property buyers. -""" - -LINKEDIN_AGENT_SYS_PROMPT = """ -You are a LinkedIn marketing expert for the real estate industry. Your task is to create professional and informative posts, highlighting property features, market trends, and investment opportunities, tailored to professionals and investors. -""" - -EMAIL_AGENT_SYS_PROMPT = """ -You are an Email marketing expert specializing in real estate. Your task is to write compelling email campaigns to promote properties, focusing on personalization, subject lines, and effective call-to-action strategies to drive conversions. -""" - -api_key = os.getenv("OPENAI_API_KEY") - -# Model -model = OpenAIChat( - openai_api_key=api_key, model_name="gpt-4-0314", temperature=0.1 -) - -# Initialize your agents for different social media platforms -agents = [ - Agent( - agent_name="Twitter-RealEstate-Agent", - system_prompt=TWITTER_AGENT_SYS_PROMPT, - llm=model, - max_loops=1, - dynamic_temperature_enabled=True, - saved_state_path="twitter_realestate_agent.json", - user_name="realestate_swarms", - retry_attempts=1, - ), - Agent( - agent_name="Instagram-RealEstate-Agent", - system_prompt=INSTAGRAM_AGENT_SYS_PROMPT, - llm=model, - max_loops=1, - dynamic_temperature_enabled=True, - saved_state_path="instagram_realestate_agent.json", - user_name="realestate_swarms", - retry_attempts=1, - ), - Agent( - agent_name="Facebook-RealEstate-Agent", - system_prompt=FACEBOOK_AGENT_SYS_PROMPT, - llm=model, - max_loops=1, - dynamic_temperature_enabled=True, - saved_state_path="facebook_realestate_agent.json", - user_name="realestate_swarms", - retry_attempts=1, - ), - Agent( - agent_name="LinkedIn-RealEstate-Agent", - system_prompt=system_prompt=LINKEDIN_AGENT_SYS_PROMPT, - llm=model, - max_loops=1, - dynamic_temperature_enabled=True, - saved_state_path="linkedin_realestate_agent.json", - user_name="realestate_swarms", - retry_attempts=1, - ), - Agent( - agent_name="Email-RealEstate-Agent", - system_prompt=EMAIL_AGENT_SYS_PROMPT, - llm=model, - max_loops=1, - dynamic_temperature_enabled=True, - saved_state_path="email_realestate_agent.json", - user_name="realestate_swarms", - retry_attempts=1, - ), -] - -# Create a Swarm with the list of agents -swarm = SpreadSheetSwarm( - name="Real-Estate-Marketing-Swarm", - description="A swarm that processes real estate marketing tasks using multiple agents on different threads.", - agents=agents, - autosave_on=True, - save_file_path="real_estate_marketing_spreadsheet.csv", - run_all_agents=False, - max_loops=2, -) - -# Run the swarm -swarm.run( - task=""" - Create posts to promote luxury properties in North Texas, highlighting their features, location, and investment potential. Include relevant hashtags, images, and engaging captions. - - Property: - $10,399,000 - 1609 Meandering Way Dr, Roanoke, TX 76262 - Link to the property: https://www.zillow.com/homedetails/1609-Meandering-Way-Dr-Roanoke-TX-76262/308879785_zpid/ - - What's special: - Unveiling a new custom estate in the prestigious gated Quail Hollow Estates! This impeccable residence, set on a sprawling acre surrounded by majestic trees, features a gourmet kitchen equipped with top-tier Subzero and Wolf appliances. European soft-close cabinets and drawers, paired with a double Cambria Quartzite island, perfect for family gatherings. The first-floor game room & media room add extra layers of entertainment. Step into the outdoor sanctuary, where a sparkling pool and spa, and sunken fire pit, beckon leisure. The lavish master suite features stunning marble accents, custom his & her closets, and a secure storm shelter. Throughout the home, indulge in the visual charm of designer lighting and wallpaper, elevating every space. The property is complete with a 6-car garage and a sports court, catering to the preferences of basketball or pickleball enthusiasts. This residence seamlessly combines luxury & recreational amenities, making it a must-see for the discerning buyer. - - Facts & features: - Interior - Bedrooms & bathrooms: - Bedrooms: 6 - Bathrooms: 8 - Full bathrooms: 7 - 1/2 bathrooms: 1 - Primary bedroom features: Built-in Features, En Suite Bathroom, Walk-In Closet(s) - Cooling: Central Air, Ceiling Fan(s), Electric - Appliances included: Built-In Gas Range, Built-In Refrigerator, Double Oven, Dishwasher, Gas Cooktop, Disposal, Ice Maker, Microwave, Range, Refrigerator, Some Commercial Grade, Vented Exhaust Fan, Warming Drawer, Wine Cooler - Features: Wet Bar, Built-in Features, Dry Bar, Decorative/Designer Lighting Fixtures, Eat-in Kitchen, Elevator, High Speed Internet, Kitchen Island, Pantry, Smart Home, Cable TV, Walk-In Closet(s), Wired for Sound - Flooring: Hardwood - Has basement: No - Number of fireplaces: 3 - Fireplace features: Living Room, Primary Bedroom - Interior area: Total interior livable area: 10,466 sqft - Total spaces: 12 - Parking features: Additional Parking - Attached garage spaces: 6 - Carport spaces: 6 - Levels: Two - Stories: 2 - Patio & porch: Covered - Exterior features: Built-in Barbecue, Barbecue, Gas Grill, Lighting, Outdoor Grill, Outdoor Living Area, Private Yard, Sport Court, Fire Pit - Pool features: Heated, In Ground, Pool, Pool/Spa Combo - Fencing: Wrought Iron - Lot size: 1.05 Acres - Additional structures: Outdoor Kitchen - Parcel number: 42232692 - Special conditions: Standard - Construction type & style: SingleFamily - Architectural style: Contemporary/Modern, Detached - Property subtype: Single Family Residence - """ -) -``` - -### Methods - -| Method | Description | Parameters | Return Value | -|--------|-------------|------------|--------------| -| `__init__` | Initialize the SpreadSheetSwarm | `name`: Name of the swarm
`description`: Description of the swarm
`agents`: List of Agent objects
`autosave_on`: Boolean to enable autosave
`save_file_path`: Path to save the spreadsheet
`run_all_agents`: Boolean to run all agents or not
`max_loops`: Maximum number of loops | None | -| `run` | Execute the swarm | `task`: Input task for the swarm | Dictionary of agent outputs | - -### Inputs - -| Input | Type | Description | -|-------|------|-------------| -| `name` | str | Name of the swarm | -| `description` | str | Description of the swarm's purpose | -| `agents` | List[Agent] | List of Agent objects to be used in the swarm | -| `autosave_on` | bool | Enable autosaving of results | -| `save_file_path` | str | Path to save the spreadsheet results | -| `run_all_agents` | bool | Whether to run all agents or select based on relevance | -| `max_loops` | int | Maximum number of processing loops | - -### Output - -The `run` method returns a dictionary containing the outputs of each agent that processed the task. - -## Forest Swarm - -The `ForestSwarm` architecture is designed for efficient task assignment by dynamically selecting the most suitable agent from a collection of trees. This is achieved through asynchronous task processing, where agents are chosen based on their relevance to the task at hand. - -### Diagram - -```mermaid -graph TD - A[Task] --> B[Forest Swarm] - B --> C[Tree 1] - B --> D[Tree 2] - C --> E[Agent 1.1] - C --> F[Agent 1.2] - C --> G[Agent 1.3] - D --> H[Agent 2.1] - D --> I[Agent 2.2] - D --> J[Agent 2.3] - E --> K[Output] - F --> K - G --> K - H --> K - I --> K - J --> K -``` - -### Example Usage - -```python -from swarms.structs.tree_swarm import TreeAgent, Tree, ForestSwarm - -# Create agents with varying system prompts and dynamically generated distances/keywords -agents_tree1 = [ - TreeAgent( - system_prompt="Stock Analysis Agent", - agent_name="Stock Analysis Agent", - ), - TreeAgent( - system_prompt="Financial Planning Agent", - agent_name="Financial Planning Agent", - ), - TreeAgent( - agent_name="Retirement Strategy Agent", - system_prompt="Retirement Strategy Agent", - ), -] - -agents_tree2 = [ - TreeAgent( - system_prompt="Tax Filing Agent", - agent_name="Tax Filing Agent", - ), - TreeAgent( - system_prompt="Investment Strategy Agent", - agent_name="Investment Strategy Agent", - ), - TreeAgent( - system_prompt="ROTH IRA Agent", agent_name="ROTH IRA Agent" - ), -] - -# Create trees -tree1 = Tree(tree_name="Financial Tree", agents=agents_tree1) -tree2 = Tree(tree_name="Investment Tree", agents=agents_tree2) - -# Create the ForestSwarm -multi_agent_structure = ForestSwarm(trees=[tree1, tree2]) - -# Run a task -task = "Our company is incorporated in Delaware, how do we do our taxes for free?" -output = multi_agent_structure.run(task) -print(output) -``` - -### Methods - -| Method | Description | Parameters | Return Value | -|--------|-------------|------------|--------------| -| `__init__` | Initialize the ForestSwarm | `trees`: List of Tree objects | None | -| `run` | Execute the ForestSwarm | `task`: Input task for the swarm | Output from the most relevant agent | - -### Inputs - -| Input | Type | Description | -|-------|------|-------------| -| `trees` | List[Tree] | List of Tree objects, each containing TreeAgent objects | -| `task` | str | The task to be processed by the ForestSwarm | - -### Output - -The `run` method returns the output from the most relevant agent selected based on the input task. - -This concludes the comprehensive documentation for the various swarm architectures in the Swarms library. Each architecture offers unique capabilities for orchestrating multiple agents to perform complex tasks efficiently. \ No newline at end of file