[DOCS]Simplificaiton]

pull/488/head
Kye Gomez 7 months ago
parent 25adc2c360
commit 1f564108fa

@ -1,49 +0,0 @@
# Release Notes
## 3.7.5
2024-01-21
### Bug Fixes
Fix imports of Agent, SequentialWorkflow, ModelParallelizer, Task, OpenAIChat, Gemini, GPT4VisionAPI
### New Features
New model: Odin for Object Detection and tracking
New mode: Ultralytics Object recognition YOLO
New Tokenizers
Schema generator for prompts.
New prompt for worker agent.
New structure: plan, step
New tool: execute tool
New logger: get_logger
Example for worker_agent
## 3.6.8
2024-01-19
### Bug Fixes
Removed ModelScope
Removed CogAgent
### New Features
Added ultralytics vision models
Added TimmModel to wrap timm models
### Other
Loosened version of timm

@ -94,40 +94,37 @@ markdown_extensions:
- tables
- def_list
- footnotes
nav:
- Home:
- Installation:
- Overview: "index.md"
- Install: "install.md"
- Docker Setup: docker_setup.md
- Install: "swarms/install/install.md"
- Docker Setup: "swarms/install/docker_setup.md"
- Usage Examples:
- Build an Agent: "diy_your_own_agent.md"
- Build an Agent with tools: "examples/tools_agents.md"
# Add an examples with building agents
# Add multiple blogs on orchestrating agents with different types of frameworks
- Why does Swarms Exist?:
- Why Swarms? Orchestrating Agents for Enterprise Automation: "why.md"
- Limitations of Individual Agents: "limits_of_individual_agents.md"
- References:
- Agent Glossary: "swarms/glossary.md"
- List of The Best Multi-Agent Papers: "swarms/papers.md"
- Swarms Framework [PY]:
- Models:
- How to Create A Custom Language Model: "swarms/models/custom_model.md"
- Models Available: "swarms/models/index.md"
- MultiModal Models Available: "swarms/models/multimodal_models.md"
- Agents:
- Getting started with Agents: "diy_your_own_agent.md"
- Tools:
- The Swarms Tool System Functions, Pydantic BaseModels as Tools, and Radical Customization: "swarms/tools/main.md"
- Memory:
- Building Custom Vector Memory Databases with the BaseVectorDatabase Class: "swarms/memory/diy_memory.md"
- ShortTermMemory: "swarms/memory/short_term_memory.md"
- Multi-Agent Collaboration:
- Models:
- How to Create A Custom Language Model: "swarms/models/custom_model.md"
- Models Available: "swarms/models/index.md"
- MultiModal Models Available: "swarms/models/multimodal_models.md"
- Agents:
- Getting started with Agents: "swarms/structs/diy_your_own_agent.md"
- Tools:
- The Swarms Tool System Functions, Pydantic BaseModels as Tools, and Radical Customization: "swarms/tools/main.md"
- Memory:
- Building Custom Vector Memory Databases with the BaseVectorDatabase Class: "swarms/memory/diy_memory.md"
- ShortTermMemory: "swarms/memory/short_term_memory.md"
- Multi-Agent Collaboration:
- Conversation: "swarms/structs/conversation.md"
- SwarmNetwork: "swarms/structs/swarmnetwork.md"
- MajorityVoting: "swarms/structs/majorityvoting.md"
- AgentRearrange: "swarms/structs/agent_rearrange.md"
- Why does Swarms Exist?:
- Why Swarms? Orchestrating Agents for Enterprise Automation: "swarms/purpose/why.md"
- Limitations of Individual Agents: "swarms/purpose/limits_of_individual_agents.md"
- References:
- Agent Glossary: "swarms/glossary.md"
- List of The Best Multi-Agent Papers: "swarms/papers.md"
- Contributors:
- Contributing: "contributing.md"
- Swarms Framework Reference:
- swarms.models:
- How to Create A Custom Language Model: "swarms/models/custom_model.md"
@ -172,19 +169,16 @@ nav:
- Enterprise Guide to High-Performance Multi-Agent LLM Deployments: "swarms_cloud/production_deployment.md"
- Under The Hood The Swarm Cloud Serving Infrastructure: "swarms_cloud/architecture.md"
- Guides:
- Agents:
- Building Custom Vector Memory Databases with the BaseVectorDatabase Class: "swarms/memory/diy_memory.md"
# - Building Custom Vector Memory Databases with the BaseVectorDatabase Class: "swarms/memory/diy_memory.md"
- Models:
- How to Create A Custom Language Model: "swarms/models/custom_model.md"
- Deploying Azure OpenAI in Production, A Comprehensive Guide: "swarms/models/azure_openai.md"
- Agents:
- Agent: "examples/flow.md"
- DIY Build Your Own Agent: "diy_your_own_agent.md"
- Equipping Autonomous Agents with Tools: "examples/tools_agent.md"
- Overview: "examples/index.md"
- Agents:
- Agent: "examples/flow.md"
- OmniAgent: "examples/omni_agent.md"
- Swarms:
- SequentialWorkflow: "examples/reliable_autonomous_agents.md"
- 2O+ Autonomous Agent Blogs: "examples/ideas.md"
- Swarms:
- SequentialWorkflow: "examples/reliable_autonomous_agents.md"
- Applications:
- CustomerSupport:
- Overview: "applications/customer_support.md"
@ -207,6 +201,4 @@ nav:
- Design: "corporate/design.md"
- Metric: "corporate/metric.md"
- Organization:
- FrontEnd Member Onboarding: "corporate/front_end_contributors.md"
- Contributors:
- Contributing: "contributing.md"
- FrontEnd Member Onboarding: "corporate/front_end_contributors.md"

