parent
9e4f5a1561
commit
9366437976
@ -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: `<DONE>`
|
|
||||||
|
|
||||||
#### Methods:
|
|
||||||
|
|
||||||
1. `__init__(self, stopping_token: str = "<DONE>")`: 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.
|
|
@ -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="<DONE>")
|
|
||||||
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.
|
|
@ -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.
|
|
||||||
|
|
Before Width: | Height: | Size: 174 KiB After Width: | Height: | Size: 174 KiB |
@ -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)
|
@ -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="<DONE>",
|
|
||||||
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)
|
|
||||||
```
|
|
@ -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="<red>{time}</red> - <level>{level}</level> - <level>{message}</level>",
|
||||||
|
)
|
||||||
|
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)
|
Loading…
Reference in new issue