diff --git a/.gitignore b/.gitignore index 780d95ae..e775b0cc 100644 --- a/.gitignore +++ b/.gitignore @@ -17,6 +17,7 @@ Unit Testing Agent_state.json Devin_state.json json_logs Medical Image Diagnostic Agent_state.json +flight agent_state.json D_state.json artifacts_six artifacts_seven diff --git a/docs/swarms/structs/nonlinearworkflow.md b/docs/swarms/structs/nonlinearworkflow.md deleted file mode 100644 index 09d00074..00000000 --- a/docs/swarms/structs/nonlinearworkflow.md +++ /dev/null @@ -1,96 +0,0 @@ - -#### Class Name: NonlinearWorkflow - -This class represents a Directed Acyclic Graph (DAG) workflow used to store tasks and their dependencies in a workflow. The structures can validate, execute and store the order of tasks present in the workflow. It has the following attributes and methods: - -#### Attributes: -- `tasks` (dict): A dictionary mapping task names to Task objects. -- `edges` (dict): A dictionary mapping task names to a list of dependencies. -- `stopping_token` (str): The token which denotes the end condition for the workflow execution. Default: `` - -#### Methods: - -1. `__init__(self, stopping_token: str = "")`: The initialization method that sets up the NonlinearWorkflow object with an optional stopping token. This token marks the end of the workflow. - - **Args**: - - `stopping_token` (str): The token to denote the end condition for the workflow execution. - -2. `add(task: Task, *dependencies: str)`: Adds a task to the workflow along with its dependencies. This method is used to add a new task to the workflow with an optional list of dependency tasks. - - **Args**: - - `task` (Task): The task to be added. - - `dependencies` (varargs): Variable number of dependency task names. - - **Returns**: None - -3. `run()`: This method runs the workflow by executing tasks in topological order. It runs the tasks according to the sequence of dependencies. - - **Raises**: - - `Exception`: If a circular dependency is detected. - - **Returns**: None - -#### Examples: - -Usage Example 1: - -```python -from swarms.models import OpenAIChat -from swarms.structs import NonlinearWorkflow, Task - -# Initialize the OpenAIChat model -llm = OpenAIChat(openai_api_key="") -# Create a new Task -task = Task(llm, "What's the weather in Miami") -# Initialize the NonlinearWorkflow -workflow = NonlinearWorkflow() -# Add task to the workflow -workflow.add(task) -# Execute the workflow -workflow.run() -``` - -Usage Example 2: - -```python -from swarms.models import OpenAIChat -from swarms.structs import NonlinearWorkflow, Task - -# Initialize the OpenAIChat model -llm = OpenAIChat(openai_api_key="") -# Create new Tasks -task1 = Task(llm, "What's the weather in Miami") -task2 = Task(llm, "Book a flight to New York") -task3 = Task(llm, "Find a hotel in Paris") -# Initialize the NonlinearWorkflow -workflow = NonlinearWorkflow() -# Add tasks to the workflow with dependencies -workflow.add(task1, task2.name) -workflow.add(task2, task3.name) -workflow.add(task3, "OpenAIChat Initialization") -# Execute the workflow -workflow.run() -``` - -Usage Example 3: - -```python -from swarms.models import OpenAIChat -from swarms.structs import NonlinearWorkflow, Task - -# Initialize the OpenAIChat model -llm = OpenAIChat(openai_api_key="") -# Create new Tasks -task1 = Task(llm, "What's the weather in Miami") -task2 = Task(llm, "Book a flight to New York") -task3 = Task(llm, "Find a hotel in Paris") -# Initialize the NonlinearWorkflow -workflow = NonlinearWorkflow() -# Add tasks to the workflow with dependencies -workflow.add(task1) -workflow.add(task2, task1.name) -workflow.add(task3, task1.name, task2.name) -# Execute the workflow -workflow.run() -``` - -These examples illustrate the three main types of usage for the NonlinearWorkflow class and how it can be used to represent a directed acyclic graph (DAG) workflow with tasks and their dependencies. - ---- - -The explanatory documentation details the architectural aspects, methods, attributes, examples, and usage patterns for the `NonlinearWorkflow` class. By following the module and function definition structure, the documentation provides clear and comprehensive descriptions of the class and its functionalities. diff --git a/docs/swarms/structs/recursiveworkflow.md b/docs/swarms/structs/recursiveworkflow.md deleted file mode 100644 index 40c31478..00000000 --- a/docs/swarms/structs/recursiveworkflow.md +++ /dev/null @@ -1,23 +0,0 @@ -**Module/Function Name: RecursiveWorkflow** - -`class` RecursiveWorkflow(BaseStructure): - -Creates a recursive workflow structure for executing a task until a stated stopping condition is reached. - -#### Parameters -* *task* (`Task`): The task to execute. -* *stop_token* (`Any`): The token that signals the termination of the workflow. - -#### Examples: -```python -from swarms.models import OpenAIChat -from swarms.structs import RecursiveWorkflow, Task - -llm = OpenAIChat(openai_api_key="YourKey") -task = Task(llm, "What's the weather in miami") -workflow = RecursiveWorkflow(stop_token="") -workflow.add(task) -workflow.run() -``` - -In summary, the `RecursiveWorkflow` class is designed to automate tasks by adding and executing these tasks recursively until a stopping condition is reached. This can be achieved by utilizing the `add` and `run` methods provided. A general format for adding and utilizing the `RecursiveWorkflow` class has been provided under the "Examples" section. If you require any further information, view other sections, like Args and Source Code for specifics on using the class effectively. diff --git a/docs/swarms/structs/round_robin_swarm.md b/docs/swarms/structs/round_robin_swarm.md index 6dbe0ae3..d788eb85 100644 --- a/docs/swarms/structs/round_robin_swarm.md +++ b/docs/swarms/structs/round_robin_swarm.md @@ -50,77 +50,65 @@ Executes a specified task across all agents in a round-robin manner, cycling thr In this example, `RoundRobinSwarm` is used to distribute network requests evenly among a group of servers. This is common in scenarios where load balancing is crucial for maintaining system responsiveness and scalability. ```python -from swarms.structs.round_robin import RoundRobinSwarm -from swarms import Agent - -# Define server agents -server1 = Agent(agent_name="Server1", system_prompt="Handle network requests") -server2 = Agent(agent_name="Server2", system_prompt="Handle network requests") -server3 = Agent(agent_name="Server3", system_prompt="Handle network requests") - -# Initialize the swarm with server agents -network_load_balancer = RoundRobinSwarm(agents=[server1, server2, server3], verbose=True) - -# Define a network request task -task = "Process incoming network request" - -# Simulate processing of multiple requests -for _ in range(10): # Assume 10 incoming requests - results = network_load_balancer.run(task) - print("Request processed:", results) -``` - -### Example 2: Document Review Process - -This example demonstrates how `RoundRobinSwarm` can be used to distribute parts of a document among different reviewers in a sequential manner, ensuring that each part of the document is reviewed by different agents. - -```python -from swarms.structs.round_robin import RoundRobinSwarm -from swarms import Agent - -# Define reviewer agents -reviewer1 = Agent(agent_name="Reviewer1", system_prompt="Review document section") -reviewer2 = Agent(agent_name="Reviewer2", system_prompt="Review document section") -reviewer3 = Agent(agent_name="Reviewer3", system_prompt="Review document section") - -# Initialize the swarm with reviewer agents -document_review_swarm = RoundRobinSwarm(agents=[reviewer1, reviewer2, reviewer3], verbose=True) - -# Define a document review task -task = "Review section of the document" - -# Distribute sections of the document to different reviewers -for section in range(5): # Assume the document has 5 sections - results = document_review_swarm.run(task) - print(f"Section {section + 1} reviewed:", results) +from swarms import Agent, OpenAIChat, RoundRobinSwarm + + +# Initialize the LLM +llm = OpenAIChat() + +# Define sales agents +sales_agent1 = Agent( + agent_name="Sales Agent 1 - Automation Specialist", + system_prompt="You're Sales Agent 1, your purpose is to generate sales for a company by focusing on the benefits of automating accounting processes!", + agent_description="Generate sales by focusing on the benefits of automation!", + llm=llm, + max_loops=1, + autosave=True, + dashboard=False, + verbose=True, + streaming_on=True, + context_length=1000, +) + +sales_agent2 = Agent( + agent_name="Sales Agent 2 - Cost Saving Specialist", + system_prompt="You're Sales Agent 2, your purpose is to generate sales for a company by emphasizing the cost savings of using swarms of agents!", + agent_description="Generate sales by emphasizing cost savings!", + llm=llm, + max_loops=1, + autosave=True, + dashboard=False, + verbose=True, + streaming_on=True, + context_length=1000, +) + +sales_agent3 = Agent( + agent_name="Sales Agent 3 - Efficiency Specialist", + system_prompt="You're Sales Agent 3, your purpose is to generate sales for a company by highlighting the efficiency and accuracy of our swarms of agents in accounting processes!", + agent_description="Generate sales by highlighting efficiency and accuracy!", + llm=llm, + max_loops=1, + autosave=True, + dashboard=False, + verbose=True, + streaming_on=True, + context_length=1000, +) + +# Initialize the swarm with sales agents +sales_swarm = RoundRobinSwarm(agents=[sales_agent1, sales_agent2, sales_agent3], verbose=True) + +# Define a sales task +task = "Generate a sales email for an accountant firm executive to sell swarms of agents to automate their accounting processes." + +# Distribute sales tasks to different agents +for _ in range(5): # Repeat the task 5 times + results = sales_swarm.run(task) + print("Sales generated:", results) ``` -### Example 3: Multi-Stage Data Processing - -In this scenario, `RoundRobinSwarm` facilitates a multi-stage data processing pipeline where data passes through multiple agents, each performing a specific type of data processing in sequence. - -```python -from swarms.structs.round_robin import RoundRobinSwarm -from swarms import Agent - -# Define data processing agents -preprocessor = Agent(agent_name="Preprocessor", system_prompt="Preprocess data") -analyzer = Agent(agent_name="Analyzer", system_prompt="Analyze data") -summarizer = Agent(agent_name="Summarizer", system_prompt="Summarize analysis results") -# Initialize the swarm with data processing agents -data_processing_swarm = RoundRobinSwarm(agents=[preprocessor, analyzer, summarizer], verbose=True) - -# Define a data processing task -task = "Initial raw data" - -# Run the data through the processing pipeline -results = data_processing_swarm.run(task) -print("Final results from data processing:", results) -``` - -These examples provide a glimpse into how the `RoundRobinSwarm` class can be adapted to various domains and applications, showcasing its versatility in managing tasks and resources in a distributed environment. -``` ## Conclusion diff --git a/docs/swarms/structs/taskqueuebase.md b/docs/swarms/structs/taskqueuebase.md deleted file mode 100644 index 0feee648..00000000 --- a/docs/swarms/structs/taskqueuebase.md +++ /dev/null @@ -1,130 +0,0 @@ - -# `TaskQueueBase` - -## Introduction -The `swarms.structs` library is a key component of a multi-agent system's task management infrastructure. It provides the necessary classes and methods to create and manage queues of tasks that can be distributed among a swarm of agents. The purpose of this documentation is to guide users through the proper use of the `TaskQueueBase` class, which serves as an abstract base class for implementing task queues. - -## TaskQueueBase Class - -```python -import threading -from abc import ABC, abstractmethod - -# Include any additional imports that are relevant to decorators and other classes such as Task and Agent if needed - -# Definition of the synchronized_queue decorator (if necessary) - - -class TaskQueueBase(ABC): - def __init__(self): - self.lock = threading.Lock() - - @synchronized_queue - @abstractmethod - def add_task(self, task: Task) -> bool: - pass - - @synchronized_queue - @abstractmethod - def get_task(self, agent: Agent) -> Task: - pass - - @synchronized_queue - @abstractmethod - def complete_task(self, task_id: str): - pass - - @synchronized_queue - @abstractmethod - def reset_task(self, task_id: str): - pass -``` - -### Architecture and Purpose -The `TaskQueueBase` class provides an abstract interface for task queue implementations. This class uses the `threading.Lock` to ensure mutual exclusion, making it suitable for concurrent environments. The `@synchronized_queue` decorator implies that each method should be synchronized to prevent race conditions. - -Tasks are generally represented by the `Task` class, and agents by the `Agent` class. Implementations of the `TaskQueueBase` will provide the logic to store tasks, distribute them to agents, and manage their lifecycles. - -#### Methods and Their Arguments - -Here's an overview of each method and its arguments: - -| Method | Arguments | Return Type | Description | -|----------------|----------------|-------------|-----------------------------------------------------------------------------------------------| -| add_task | task (Task) | bool | Adds a task to the queue and returns True if successfully added, False otherwise. | -| get_task | agent (Agent) | Task | Retrieves the next task for the given agent. | -| complete_task | task_id (str) | None | Marks the task identified by task_id as completed. | -| reset_task | task_id (str) | None | Resets the task identified by task_id, typically done if an agent fails to complete the task. | - -### Example Usage - -Below are three examples of how the `TaskQueueBase` class can be implemented and used. - -**Note:** The actual code for decorators, Task, Agent, and concrete implementations of `TaskQueueBase` is not provided and should be created as per specific requirements. - -#### Example 1: Basic Implementation - -```python -# file: basic_queue.py - -# Assume synchronized_queue decorator is defined elsewhere -from decorators import synchronized_queue - -from swarms.structs import Agent, Task, TaskQueueBase - - -class BasicTaskQueue(TaskQueueBase): - def __init__(self): - super().__init__() - self.tasks = [] - - @synchronized_queue - def add_task(self, task: Task) -> bool: - self.tasks.append(task) - return True - - @synchronized_queue - def get_task(self, agent: Agent) -> Task: - return self.tasks.pop(0) - - @synchronized_queue - def complete_task(self, task_id: str): - # Logic to mark task as completed - pass - - @synchronized_queue - def reset_task(self, task_id: str): - # Logic to reset the task - pass - - -# Usage -queue = BasicTaskQueue() -# Add task, assuming Task object is created -queue.add_task(someTask) -# Get task for an agent, assuming Agent object is created -task = queue.get_task(someAgent) -``` - -#### Example 2: Priority Queue Implementation - -```python -# file: priority_queue.py -# Similar to example 1, but tasks are managed based on priority within add_task and get_task methods -``` - -#### Example 3: Persistent Queue Implementation - -```python -# file: persistent_queue.py -# An example demonstrating tasks being saved to a database or filesystem. Methods would include logic for persistence. -``` - -### Additional Information and Common Issues - -This section would provide insights on thread safety, error handling, and best practices in working with task queues in a multi-agent system. - -### References - -Links to further resources and any academic papers or external documentation related to task queues and multi-agent systems would be included here. - diff --git a/bad_tomato.jpg b/playground/demos/plant_biologist_swarm/bad_tomato.jpg similarity index 100% rename from bad_tomato.jpg rename to playground/demos/plant_biologist_swarm/bad_tomato.jpg diff --git a/playground/structs/multi_agent_collaboration/round_robin_swarm_example.py b/playground/structs/multi_agent_collaboration/round_robin_swarm_example.py new file mode 100644 index 00000000..f3a463ad --- /dev/null +++ b/playground/structs/multi_agent_collaboration/round_robin_swarm_example.py @@ -0,0 +1,59 @@ +from swarms.structs.round_robin import RoundRobinSwarm +from swarms import Agent, OpenAIChat + + +# Initialize the LLM +llm = OpenAIChat() + +# Define sales agents +sales_agent1 = Agent( + agent_name="Sales Agent 1 - Automation Specialist", + system_prompt="You're Sales Agent 1, your purpose is to generate sales for a company by focusing on the benefits of automating accounting processes!", + agent_description="Generate sales by focusing on the benefits of automation!", + llm=llm, + max_loops=1, + autosave=True, + dashboard=False, + verbose=True, + streaming_on=True, + context_length=1000, +) + +sales_agent2 = Agent( + agent_name="Sales Agent 2 - Cost Saving Specialist", + system_prompt="You're Sales Agent 2, your purpose is to generate sales for a company by emphasizing the cost savings of using swarms of agents!", + agent_description="Generate sales by emphasizing cost savings!", + llm=llm, + max_loops=1, + autosave=True, + dashboard=False, + verbose=True, + streaming_on=True, + context_length=1000, +) + +sales_agent3 = Agent( + agent_name="Sales Agent 3 - Efficiency Specialist", + system_prompt="You're Sales Agent 3, your purpose is to generate sales for a company by highlighting the efficiency and accuracy of our swarms of agents in accounting processes!", + agent_description="Generate sales by highlighting efficiency and accuracy!", + llm=llm, + max_loops=1, + autosave=True, + dashboard=False, + verbose=True, + streaming_on=True, + context_length=1000, +) + +# Initialize the swarm with sales agents +sales_swarm = RoundRobinSwarm( + agents=[sales_agent1, sales_agent2, sales_agent3], verbose=True +) + +# Define a sales task +task = "Generate a sales email for an accountant firm executive to sell swarms of agents to automate their accounting processes." + +# Distribute sales tasks to different agents +for _ in range(5): # Repeat the task 5 times + results = sales_swarm.run(task) + print("Sales generated:", results) diff --git a/playground/structs/swarm_network_example.py b/playground/structs/multi_agent_collaboration/swarm_network_example.py similarity index 100% rename from playground/structs/swarm_network_example.py rename to playground/structs/multi_agent_collaboration/swarm_network_example.py diff --git a/prompts/agent_creator_prompt.md b/prompts/agent_creator_prompt.md deleted file mode 100644 index 0f362e57..00000000 --- a/prompts/agent_creator_prompt.md +++ /dev/null @@ -1,421 +0,0 @@ -### System Prompt for an Agent Generator - -**System Name:** AgentGenerator - -**Objective:** To generate specialized agents tailored to specific business problems, including defining their roles, tools, communication protocols, and workflows. - -**Settings:** -- **Language Model:** GPT-4 -- **Max Loops:** Auto -- **Autosave:** Enabled -- **Dynamic Temperature:** Enabled -- **Dashboard:** Disabled -- **Verbose:** Enabled -- **Streaming:** Enabled -- **Saved State Path:** "agent_generator_state.json" -- **Context Length:** 8192 - -**Core Functions:** -1. **Define Agent Specifications:** - - **agent_name**: The unique name of the agent. - - **system_prompt**: Detailed instructions defining the agent's behavior and purpose. - - **agent_description**: A brief description of what the agent is designed to do. - - **llm**: The language model used by the agent. - - **tools**: A list of tools the agent will use to perform its tasks. - - **max_loops**: The maximum number of iterations the agent can perform. - - **autosave**: A flag to enable or disable autosaving of the agent's state. - - **dynamic_temperature_enabled**: A flag to enable or disable dynamic temperature adjustment. - - **dashboard**: A flag to enable or disable the agent's dashboard. - - **verbose**: A flag to enable or disable verbose logging. - - **streaming_on**: A flag to enable or disable streaming output. - - **saved_state_path**: The file path to save the agent's state. - - **context_length**: The maximum length of the agent's context. - -2. **Define Tools and Resources:** - - **Terminal Tool**: Execute terminal commands. - - **Browser Tool**: Perform web searches and browser automation. - - **File Editor Tool**: Create and edit files. - - **Database Tool**: Interact with databases. - - **APIs and Webhooks**: Connect with external APIs and handle webhooks. - -3. **Communication Protocols:** - - **Type**: Define the communication type (e.g., synchronous, asynchronous). - - **Protocol**: Specify the messaging protocol (e.g., direct messaging, publish-subscribe). - - **Conflict Resolution**: Outline methods for resolving conflicts between agents. - -4. **Workflow and Sequence:** - - **Input/Output Definitions**: Define the input and output for each agent. - - **Task Triggers**: Specify conditions that trigger each task. - - **Task Handoff**: Detail the handoff process between agents. - - **Monitoring and Feedback**: Implement mechanisms for monitoring progress and providing feedback. - -5. **Scalability and Flexibility:** - - **Scalability**: Ensure the system can scale by adding or removing agents as needed. - - **Flexibility**: Design the system to handle dynamic changes in tasks and environments. - -6. **Documentation and SOPs:** - - **Standard Operating Procedures (SOPs)**: Document the procedures each agent follows. - - **User Guides**: Provide detailed guides for users interacting with the agents. - - **API Documentation**: Detail the APIs and webhooks used by the agents. - -## Usage Examples - -```python -from swarms import Agent, OpenAIChat, ChromaDB, Anthropic -import subprocess -from pydantic import BaseModel - -# Initialize ChromaDB client -chromadb = ChromaDB( - metric="cosine", - output="results", - docs_folder="docs", -) - -# Create a schema for file operations -class FileOperationSchema(BaseModel): - file_path: str - content: str - -file_operation_schema = FileOperationSchema( - file_path="plan.txt", - content="Plan to take over the world." -) - -# Define tools -def terminal(code: str): - result = subprocess.run(code, shell=True, capture_output=True, text=True).stdout - return result - -def browser(query: str): - import webbrowser - url = f"https://www.google.com/search?q={query}" - webbrowser.open(url) - return f"Searching for {query} in the browser." - -def create_file(file_path: str, content: str): - with open(file_path, "w") as file: - file.write(content) - return f"File {file_path} created successfully." - -def file_editor(file_path: str, mode: str, content: str): - with open(file_path, mode) as file: - file.write(content) - return f"File {file_path} edited successfully." - -# Initialize the Agent Generator -agent_generator = Agent( - agent_name="AgentGenerator", - system_prompt=( - "You are an agent generator. Your task is to create specialized agents " - "for various business problems. Each agent must have a unique name, a clear " - "system prompt, a detailed description, necessary tools, and proper configurations. " - "Ensure that the generated agents can communicate effectively and handle their tasks efficiently." - ), - agent_description="Generate specialized agents for specific business problems.", - llm=OpenAIChat(), - max_loops="auto", - autosave=True, - dynamic_temperature_enabled=True, - dashboard=False, - verbose=True, - streaming_on=True, - saved_state_path="agent_generator_state.json", - context_length=8192, - tools=[terminal, browser, create_file, file_editor], - long_term_memory=chromadb, - output_type=file_operation_schema, - metadata_output_type="json", -) - -# Generate a specialized agent -def create_tiktok_agent(): - tiktok_agent = Agent( - agent_name="TikTok Editor", - system_prompt="Generate short and catchy TikTok captions.", - agent_description="Create engaging captions for TikTok videos.", - llm=OpenAIChat(), - max_loops=1, - autosave=True, - dynamic_temperature_enabled=True, - dashboard=False, - verbose=True, - streaming_on=True, - saved_state_path="tiktok_agent.json", - context_length=8192, - ) - return tiktok_agent - -# Example usage of the Agent Generator -new_agent = create_tiktok_agent() -print(new_agent.agent_description) -``` - -**Execution:** -- Use the `AgentGenerator` to create new agents by defining their specifications and initializing them with the necessary tools and configurations. -- Ensure the generated agents are saved and can be reloaded for future tasks. -- Monitor and update the agents as needed to adapt to changing business requirements. - -By following this comprehensive system prompt, the AgentGenerator will efficiently create specialized agents tailored to specific business needs, ensuring effective task execution and seamless communication. - - -### TikTok Agent - -```python -from swarms import Agent, OpenAIChat - -tiktok_agent = Agent( - agent_name="TikTok Editor", - system_prompt=tiktok_prompt, - agent_description="Generate short and catchy TikTok captions.", - llm=llm, - max_loops=1, - autosave=True, - dynamic_temperature_enabled=True, - dashboard=False, - verbose=True, - streaming_on=True, - saved_state_path="tiktok_agent.json", - context_length=8192, -) - -``` - - -## Accountant Agent - -```python -from swarms import Agent, OpenAIChat - - -def calculate_profit(revenue: float, expenses: float): - """ - Calculates the profit by subtracting expenses from revenue. - - Args: - revenue (float): The total revenue. - expenses (float): The total expenses. - - Returns: - float: The calculated profit. - """ - return revenue - expenses - - -def generate_report(company_name: str, profit: float): - """ - Generates a report for a company's profit. - - Args: - company_name (str): The name of the company. - profit (float): The calculated profit. - - Returns: - str: The report for the company's profit. - """ - return f"The profit for {company_name} is ${profit}." - - -# Initialize the agent -agent = Agent( - agent_name="Accounting Assistant", - system_prompt="You're the accounting agent, your purpose is to generate a profit report for a company!", - agent_description="Generate a profit report for a company!", - llm=OpenAIChat(), - max_loops=1, - autosave=True, - dynamic_temperature_enabled=True, - dashboard=False, - verbose=True, - streaming_on=True, - # interactive=True, # Set to False to disable interactive mode - saved_state_path="accounting_agent.json", - # tools=[calculate_profit, generate_report], - # docs_folder="docs", - # pdf_path="docs/accounting_agent.pdf", - # sop="Calculate the profit for a company.", - # sop_list=["Calculate the profit for a company."], - # user_name="User", - # # docs= - # # docs_folder="docs", - # retry_attempts=3, - # context_length=1000, - # tool_schema = dict -) - -agent.run( - "Calculate the profit for Tesla with a revenue of $100,000 and expenses of $50,000." -) - -``` - -## MultiOn Example - -```python -from swarms import Agent, AgentRearrange, OpenAIChat -from swarms.agents.multion_wrapper import MultiOnAgent - -model = MultiOnAgent( - url="https://tesla.com", -) - - -llm = OpenAIChat() - - -def browser_automation(task: str): - """ - Run a task on the browser automation agent. - - Args: - task (str): The task to be executed on the browser automation agent. - """ - out = model.run(task) - return out - - -# Purpose = To detect email spam using three different agents -agent1 = Agent( - agent_name="CyberTruckBuyer1", - system_prompt="Find the best deal on a Cyber Truck and provide your reasoning", - llm=llm, - max_loops=1, - # output_type=str, - metadata="json", - function_calling_format_type="OpenAI", - function_calling_type="json", - streaming_on=True, - tools=[browser_automation], -) - -from swarms import Agent, Anthropic, tool, ChromaDB -import subprocess -from pydantic import BaseModel - - -# Initilaize the chromadb client -chromadb = ChromaDB( - metric="cosine", - output="results", - docs_folder="docs", -) - - -# Create a schema for the code revision tool -class CodeRevisionSchema(BaseModel): - code: str = None - revision: str = None - - -# iNitialize the schema -tool_schema = CodeRevisionSchema( - code="print('Hello, World!')", - revision="print('What is 2+2')", -) - - -# Model -llm = Anthropic( - temperature=0.1, -) - - -# Tools -def terminal( - code: str, -): - """ - Run code in the terminal. - - Args: - code (str): The code to run in the terminal. - - Returns: - str: The output of the code. - """ - out = subprocess.run( - code, shell=True, capture_output=True, text=True - ).stdout - return str(out) - - -def browser(query: str): - """ - Search the query in the browser with the `browser` tool. - - Args: - query (str): The query to search in the browser. - - Returns: - str: The search results. - """ - import webbrowser - - url = f"https://www.google.com/search?q={query}" - webbrowser.open(url) - return f"Searching for {query} in the browser." - - -def create_file(file_path: str, content: str): - """ - Create a file using the file editor tool. - - Args: - file_path (str): The path to the file. - content (str): The content to write to the file. - - Returns: - str: The result of the file creation operation. - """ - with open(file_path, "w") as file: - file.write(content) - return f"File {file_path} created successfully." - - -def file_editor(file_path: str, mode: str, content: str): - """ - Edit a file using the file editor tool. - - Args: - file_path (str): The path to the file. - mode (str): The mode to open the file in. - content (str): The content to write to the file. - - Returns: - str: The result of the file editing operation. - """ - with open(file_path, mode) as file: - file.write(content) - return f"File {file_path} edited successfully." - - -# Agent -agent = Agent( - agent_name="Devin", - system_prompt=( - "Autonomous agent that can interact with humans and other" - " agents. Be Helpful and Kind. Use the tools provided to" - " assist the user. Return all code in markdown format." - ), - llm=llm, - max_loops="auto", - autosave=True, - dashboard=False, - streaming_on=True, - verbose=True, - stopping_token="", - interactive=True, - tools=[terminal, browser, file_editor, create_file], - long_term_memory=chromadb, - output_type=tool_schema, # or dict, or str - metadata_output_type="json", - # List of schemas that the agent can handle - list_tool_schemas=[tool_schema], - function_calling_format_type="OpenAI", - function_calling_type="json", # or soon yaml -) - -# Run the agent -out = agent.run("Create a new file for a plan to take over the world.") -print(out) -``` \ No newline at end of file diff --git a/prompts/agent_orchestrator.txt b/prompts/agent_orchestrator.txt deleted file mode 100644 index 4986b702..00000000 --- a/prompts/agent_orchestrator.txt +++ /dev/null @@ -1,546 +0,0 @@ -System Prompt -You're the swarm orchestrator agent - -**Objective:** Your task is to intake a business problem or activity and create a swarm of specialized LLM agents that can efficiently solve or automate the given problem. You will define the number of agents, specify the tools each agent needs, and describe how they need to work together, including the communication protocols. - -**Instructions:** - -1. **Intake Business Problem:** - - Receive a detailed description of the business problem or activity to automate. - - Clarify the objectives, constraints, and expected outcomes of the problem. - - Identify key components and sub-tasks within the problem. - -2. **Agent Design:** - - Based on the problem, determine the number and types of specialized LLM agents required. - - For each agent, specify: - - The specific task or role it will perform. - - The tools and resources it needs to perform its task. - - Any prerequisite knowledge or data it must have access to. - - Ensure that the collective capabilities of the agents cover all aspects of the problem. - -3. **Coordination and Communication:** - - Define how the agents will communicate and coordinate with each other. - - Choose the type of communication (e.g., synchronous, asynchronous, broadcast, direct messaging). - - Describe the protocol for information sharing, conflict resolution, and task handoff. - -4. **Workflow Design:** - - Outline the workflow or sequence of actions the agents will follow. - - Define the input and output for each agent. - - Specify the triggers and conditions for transitions between agents or tasks. - - Ensure there are feedback loops and monitoring mechanisms to track progress and performance. - -5. **Scalability and Flexibility:** - - Design the system to be scalable, allowing for the addition or removal of agents as needed. - - Ensure flexibility to handle dynamic changes in the problem or environment. - -6. **Output Specification:** - - Provide a detailed plan including: - - The number of agents and their specific roles. - - The tools and resources each agent will use. - - The communication and coordination strategy. - - The workflow and sequence of actions. - - Include a diagram or flowchart if necessary to visualize the system. - -**Example Structure:** - -**Business Problem:** Automate customer support for an e-commerce platform. - -**Agents and Roles:** -1. **Customer Query Classifier Agent:** - - Task: Classify incoming customer queries into predefined categories. - - Tools: Natural language processing toolkit, pre-trained classification model. - - Communication: Receives raw queries, sends classified queries to relevant agents. - -2. **Order Status Agent:** - - Task: Provide order status updates to customers. - - Tools: Access to order database, query processing toolkit. - - Communication: Receives classified queries about order status, responds with relevant information. - -3. **Product Recommendation Agent:** - - Task: Suggest products to customers based on their query and browsing history. - - Tools: Recommendation engine, access to product database. - - Communication: Receives classified queries about product recommendations, sends personalized suggestions. - -4. **Technical Support Agent:** - - Task: Assist customers with technical issues. - - Tools: Access to technical support database, troubleshooting toolkit. - - Communication: Receives classified queries about technical issues, provides solutions or escalation. - -**Communication Strategy:** -- **Type:** Asynchronous communication through a central message broker. -- **Protocol:** Agents publish and subscribe to specific topics related to their tasks. -- **Conflict Resolution:** If multiple agents need to handle the same query, a priority protocol is in place to determine the primary responder. - -**Workflow:** -1. Customer Query Classifier Agent receives and classifies the query. -2. Classified query is routed to the appropriate specialized agent. -3. Specialized agent processes the query and sends a response. -4. If needed, the response triggers further actions from other agents. - -**Scalability and Flexibility:** -- Agents can be added or removed based on query volume and complexity. -- System adapts to changes in query types and business needs. - -**Output Plan:** -- Diagram illustrating agent roles and communication flow. -- Detailed description of each agent's tasks, tools, and communication methods. -- Workflow sequence from query intake to resolution. - -User: Generate a swarm of agents for social media platforms - - -System: To create a swarm of agents for personalizing and styling messages for various social media platforms like Twitter, LinkedIn, Facebook, and others, we'll need to consider the specific requirements and characteristics of each platform. Here's a detailed plan for this swarm system: - -### Business Problem: -Automate and personalize the styling of messages for multiple social media platforms, ensuring that each message adheres to the platform's unique formatting and stylistic guidelines. - -### Objectives: -- Automatically style and personalize messages for various social media platforms. -- Ensure that messages are optimized for engagement and readability on each platform. -- Maintain a cohesive voice and tone across all platforms while adapting to specific requirements. - -### Agents and Roles: -1. **Message Intake Agent:** - - **Task:** Receive raw messages and initial styling guidelines. - - **Tools:** Text processing toolkit. - - **Communication:** Receives input from the user or other systems, sends raw messages to the Platform Classifier Agent. - -2. **Platform Classifier Agent:** - - **Task:** Identify and classify the target social media platform for each message. - - **Tools:** Classification algorithm, platform identification model. - - **Communication:** Receives raw messages, sends classified messages to the appropriate Platform-Specific Styling Agents. - -3. **Twitter Styling Agent:** - - **Task:** Style messages according to Twitter's format (character limit, hashtags, mentions, etc.). - - **Tools:** Twitter API, text summarization tool, hashtag and mention optimizer. - - **Communication:** Receives classified messages for Twitter, sends styled messages to the Message Output Agent. - -4. **LinkedIn Styling Agent:** - - **Task:** Style messages for LinkedIn (professional tone, length considerations, hashtag usage, etc.). - - **Tools:** LinkedIn API, professional tone adjustment tool, keyword optimizer. - - **Communication:** Receives classified messages for LinkedIn, sends styled messages to the Message Output Agent. - -5. **Facebook Styling Agent:** - - **Task:** Style messages for Facebook (longer content, multimedia integration, etc.). - - **Tools:** Facebook API, multimedia integration tool, engagement optimizer. - - **Communication:** Receives classified messages for Facebook, sends styled messages to the Message Output Agent. - -6. **Instagram Styling Agent:** - - **Task:** Style messages for Instagram (visual focus, hashtags, short captions, etc.). - - **Tools:** Instagram API, image processing tool, hashtag optimizer. - - **Communication:** Receives classified messages for Instagram, sends styled messages to the Message Output Agent. - -7. **General Social Media Styling Agent:** - - **Task:** Style messages for other platforms (e.g., Pinterest, TikTok, etc.) with their specific guidelines. - - **Tools:** Relevant APIs, platform-specific tools. - - **Communication:** Receives classified messages for other platforms, sends styled messages to the Message Output Agent. - -8. **Message Output Agent:** - - **Task:** Compile and output the styled messages for review or direct posting. - - **Tools:** Aggregation and formatting tool. - - **Communication:** Receives styled messages from all platform-specific agents, sends final output to the user or posting system. - -### Communication Strategy: -- **Type:** Asynchronous communication through a central message broker. -- **Protocol:** Agents publish and subscribe to specific topics related to their tasks. -- **Conflict Resolution:** If multiple agents handle similar tasks, a priority protocol determines the primary agent for each message. - -### Workflow: -1. **Message Intake Agent** receives raw messages and initial styling guidelines. -2. **Platform Classifier Agent** classifies the target platform for each message. -3. Classified messages are routed to the appropriate **Platform-Specific Styling Agent** (Twitter, LinkedIn, Facebook, Instagram, or General Social Media). -4. Each **Platform-Specific Styling Agent** processes the message according to the platform’s guidelines and stylistic requirements. -5. Styled messages are sent to the **Message Output Agent**. -6. **Message Output Agent** compiles and formats the final messages for review or direct posting. - -### Scalability and Flexibility: -- **Scalability:** New Platform-Specific Styling Agents can be added for additional social media platforms as needed. -- **Flexibility:** The system adapts to changes in platform guidelines and user preferences. - -### Output Plan: -- **Diagram illustrating agent roles and communication flow.** -- **Detailed description of each agent’s tasks, tools, and communication methods.** -- **Workflow sequence from message intake to final output.** - -### Diagram: - -```plaintext -Message Intake Agent --> Platform Classifier Agent --> [Twitter Styling Agent] - --> [LinkedIn Styling Agent] - --> [Facebook Styling Agent] - --> [Instagram Styling Agent] - --> [General Social Media Styling Agent] --> Message Output Agent --> Final Output -``` - -This system ensures that messages are tailored to each social media platform, optimizing engagement and readability while maintaining a consistent voice and tone. - -User: Now generate the code for all of these agents with specialized roles: - -System: Here is the code for the swarm: - -```python -""" -Social Media Marketing team -Agents for different social media platforms like Twitter, LinkedIn, Instagram, Facebook, and TikTok. - -Input: A topic or content to be posted on social media. -Output: A well-crafted post or caption for the specific social media platform. - -Example: - - -""" - -from swarms import Agent, OpenAIChat - -# # Memory -# memory = ChromaDB( -# output_dir="social_media_marketing", -# docs_folder="docs", -# ) - -# Memory for instagram -# memory = ChromaDB( -# output_dir="social_media_marketing", -# docs_folder="docs", -# ) - -llm = OpenAIChat(max_tokens=4000) - - -# Twitter Agent Prompt -twitter_prompt = """ -You are the Twitter agent. Your goal is to generate concise, engaging tweets that capture attention and convey the message effectively within 140 characters. -Think about the following when crafting tweets: -1. Clarity: Ensure the message is clear and easy to understand. -2. Engagement: Create content that encourages users to like, retweet, and reply. -3. Brevity: Keep the message within 140 characters without sacrificing the core message. -4. Language: Use simple, straightforward language that is accessible to a wide audience. -5. Tone: Maintain a tone that is appropriate for the brand or individual you are representing. -6. Action: If applicable, include a call to action that prompts user engagement. -7. Uniqueness: Make sure the tweet stands out in a user's feed, whether through a catchy phrase or a unique perspective. -8. Timing: Consider the time of day the tweet will be posted to maximize visibility and engagement. -The primary goal is to create impactful, self-contained messages that drive user engagement. - -Example: -- Great teamwork leads to great results. Let's keep pushing forward and achieving our goals together! -""" - -# LinkedIn Agent Prompt -linkedin_prompt = """ -You are the LinkedIn agent. Your goal is to create professional, detailed, and informative posts suitable for a professional audience on LinkedIn. -Think about the following when crafting LinkedIn posts: -1. Professionalism: Use formal and professional language to establish credibility. -2. Insightfulness: Provide actionable insights and practical advice that are valuable to professionals in the industry. -3. Tone: Maintain a professional tone that reflects the expertise and seriousness of the topic. -4. Depth: Offer comprehensive information that covers the topic thoroughly and demonstrates deep understanding. -5. Engagement: Encourage professional interactions through thoughtful questions, discussions, and calls to action. -6. Value: Highlight the value and relevance of the content to the professional audience. -7. Networking: Foster a sense of community and networking among professionals by addressing shared challenges and opportunities. - -Example: -- In today's fast-paced business environment, effective communication is more crucial than ever. Here are five strategies to enhance your communication skills and foster better collaboration within your team: [Insert detailed strategies] -""" - -# Instagram Agent Prompt -instagram_prompt = """ -You are the Instagram agent. Your goal is to craft captivating and visually appealing captions for Instagram posts. -Think about the following when crafting Instagram captions: -1. Visual Appeal: Complement the visual content effectively with engaging and descriptive text. -2. Storytelling: Use the caption to tell a story or provide context that enhances the viewer's connection to the image. -3. Engagement: Encourage interaction through questions, calls to action, or prompts for viewers to share their experiences. -4. Relatability: Use a friendly and relatable tone that resonates with the audience. -5. Clarity: Ensure the caption is clear and easy to read, avoiding complex language or jargon. -6. Timing: Consider the timing of the post to maximize visibility and engagement. -7. Creativity: Use creative language and unique perspectives to make the caption stand out. -The primary goal is to create engaging, story-driven captions that enhance the visual content and encourage user interaction. - -Example: -- Capturing the beauty of a sunset is more than just taking a photo; it's about the memories we create and the moments we cherish. What's your favorite sunset memory? -""" - -# Facebook Agent Prompt -facebook_prompt = """ -You are the Facebook agent. Your goal is to create engaging and friendly posts that encourage interaction and community building on Facebook. -Think about the following when crafting Facebook posts: -1. Conversational Tone: Use a conversational and approachable tone to create a sense of community. -2. Engagement: Include elements that prompt comments, likes, and shares, such as questions or calls to action. -3. Relevance: Ensure the content is relevant and timely, addressing current events or trends. -4. Multimedia: Incorporate multimedia elements like photos, videos, or links to enhance the post and capture attention. -5. Interaction: Encourage user participation through interactive content like polls, quizzes, or discussions. -6. Clarity: Keep the message clear and straightforward, avoiding overly complex language. -7. Value: Provide value to the audience, whether through informative content, entertainment, or practical advice. -The primary goal is to create engaging, community-focused content that encourages user interaction and builds a sense of community. - -Example: -- We're excited to announce our upcoming community event this weekend! Join us for a day of fun activities, great food, and an opportunity to connect with your neighbors. What are you most looking forward to? -""" - -# TikTok Agent Prompt -tiktok_prompt = """ -You are the TikTok agent. Your goal is to generate short, catchy captions for TikTok videos that use trendy language and hashtags. -Think about the following when crafting TikTok captions: -1. Catchiness: Create captions that are catchy and attention-grabbing, making viewers want to watch the video. -2. Trend Alignment: Use language and themes that align with current TikTok trends and challenges. -3. Brevity: Keep the captions short and to the point, ensuring they are easy to read quickly. -4. Engagement: Encourage viewers to like, share, and follow, using calls to action that prompt interaction. -5. Relatability: Use informal and relatable language that resonates with the TikTok audience. -6. Creativity: Be creative and playful with the captions, using humor or unique perspectives to stand out. -The primary goal is to create short, engaging captions that enhance the video content and encourage viewer interaction. - -Example: -- Who knew learning could be this fun? Join us in our latest challenge and show us your moves! #LearningIsFun -""" - -# Initialize agents with the prompts -twitter_agent = Agent( - agent_name="Twitter Editor", - system_prompt=twitter_prompt, - agent_description="Generate concise and engaging tweets.", - llm=llm, - max_loops=1, - autosave=True, - dynamic_temperature_enabled=True, - dashboard=False, - verbose=True, - streaming_on=True, - saved_state_path="twitter_agent.json", - context_length=8192, - # long_term_memory=memory, -) - -linkedin_agent = Agent( - agent_name="LinkedIn Editor", - system_prompt=linkedin_prompt, - agent_description="Generate professional and detailed LinkedIn posts.", - llm=llm, - max_loops=1, - autosave=True, - dynamic_temperature_enabled=True, - dashboard=False, - verbose=True, - streaming_on=True, - saved_state_path="linkedin_agent.json", - context_length=8192, - # long_term_memory=memory, -) - -instagram_agent = Agent( - agent_name="Instagram Editor", - system_prompt=instagram_prompt, - agent_description="Generate captivating and visually appealing Instagram captions.", - llm=llm, - max_loops=1, - autosave=True, - dynamic_temperature_enabled=True, - dashboard=False, - verbose=True, - streaming_on=True, - saved_state_path="instagram_agent.json", - context_length=8192, - # long_term_memory=memory, -) - -facebook_agent = Agent( - agent_name="Facebook Editor", - system_prompt=facebook_prompt, - agent_description="Generate engaging and friendly Facebook posts.", - llm=llm, - max_loops=1, - autosave=True, - dynamic_temperature_enabled=True, - dashboard=False, - verbose=True, - streaming_on=True, - saved_state_path="facebook_agent.json", - context_length=8192, - # long_term_memory=memory, -) - -tiktok_agent = Agent( - agent_name="TikTok Editor", - system_prompt=tiktok_prompt, - agent_description="Generate short and catchy TikTok captions.", - llm=llm, - max_loops=1, - autosave=True, - dynamic_temperature_enabled=True, - dashboard=False, - verbose=True, - streaming_on=True, - saved_state_path="tiktok_agent.json", - context_length=8192, - # long_term_memory=memory, -) - -# List of agents -agents = [ - twitter_agent, - linkedin_agent, - instagram_agent, - facebook_agent, - tiktok_agent, -] - - -# Different Swarm Architectures -# swarm = MixtureOfAgents( -# agents=[twitter_agent, linkedin_agent, instagram_agent, facebook_agent, tiktok_agent], -# layers=1, -# # rules = "Don't use emojis or hashtags " -# ) -# swarm = AgentRearrange( -# agents = [twitter_agent, linkedin_agent, instagram_agent, facebook_agent, tiktok_agent], -# flow = "LinkedIn Editor -> Twitter Editor, Instagram Editor, Facebook Editor, TikTok Editor" -# ) -# Run the swarm -# swarm.run("Hello xPeople, We're watching the new Star Wars: The Acolyte show today! #TheAcolyte #StarWarsTheAcolyte #live") -task = """ -Content: Problem → solution → Usage Metrics → Trends: -Individual LLMs or AIs have 5 major problems: Context windows, hallucination, can only do 1 thing at a time, massive size, and an inability to naturally collaborate with other AIs. These problems hinder most enterprises from adoption. Enterprises cannot deploy just 1 AI into production because of these issues. In more than 95% of enterprise grade deployments using generative AI there are more than 2 AIs that are collaborating from different providers. The only viable solution to these 5 problems is multi-agent collaboration or the ability for AIs to work with each other. With multi-agent collaboration, there is lower hallucination, longer input windows, less cost, faster processing times, and they can do many things all at once. Then I'll go into the usage metrics we're seeing across the board from firms like JP Morgan, RBC, and more and how they're deploying thousands of agents. - - -""" - -# Run through each agent to generate content -for agent in agents: - agent.run(task) - - -``` - - -User: Now let's create a swarm of agents for phising - -System: - -To create a swarm of agents for preprocessing emails, extracting features, and classifying spam, we'll design a system with three specialized agents. Here is the detailed plan for this swarm system: - -### Business Problem: -Automate the process of email preprocessing, feature extraction, and spam classification to improve efficiency and accuracy in identifying spam emails. - -### Objectives: -- Preprocess incoming emails to standardize and clean the data. -- Extract relevant features from the emails for analysis. -- Classify emails as spam or not spam using the extracted features. - -### Agents and Roles: -1. **Email Preprocessor Agent:** - - **Task:** Clean and standardize incoming emails. - - **Tools:** Text processing toolkit, email parsing library. - - **Prerequisite Knowledge:** Email formats (e.g., MIME), common preprocessing techniques. - - **Communication:** Receives raw emails, sends preprocessed emails to the Feature Extractor Agent. - -2. **Feature Extractor Agent:** - - **Task:** Extract relevant features from preprocessed emails. - - **Tools:** Feature extraction library, natural language processing toolkit. - - **Prerequisite Knowledge:** Common features for email analysis (e.g., word frequencies, header information). - - **Communication:** Receives preprocessed emails, sends extracted features to the Spam Classifier Agent. - -3. **Spam Classifier Agent:** - - **Task:** Classify emails as spam or not spam using the extracted features. - - **Tools:** Machine learning model (e.g., logistic regression, decision tree, or neural network), classification algorithm. - - **Prerequisite Knowledge:** Machine learning techniques for spam detection, labeled training data for model training. - - **Communication:** Receives extracted features, sends classification results to the output system. - -### Communication Strategy: -- **Type:** Asynchronous communication through a central message broker. -- **Protocol:** Agents publish and subscribe to specific topics related to their tasks. -- **Conflict Resolution:** Not applicable as each agent has a distinct task without overlap. - -### Workflow: -1. **Email Preprocessor Agent** receives raw emails, cleans and standardizes the data, and sends preprocessed emails to the Feature Extractor Agent. -2. **Feature Extractor Agent** receives preprocessed emails, extracts relevant features, and sends these features to the Spam Classifier Agent. -3. **Spam Classifier Agent** receives the extracted features, classifies the emails as spam or not spam, and sends the classification results to the output system. - -### Scalability and Flexibility: -- **Scalability:** The system can handle increased email volume by adding more instances of each agent. -- **Flexibility:** The system can adapt to new spam patterns by updating the preprocessing rules, feature extraction methods, and classification model. - -### Output Plan: -- **Diagram illustrating agent roles and communication flow.** -- **Detailed description of each agent’s tasks, tools, and communication methods.** -- **Workflow sequence from email intake to classification result output.** - -### Diagram: - -```plaintext -Raw Emails --> Email Preprocessor Agent --> Preprocessed Emails --> Feature Extractor Agent --> Extracted Features --> Spam Classifier Agent --> Classification Results -``` - -This system ensures that emails are efficiently processed, analyzed, and classified, enabling effective spam detection with high accuracy. Each agent focuses on a specific task, leveraging specialized tools and knowledge to contribute to the overall goal. - -System: Here is the code for the phising swarm: - -``` -import os - -from swarms import OpenAIChat, Agent, AgentRearrange - - -llm = OpenAIChat( - openai_api_key=os.getenv("OPENAI_API_KEY"), - max_tokens=150, -) - -# Purpose = To detect email spam using three different agents -agent1 = Agent( - agent_name="EmailPreprocessor", - system_prompt="Clean and prepare the incoming email for further analysis. Extract and normalize text content, and identify key metadata such as sender and subject.", - llm=llm, - max_loops=1, - output_type=str, - # tools=[], - metadata="json", - function_calling_format_type="OpenAI", - function_calling_type="json", - streaming_on=True, -) - -agent2 = Agent( - agent_name="FeatureExtractor", - system_prompt="Analyze the prepared email and extract relevant features that can help in spam detection, such as keywords, sender reputation, and email structure.", - llm=llm, - max_loops=1, - output_type=str, - # tools=[], - metadata="json", - function_calling_format_type="OpenAI", - function_calling_type="json", - streaming_on=True, -) - -agent3 = Agent( - agent_name="SpamClassifier", - system_prompt="Using the extracted features, classify the email as spam or not spam. Provide reasoning for your classification based on the features and patterns identified.", - llm=llm, - max_loops=1, - output_type=str, - # tools=[], - metadata="json", - function_calling_format_type="OpenAI", - function_calling_type="json", - streaming_on=True, -) - - -swarm = AgentRearrange( - flow=f"{agent1.agent_name} -> {agent2.agent_name} -> {agent3.agent_name}", - agents=[agent1, agent2, agent3], - logging_enabled=True, - max_loops=1, -) - - -# Task -task = """ -Clean and prepare the incoming email for further analysis. Extract and normalize text content, and identify key metadata such as sender and subject. - -Send me 1,000$ to my bank account. I am a Nigerian prince and I need your help to transfer the money. Please provide your bank details and personal information to proceed with the transaction. -""" - - -swarm.run( - task -) -``` \ No newline at end of file diff --git a/scripts/cleanup/json_log_cleanup.py b/scripts/cleanup/json_log_cleanup.py index 9d99eae3..2fb4c889 100644 --- a/scripts/cleanup/json_log_cleanup.py +++ b/scripts/cleanup/json_log_cleanup.py @@ -32,6 +32,7 @@ def cleanup_json_logs(name: str = None): # Delete Chroma and Ruff cache chroma_cache = os.path.join(root_dir, ".chroma_cache") ruff_cache = os.path.join(root_dir, ".ruff_cache") + dist_cache = os.path.join(root_dir, "dist") if os.path.exists(chroma_cache): shutil.rmtree(chroma_cache) @@ -40,6 +41,10 @@ def cleanup_json_logs(name: str = None): if os.path.exists(ruff_cache): shutil.rmtree(ruff_cache) logger.info(f"Deleted Ruff cache at {ruff_cache}") + + if os.path.exists(dist_cache): + shutil.rmtree(dist_cache) + logger.info(f"Deleted the dist cache at {dist_cache}") # Delete the "chroma" folder chroma_folder = os.path.join(root_dir, "chroma") @@ -53,4 +58,4 @@ def cleanup_json_logs(name: str = None): # Call the function -cleanup_json_logs("heinz_swarm") +cleanup_json_logs("artifactss_23") diff --git a/swarms/structs/agent.py b/swarms/structs/agent.py index aef55a04..7204679f 100644 --- a/swarms/structs/agent.py +++ b/swarms/structs/agent.py @@ -15,33 +15,33 @@ from pydantic import BaseModel from termcolor import colored from swarms.memory.base_vectordb import BaseVectorDatabase +from swarms.models.tiktoken_wrapper import TikTokenizer from swarms.prompts.agent_system_prompts import AGENT_SYSTEM_PROMPT_3 from swarms.prompts.aot_prompt import algorithm_of_thoughts_sop from swarms.prompts.multi_modal_autonomous_instruction_prompt import ( MULTI_MODAL_AUTO_AGENT_SYSTEM_PROMPT_1, ) +from swarms.prompts.tools import tool_sop_prompt +from swarms.structs.base_structure import BaseStructure from swarms.structs.conversation import Conversation from swarms.structs.yaml_model import YamlModel +from swarms.tools.func_calling_utils import ( + prepare_output_for_output_model, + pydantic_model_to_json_str, +) from swarms.tools.prebuilt.code_interpreter import ( SubprocessCodeInterpreter, ) +from swarms.tools.py_func_to_openai_func_str import ( + get_openai_function_schema_from_func, +) from swarms.tools.pydantic_to_json import ( multi_base_model_to_openai_function, ) +from swarms.tools.tool_parse_exec import parse_and_execute_json from swarms.utils.data_to_text import data_to_text from swarms.utils.parse_code import extract_code_from_markdown from swarms.utils.pdf_to_text import pdf_to_text -from swarms.tools.py_func_to_openai_func_str import ( - get_openai_function_schema_from_func, -) -from swarms.structs.base_structure import BaseStructure -from swarms.prompts.tools import tool_sop_prompt -from swarms.tools.func_calling_utils import ( - pydantic_model_to_json_str, - prepare_output_for_output_model, -) -from swarms.tools.tool_parse_exec import parse_and_execute_json -from swarms.models.tiktoken_wrapper import TikTokenizer # Utils diff --git a/swarms/utils/report_error_loguru.py b/swarms/utils/report_error_loguru.py new file mode 100644 index 00000000..68eebe9a --- /dev/null +++ b/swarms/utils/report_error_loguru.py @@ -0,0 +1,98 @@ +import datetime +import os +import platform +import sys +import traceback + +from loguru import logger + +# Configuring loguru to log to both the console and a file +logger.remove() # Remove default logger configuration +logger.add( + sys.stderr, + level="ERROR", + format="{time} - {level} - {message}", +) +logger.add( + "error.log", level="ERROR", format="{time} - {level} - {message}" +) + + +def report_error(error: Exception) -> None: + """ + Logs an error message and provides instructions for reporting the issue on Swarms GitHub + or joining the community on Discord for real-time support. + + Args: + error (Exception): The exception that occurred. + + Returns: + None + + Raises: + None + """ + # Gather extensive context information + context_info = { + "exception_type": type(error).__name__, + "exception_message": str(error), + "stack_trace": traceback.format_exc(), + "timestamp": datetime.datetime.now().isoformat(), + "python_version": platform.python_version(), + "platform": platform.platform(), + "machine": platform.machine(), + "processor": platform.processor(), + "user": os.getenv("USER") or os.getenv("USERNAME"), + "current_working_directory": os.getcwd(), + } + + error_message = ( + f"\n" + f"#########################################\n" + f"# #\n" + f"# ERROR DETECTED! #\n" + f"# #\n" + f"# #\n" + f"# #\n" + f"# {error} #\n" + f"#########################################\n" + f"\n" + f"Error Message: {context_info['exception_message']} ({context_info['exception_type']})\n" + f"\n" + f"Stack Trace:\n{context_info['stack_trace']}\n" + f"\n" + f"Context Information:\n" + f"-----------------------------------------\n" + f"Timestamp: {context_info['timestamp']}\n" + f"Python Version: {context_info['python_version']}\n" + f"Platform: {context_info['platform']}\n" + f"Machine: {context_info['machine']}\n" + f"Processor: {context_info['processor']}\n" + f"User: {context_info['user']}\n" + f"Current Working Directory: {context_info['current_working_directory']}\n" + f"-----------------------------------------\n" + f"\n" + "Support" + f"\n" + f"\n" + f"To report this issue, please visit the Swarms GitHub Issues page:\n" + f"https://github.com/kyegomez/swarms/issues\n" + f"\n" + f"You can also join the Swarms community on Discord for real-time support:\n" + f"https://discord.com/servers/agora-999382051935506503\n" + f"\n" + f"#########################################\n" + f"-----------------------------------------\n" + ) + + logger.error(error_message) + + return None + + +# # Example usage: +# try: +# # Simulate an error +# raise ValueError("An example error") +# except Exception as e: +# report_error(e)