@ -261,49 +261,181 @@ In this example, we define a `PineconeVectorDatabase` class that inherits from `
Chroma is an open-source vector database library that provides efficient storage, retrieval, and manipulation of vector data using various backends, including DuckDB, Chromadb, and more.
```python
import logging
import os
import uuid
from typing import Optional
from chromadb.client import Client
from swarms import BaseVectorDatabase
class ChromaVectorDatabase(MyCustomVectorDatabase):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # Chroma initialization
        self.client = Client()
        self.collection = self.client.get_or_create_collection("vector_collection")
    def connect(self):
        # Chroma connection logic
        pass
    def close(self):
        # Close Chroma connection
        pass
    def query(self, query: str):
        # Execute Chroma query
        results = self.collection.query(query)
import chromadb
from dotenv import load_dotenv
        return results
from swarms.utils.data_to_text import data_to_text
from swarms.utils.markdown_message import display_markdown_message
from swarms.memory.base_vectordb import BaseVectorDatabase
    def add(self, doc: str):
        # Add document to Chroma collection
# Load environment variables
load_dotenv()
        self.collection.add(doc)
    # Implement other abstract methods
# Results storage using local ChromaDB
class ChromaDB(BaseVectorDatabase):
"""
ChromaDB database
Args:
metric (str): The similarity metric to use.
output (str): The name of the collection to store the results in.
limit_tokens (int, optional): The maximum number of tokens to use for the query. Defaults to 1000.
n_results (int, optional): The number of results to retrieve. Defaults to 2.
Methods:
add: _description_
query: _description_
Examples:
>>> chromadb = ChromaDB(
>>> metric="cosine",
>>> output="results",
>>> llm="gpt3",
>>> openai_api_key=OPENAI_API_KEY,
>>> )
>>> chromadb.add(task, result, result_id)
"""
def __init__(
self,
metric: str = "cosine",
output_dir: str = "swarms",
limit_tokens: Optional[int] = 1000,
n_results: int = 3,
docs_folder: str = None,
verbose: bool = False,
*args,
**kwargs,
):
self.metric = metric
self.output_dir = output_dir
self.limit_tokens = limit_tokens
self.n_results = n_results
self.docs_folder = docs_folder
self.verbose = verbose
# Disable ChromaDB logging
if verbose:
logging.getLogger("chromadb").setLevel(logging.INFO)
# Create Chroma collection
chroma_persist_dir = "chroma"
chroma_client = chromadb.PersistentClient(
settings=chromadb.config.Settings(
persist_directory=chroma_persist_dir,
),
*args,
**kwargs,
)
# Create ChromaDB client
self.client = chromadb.Client()
# Create Chroma collection
self.collection = chroma_client.get_or_create_collection(
name=output_dir,
metadata={"hnsw:space": metric},
*args,
**kwargs,
)
display_markdown_message(
"ChromaDB collection created:"
f" {self.collection.name} with metric: {self.metric} and"
f" output directory: {self.output_dir}"
)
# If docs
if docs_folder:
display_markdown_message(
f"Traversing directory: {docs_folder}"
)
self.traverse_directory()
def add(
self,
document: str,
*args,
**kwargs,
):
"""
Add a document to the ChromaDB collection.
Args:
document (str): The document to be added.
condition (bool, optional): The condition to check before adding the document. Defaults to True.
Returns:
str: The ID of the added document.
"""
try:
doc_id = str(uuid.uuid4())
self.collection.add(
ids=[doc_id],
documents=[document],
*args,
**kwargs,
)
print("-----------------")
print("Document added successfully")
print("-----------------")
return doc_id
except Exception as e:
raise Exception(f"Failed to add document: {str(e)}")
def query(
self,
query_text: str,
*args,
**kwargs,
):
"""
Query documents from the ChromaDB collection.
Args:
query (str): The query string.
n_docs (int, optional): The number of documents to retrieve. Defaults to 1.
Returns:
dict: The retrieved documents.
"""
try:
docs = self.collection.query(
query_texts=[query_text],
n_results=self.n_results,
*args,
**kwargs,
)["documents"]
return docs[0]
except Exception as e:
raise Exception(f"Failed to query documents: {str(e)}")
def traverse_directory(self):
"""
Traverse through every file in the given directory and its subdirectories,
and return the paths of all files.
Parameters:
- directory_name (str): The name of the directory to traverse.
Returns:
- list: A list of paths to each file in the directory and its subdirectories.
"""
added_to_db = False
for root, dirs, files in os.walk(self.docs_folder):
for file in files:
file = os.path.join(self.docs_folder, file)
_, ext = os.path.splitext(file)
data = data_to_text(file)
added_to_db = self.add(str(data))
print(f"{file} added to Database")
return added_to_db
```

@ -1,258 +0,0 @@
# AbstractWorker Class
====================
The `AbstractWorker` class is an abstract class for AI workers. An AI worker can communicate with other workers and perform actions. Different workers can differ in what actions they perform in the `receive` method.
## Class Definition
----------------
```
class AbstractWorker:
"""(In preview) An abstract class for AI worker.
An worker can communicate with other workers and perform actions.
Different workers can differ in what actions they perform in the `receive` method.
"""
```
## Initialization
--------------
The `AbstractWorker` class is initialized with a single parameter:
- `name` (str): The name of the worker.
```
def __init__(
self,
name: str,
):
"""
Args:
name (str): name of the worker.
"""
self._name = name
```
## Properties
----------
The `AbstractWorker` class has a single property:
- `name`: Returns the name of the worker.
```
@property
def name(self):
"""Get the name of the worker."""
return self._name
```
## Methods
-------
The `AbstractWorker` class has several methods:
### `run`
The `run` method is used to run the worker agent once. It takes a single parameter:
- `task` (str): The task to be run.
```
def run(
self,
task: str
):
"""Run the worker agent once"""
```
### `send`
The `send` method is used to send a message to another worker. It takes three parameters:
- `message` (Union[Dict, str]): The message to be sent.
- `recipient` (AbstractWorker): The recipient of the message.
- `request_reply` (Optional[bool]): If set to `True`, the method will request a reply from the recipient.
```
def send(
self,
message: Union[Dict, str],
recipient: AbstractWorker,
request_reply: Optional[bool] = None
):
"""(Abstract method) Send a message to another worker."""
```
### `a_send`
The `a_send` method is the asynchronous version of the `send` method. It takes the same parameters as the `send` method.
```
async def a_send(
self,
message: Union[Dict, str],
recipient: AbstractWorker,
request_reply: Optional[bool] = None
):
"""(Abstract async method) Send a message to another worker."""
```
### `receive`
The `receive` method is used to receive a message from another worker. It takes three parameters:
- `message` (Union[Dict, str]): The message to be received.
- `sender` (AbstractWorker): The sender of the message.
- `request_reply` (Optional[bool]): If set to `True`, the method will request a reply from the sender.
```
def receive(
self,
message: Union[Dict, str],
sender: AbstractWorker,
request_reply: Optional[bool] = None
):
"""(Abstract method) Receive a message from another worker."""
```
### `a_receive`
The `a_receive` method is the asynchronous version of the `receive` method. It takes the same parameters as the `receive` method.
```
async def a_receive(
self,
message: Union[Dict, str],
sender: AbstractWorker,
request_reply: Optional[bool] = None
):
"""(Abstract async method) Receive a message from another worker."""
```
### `reset`
The `reset` method is used to reset the worker.
```
def reset(self):
"""(Abstract method) Reset the worker."""
```
### `generate_reply`
The `generate_reply` method is used to generate a reply based on the received messages. It takes two parameters:
- `messages` (Optional[List[Dict]]): A list of messages received.
- `sender` (AbstractWorker): The sender of the messages.
The method returns a string, a dictionary, or `None`. If `None` is returned, no reply is generated.
```
def generate_reply(
self,
messages: Optional[List[Dict]] = None,
sender: AbstractWorker,
**kwargs,
) -> Union[str, Dict, None]:
"""(Abstract method) Generate a reply based on the received messages.
Args:
messages (list[dict]): a list of messages received.
sender: sender of an Agent instance.
Returns:
str or dict or None: the generated reply. If None, no reply is generated.
"""
```
### `a_generate_reply`
The `a_generate_reply` method is the asynchronous version of the `generate_reply` method. It
takes the same parameters as the `generate_reply` method.
```
async def a_generate_reply(
self,
messages: Optional[List[Dict]] = None,
sender: AbstractWorker,
**kwargs,
) -> Union[str, Dict, None]:
"""(Abstract async method) Generate a reply based on the received messages.
Args:
messages (list[dict]): a list of messages received.
sender: sender of an Agent instance.
Returns:
str or dict or None: the generated reply. If None, no reply is generated.
"""
```
Usage Examples
--------------
### Example 1: Creating an AbstractWorker
```
from swarms.worker.base import AbstractWorker
worker = AbstractWorker(name="Worker1")
print(worker.name) # Output: Worker1
```
In this example, we create an instance of `AbstractWorker` named "Worker1" and print its name.
### Example 2: Sending a Message
```
from swarms.worker.base import AbstractWorker
worker1 = AbstractWorker(name="Worker1")
worker2 = AbstractWorker(name="Worker2")
message = {"content": "Hello, Worker2!"}
worker1.send(message, worker2)
```
In this example, "Worker1" sends a message to "Worker2". The message is a dictionary with a single key-value pair.
### Example 3: Receiving a Message
```
from swarms.worker.base import AbstractWorker
worker1 = AbstractWorker(name="Worker1")
worker2 = AbstractWorker(name="Worker2")
message = {"content": "Hello, Worker2!"}
worker1.send(message, worker2)
received_message = worker2.receive(message, worker1)
print(received_message) # Output: {"content": "Hello, Worker2!"}
```
In this example, "Worker1" sends a message to "Worker2". "Worker2" then receives the message and prints it.
Notes
-----
- The `AbstractWorker` class is an abstract class, which means it cannot be instantiated directly. Instead, it should be subclassed, and at least the `send`, `receive`, `reset`, and `generate_reply` methods should be overridden.
- The `send` and `receive` methods are abstract methods, which means they must be implemented in any subclass of `AbstractWorker`.
- The `a_send`, `a_receive`, and `a_generate_reply` methods are asynchronous methods, which means they return a coroutine that can be awaited using the `await` keyword.
- The `generate_reply` method is used to generate a reply based on the received messages. The exact implementation of this method will depend on the specific requirements of your application.
- The `reset` method is used to reset the state of the worker. The exact implementation of this method will depend on the specific requirements of your application.

@ -1,403 +0,0 @@
# `AbstractWorker` Documentation
## Table of Contents
1. [Introduction](#introduction)
2. [Abstract Worker](#abstract-worker)
1. [Class Definition](#class-definition)
2. [Attributes](#attributes)
3. [Methods](#methods)
3. [Tutorial: Creating Custom Workers](#tutorial-creating-custom-workers)
4. [Conclusion](#conclusion)
---
## 1. Introduction <a name="introduction"></a>
Welcome to the documentation for the Swarms library, a powerful tool for building and simulating swarm architectures. This library provides a foundation for creating and managing autonomous workers that can communicate, collaborate, and perform various tasks in a coordinated manner.
In this documentation, we will cover the `AbstractWorker` class, which serves as the fundamental building block for creating custom workers in your swarm simulations. We will explain the class's architecture, attributes, and methods in detail, providing practical examples to help you understand how to use it effectively.
Whether you want to simulate a team of autonomous robots, a group of AI agents, or any other swarm-based system, the Swarms library is here to simplify the process and empower you to build complex simulations.
---
## 2. Abstract Worker <a name="abstract-worker"></a>
### 2.1 Class Definition <a name="class-definition"></a>
The `AbstractWorker` class is an abstract base class that serves as the foundation for creating worker agents in your swarm simulations. It defines a set of methods that should be implemented by subclasses to customize the behavior of individual workers.
Here is the class definition:
```python
class AbstractWorker:
def __init__(self, name: str):
"""
Args:
name (str): Name of the worker.
"""
@property
def name(self):
"""Get the name of the worker."""
def run(self, task: str):
"""Run the worker agent once."""
def send(
self, message: Union[Dict, str], recipient, request_reply: Optional[bool] = None
):
"""Send a message to another worker."""
async def a_send(
self, message: Union[Dict, str], recipient, request_reply: Optional[bool] = None
):
"""Send a message to another worker asynchronously."""
def receive(
self, message: Union[Dict, str], sender, request_reply: Optional[bool] = None
):
"""Receive a message from another worker."""
async def a_receive(
self, message: Union[Dict, str], sender, request_reply: Optional[bool] = None
):
"""Receive a message from another worker asynchronously."""
def reset(self):
"""Reset the worker."""
def generate_reply(
self, messages: Optional[List[Dict]] = None, sender=None, **kwargs
) -> Union[str, Dict, None]:
"""Generate a reply based on received messages."""
async def a_generate_reply(
self, messages: Optional[List[Dict]] = None, sender=None, **kwargs
) -> Union[str, Dict, None]:
"""Generate a reply based on received messages asynchronously."""
```
### 2.2 Attributes <a name="attributes"></a>
- `name (str)`: The name of the worker, which is set during initialization.
### 2.3 Methods <a name="methods"></a>
Now, let's delve into the methods provided by the `AbstractWorker` class and understand their purposes and usage.
#### `__init__(self, name: str)`
The constructor method initializes a worker with a given name.
**Parameters:**
- `name (str)`: The name of the worker.
**Usage Example:**
```python
worker = AbstractWorker("Worker1")
```
#### `name` (Property)
The `name` property allows you to access the name of the worker.
**Usage Example:**
```python
worker_name = worker.name
```
#### `run(self, task: str)`
The `run()` method is a placeholder for running the worker. You can customize this method in your subclass to define the specific actions the worker should perform.
**Parameters:**
- `task (str)`: A task description or identifier.
**Usage Example (Customized Subclass):**
```python
class MyWorker(AbstractWorker):
def run(self, task: str):
print(f"{self.name} is performing task: {task}")
worker = MyWorker("Worker1")
worker.run("Collect data")
```
#### `send(self, message: Union[Dict, str], recipient, request_reply: Optional[bool] = None)`
The `send()` method allows the worker to send a message to another worker or recipient. The message can be either a dictionary or a string.
**Parameters:**
- `message (Union[Dict, str])`: The message to be sent.
- `recipient`: The recipient worker or entity.
- `request_reply (Optional[bool])`: If `True`, the sender requests a reply from the recipient. If `False`, no reply is requested. Default is `None`.
**Usage Example:**
```python
worker1 = AbstractWorker("Worker1")
worker2 = AbstractWorker("Worker2")
message = "Hello, Worker2!"
worker1.send(message, worker2)
```
#### `a_send(self, message: Union[Dict, str], recipient, request_reply: Optional[bool] = None)`
The `a_send()` method is an asynchronous version of the `send()` method, allowing the worker to send messages asynchronously.
**Parameters:** (Same as `send()`)
**Usage Example:**
```python
import asyncio
async def main():
worker1 = AbstractWorker("Worker1")
worker2 = AbstractWorker("Worker2")
message = "Hello, Worker2!"
await worker1.a_send(message, worker2)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
```
#### `receive(self, message: Union[Dict, str], sender, request_reply: Optional[bool] = None)`
The `receive()` method allows the worker to receive messages from other workers or senders. You can customize this method in your subclass to define how the worker handles incoming messages.
**Parameters:**
- `message (Union[Dict, str])`: The received message.
- `sender`: The sender worker or entity.
- `request_reply (Optional[bool])`: Indicates whether a reply is requested. Default is `None`.
**Usage Example (Customized Subclass):**
```python
class MyWorker(AbstractWorker):
def receive(self, message: Union[Dict, str], sender, request_reply: Optional[bool] = None):
if isinstance(message, str):
print(f"{self.name} received a text message from {sender.name}: {message}")
elif isinstance(message, dict):
print(f"{self.name} received a dictionary message from {sender.name}: {message}")
worker1 = MyWorker("Worker1")
worker2 = MyWorker("Worker2")
message1 =
"Hello, Worker2!"
message2 = {"data": 42}
worker1.receive(message1, worker2)
worker1.receive(message2, worker2)
```
#### `a_receive(self, message: Union[Dict, str], sender, request_reply: Optional[bool] = None)`
The `a_receive()` method is an asynchronous version of the `receive()` method, allowing the worker to receive messages asynchronously.
**Parameters:** (Same as `receive()`)
**Usage Example:**
```python
import asyncio
async def main():
worker1 = AbstractWorker("Worker1")
worker2 = AbstractWorker("Worker2")
message1 = "Hello, Worker2!"
message2 = {"data": 42}
await worker1.a_receive(message1, worker2)
await worker1.a_receive(message2, worker2)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
```
#### `reset(self)`
The `reset()` method is a placeholder for resetting the worker. You can customize this method in your subclass to define how the worker should reset its state.
**Usage Example (Customized Subclass):**
```python
class MyWorker(AbstractWorker):
def reset(self):
print(f"{self.name} has been reset.")
worker = MyWorker("Worker1")
worker.reset()
```
#### `generate_reply(self, messages: Optional[List[Dict]] = None, sender=None, **kwargs) -> Union[str, Dict, None]`
The `generate_reply()` method is a placeholder for generating a reply based on received messages. You can customize this method in your subclass to define the logic for generating replies.
**Parameters:**
- `messages (Optional[List[Dict]])`: A list of received messages.
- `sender`: The sender of the reply.
- `kwargs`: Additional keyword arguments.
**Returns:**
- `Union[str, Dict, None]`: The generated reply. If `None`, no reply is generated.
**Usage Example (Customized Subclass):**
```python
class MyWorker(AbstractWorker):
def generate_reply(
self, messages: Optional[List[Dict]] = None, sender=None, **kwargs
) -> Union[str, Dict, None]:
if messages:
# Generate a reply based on received messages
return f"Received {len(messages)} messages from {sender.name}."
else:
return None
worker1 = MyWorker("Worker1")
worker2 = MyWorker("Worker2")
message = "Hello, Worker2!"
reply = worker2.generate_reply([message], worker1)
if reply:
print(f"{worker2.name} generated a reply: {reply}")
```
#### `a_generate_reply(self, messages: Optional[List[Dict]] = None, sender=None, **kwargs) -> Union[str, Dict, None]`
The `a_generate_reply()` method is an asynchronous version of the `generate_reply()` method, allowing the worker to generate replies asynchronously.
**Parameters:** (Same as `generate_reply()`)
**Returns:**
- `Union[str, Dict, None]`: The generated reply. If `None`, no reply is generated.
**Usage Example:**
```python
import asyncio
async def main():
worker1 = AbstractWorker("Worker1")
worker2 = AbstractWorker("Worker2")
message = "Hello, Worker2!"
reply = await worker2.a_generate_reply([message], worker1)
if reply:
print(f"{worker2.name} generated a reply: {reply}")
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
```
---
## 3. Tutorial: Creating Custom Workers <a name="tutorial-creating-custom-workers"></a>
In this tutorial, we will walk you through the process of creating custom workers by subclassing the `AbstractWorker` class. You can tailor these workers to perform specific tasks and communicate with other workers in your swarm simulations.
### Step 1: Create a Custom Worker Class
Start by creating a custom worker class that inherits from `AbstractWorker`. Define the `run()` and `receive()` methods to specify the behavior of your worker.
```python
class CustomWorker(AbstractWorker):
def run(self, task: str):
print(f"{self.name} is performing task: {task}")
def receive(
self, message: Union[Dict, str], sender, request_reply: Optional[bool] = None
):
if isinstance(message, str):
print(f"{self.name} received a text message from {sender.name}: {message}")
elif isinstance(message, dict):
print(
f"{self.name} received a dictionary message from {sender.name}: {message}"
)
```
### Step 2: Create Custom Worker Instances
Instantiate your custom worker instances and give them unique names.
```python
worker1 = CustomWorker("Worker1")
worker2 = CustomWorker("Worker2")
```
### Step 3: Run Custom Workers
Use the `run()` method to make your custom workers perform tasks.
```python
worker1.run("Collect data")
worker2.run("Process data")
```
### Step 4: Communicate Between Workers
Use the `send()` method to send messages between workers. You can customize the `receive()` method to define how your workers handle incoming messages.
```python
worker1.send("Hello, Worker2!", worker2)
worker2.send({"data": 42}, worker1)
# Output will show the messages received by the workers
```
### Step 5: Generate Replies
Customize the `generate_reply()` method to allow your workers to generate replies based on received messages.
```python
class CustomWorker(AbstractWorker):
def generate_reply(
self, messages: Optional[List[Dict]] = None, sender=None, **kwargs
) -> Union[str, Dict, None]:
if messages:
# Generate a reply based on received messages
return f"Received {len(messages)} messages from {sender.name}."
else:
return None
```
Now, your custom workers can generate replies to incoming messages.
```python
reply = worker2.generate_reply(["Hello, Worker2!"], worker1)
if reply:
print(f"{worker2.name} generated a reply: {reply}")
```
---
## 4. Conclusion <a name="conclusion"></a>
Congratulations! You've learned how to use the Swarms library to create and customize worker agents for swarm simulations. You can now build complex swarm architectures, simulate autonomous systems, and experiment with various communication and task allocation strategies.
Feel free to explore the Swarms library further and adapt it to your specific use cases. If you have any questions or need assistance, refer to the extensive documentation and resources available.
Happy swarming!

@ -1,248 +0,0 @@
# Module Name: Worker
The `Worker` class encapsulates the idea of a semi-autonomous agent that utilizes a large language model to execute tasks. The module provides a unified interface for AI-driven task execution while combining a series of tools and utilities. It sets up memory storage and retrieval mechanisms for contextual recall and offers an option for human involvement, making it a versatile and adaptive agent for diverse applications.
## **Class Definition**:
```python
class Worker:
```
### **Parameters**:
- `model_name` (str, default: "gpt-4"): Name of the language model.
- `openai_api_key` (str, Optional): API key for accessing OpenAI's models.
- `ai_name` (str, default: "Autobot Swarm Worker"): Name of the AI agent.
- `ai_role` (str, default: "Worker in a swarm"): Role description of the AI agent.
- `external_tools` (list, Optional): A list of external tool objects to be used.
- `human_in_the_loop` (bool, default: False): If set to `True`, it indicates that human intervention may be required.
- `temperature` (float, default: 0.5): Sampling temperature for the language model's output. Higher values make the output more random, and lower values make it more deterministic.
### **Methods**:
#### `__init__`:
Initializes the Worker class.
#### `setup_tools`:
Sets up the tools available to the worker. Default tools include reading and writing files, processing CSV data, querying websites, and taking human input. Additional tools can be appended through the `external_tools` parameter.
#### `setup_memory`:
Initializes memory systems using embeddings and a vector store for the worker.
#### `setup_agent`:
Sets up the primary agent using the initialized tools, memory, and language model.
#### `run`:
Executes a given task using the agent.
#### `__call__`:
Makes the Worker class callable. When an instance of the class is called, it will execute the provided task using the agent.
## **Usage Examples**:
### **Example 1**: Basic usage with default parameters:
```python
from swarms import Worker
from swarms.models import OpenAIChat
llm = OpenAIChat(
# enter your api key
openai_api_key="",
temperature=0.5,
)
node = Worker(
llm=llm,
ai_name="Optimus Prime",
openai_api_key="",
ai_role="Worker in a swarm",
external_tools=None,
human_in_the_loop=False,
temperature=0.5,
)
task = "What were the winning boston marathon times for the past 5 years (ending in 2022)? Generate a table of the year, name, country of origin, and times."
response = node.run(task)
print(response)
```
### **Example 2**: Usage with custom tools:
```python
import os
import interpreter
from swarms.agents.hf_agents import HFAgent
from swarms.agents.omni_modal_agent import OmniModalAgent
from swarms.models import OpenAIChat
from swarms.tools.autogpt import tool
from swarms.workers import Worker
# Initialize API Key
api_key = ""
# Initialize the language model,
# This model can be swapped out with Anthropic, ETC, Huggingface Models like Mistral, ETC
llm = OpenAIChat(
openai_api_key=api_key,
temperature=0.5,
)
# wrap a function with the tool decorator to make it a tool, then add docstrings for tool documentation
@tool
def hf_agent(task: str = None):
"""
An tool that uses an openai model to call and respond to a task by search for a model on huggingface
It first downloads the model then uses it.
Rules: Don't call this model for simple tasks like generating a summary, only call this tool for multi modal tasks like generating images, videos, speech, etc
"""
agent = HFAgent(model="text-davinci-003", api_key=api_key)
response = agent.run(task, text="¡Este es un API muy agradable!")
return response
# wrap a function with the tool decorator to make it a tool
@tool
def omni_agent(task: str = None):
"""
An tool that uses an openai Model to utilize and call huggingface models and guide them to perform a task.
Rules: Don't call this model for simple tasks like generating a summary, only call this tool for multi modal tasks like generating images, videos, speech
The following tasks are what this tool should be used for:
Tasks omni agent is good for:
--------------
document-question-answering
image-captioning
image-question-answering
image-segmentation
speech-to-text
summarization
text-classification
text-question-answering
translation
huggingface-tools/text-to-image
huggingface-tools/text-to-video
text-to-speech
huggingface-tools/text-download
huggingface-tools/image-transformation
"""
agent = OmniModalAgent(llm)
response = agent.run(task)
return response
# Code Interpreter
@tool
def compile(task: str):
"""
Open Interpreter lets LLMs run code (Python, Javascript, Shell, and more) locally.
You can chat with Open Interpreter through a ChatGPT-like interface in your terminal
by running $ interpreter after installing.
This provides a natural-language interface to your computer's general-purpose capabilities:
Create and edit photos, videos, PDFs, etc.
Control a Chrome browser to perform research
Plot, clean, and analyze large datasets
...etc.
⚠️ Note: You'll be asked to approve code before it's run.
Rules: Only use when given to generate code or an application of some kind
"""
task = interpreter.chat(task, return_messages=True)
interpreter.chat()
interpreter.reset(task)
os.environ["INTERPRETER_CLI_AUTO_RUN"] = True
os.environ["INTERPRETER_CLI_FAST_MODE"] = True
os.environ["INTERPRETER_CLI_DEBUG"] = True
# Append tools to an list
tools = [hf_agent, omni_agent, compile]
# Initialize a single Worker node with previously defined tools in addition to it's
# predefined tools
node = Worker(
llm=llm,
ai_name="Optimus Prime",
openai_api_key=api_key,
ai_role="Worker in a swarm",
external_tools=tools,
human_in_the_loop=False,
temperature=0.5,
)
# Specify task
task = "What were the winning boston marathon times for the past 5 years (ending in 2022)? Generate a table of the year, name, country of origin, and times."
# Run the node on the task
response = node.run(task)
# Print the response
print(response)
```
### **Example 3**: Usage with human in the loop:
```python
from swarms import Worker
from swarms.models import OpenAIChat
llm = OpenAIChat(
# enter your api key
openai_api_key="",
temperature=0.5,
)
node = Worker(
llm=llm,
ai_name="Optimus Prime",
openai_api_key="",
ai_role="Worker in a swarm",
external_tools=None,
human_in_the_loop=True,
temperature=0.5,
)
task = "What were the winning boston marathon times for the past 5 years (ending in 2022)? Generate a table of the year, name, country of origin, and times."
response = node.run(task)
print(response)
```
## **Mathematical Description**:
Conceptually, the `Worker` class can be seen as a function:
\[ W(t, M, K, T, H, \theta) \rightarrow R \]
Where:
- \( W \) = Worker function
- \( t \) = task to be performed
- \( M \) = Model (e.g., "gpt-4")
- \( K \) = OpenAI API key
- \( T \) = Set of Tools available
- \( H \) = Human involvement flag (True/False)
- \( \theta \) = Temperature parameter
- \( R \) = Result of the task
This mathematical abstraction provides a simple view of the `Worker` class's capability to transform a task input into a desired output using a combination of AI and toolsets.
## **Notes**:
The Worker class acts as a bridge between raw tasks and the tools & AI required to accomplish them. The setup ensures flexibility and versatility. The decorators used in the methods (e.g., log_decorator, error_decorator) emphasize the importance of logging, error handling, and performance measurement, essential for real-world applications.

@ -1,4 +1,3 @@
import requests
from PIL import Image
from transformers import AutoModelForVision2Seq, AutoProcessor

Loading…
Cancel
Save