Spaces:
Runtime error
Runtime error
File size: 11,937 Bytes
4962437 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 |
# Swarms Documentation
## ClassName
Swarms
## Purpose
The Swarms module provides a powerful framework for creating and managing swarms of autonomous agents to accomplish complex tasks. It consists of the `WorkerNode` and `BossNode` classes, along with the `LLM` utility class, which allow you to easily set up and run a swarm of agents to tackle any objective. The module is highly configurable and extensible, providing flexibility to accommodate various use cases.
## Usage example
```python
from swarms import Swarms
api_key = "your_openai_api_key"
# Initialize Swarms with your API key
swarm = Swarms(api_key=api_key)
# Define an objective
objective = "Please make a web GUI for using HTTP API server..."
# Run Swarms
result = swarm.run(objective)
print(result)
```
## Constructor
```python
def __init__(self, openai_api_key)
```
- `openai_api_key` (required): The API key for OpenAI's models.
## Methods
### run(objective)
Runs the swarm with the given objective by initializing the worker and boss nodes.
- `objective` (required): The objective or task to be accomplished by the swarm.
Returns the result of the swarm execution.
## Example Usage
```python
from swarms import Swarms
api_key = "your_openai_api_key"
# Initialize Swarms with your API key
swarm = Swarms(api_key=api_key)
# Define an objective
objective = "Please make a web GUI for using HTTP API server..."
# Run Swarms
result = swarm.run(objective)
print(result)
```
## WorkerNode
The `WorkerNode` class represents an autonomous agent instance that functions as a worker to accomplish complex tasks. It has the ability to search the internet, process and generate images, text, audio, and more.
### Constructor
```python
def __init__(self, llm, tools, vectorstore)
```
- `llm` (required): The language model used by the worker node.
- `tools` (required): A list of tools available to the worker node.
- `vectorstore` (required): The vector store used by the worker node.
### Methods
- `create_agent(ai_name, ai_role, human_in_the_loop, search_kwargs)`: Creates an agent within the worker node.
- `add_tool(tool)`: Adds a tool to the worker node.
- `run(prompt)`: Runs the worker node to complete a task specified by the prompt.
### Example Usage
```python
from swarms import worker_node
# Your OpenAI API key
api_key = "your_openai_api_key"
# Initialize a WorkerNode with your API key
node = worker_node(api_key)
# Define an objective
objective = "Please make a web GUI for using HTTP API server..."
# Run the task
task = node.run(objective)
print(task)
```
## BossNode
The `BossNode` class represents an agent responsible for creating and managing tasks for the worker agent(s). It interacts with the worker node(s) to delegate tasks and monitor their progress.
### Constructor
```python
def __init__(self, llm, vectorstore, agent_executor, max_iterations)
```
- `llm` (required): The language model used by the boss node.
- `vectorstore` (required): The vector store used by the boss node.
- `agent_executor` (required): The agent executor used to execute tasks.
- `max_iterations` (required): The maximum number of iterations for task execution.
### Methods
- `create_task(objective)`: Creates a task with the given objective.
- `execute_task(task)`: Executes the given task by interacting with the worker agent(s).
## LLM
The `LLM` class is a utility class that provides an interface to different language models (LLMs) such as OpenAI's ChatGPT and Hugging Face models. It is used to initialize the language model for the worker and boss nodes.
### Constructor
```python
def __init__(self, openai_api_key=None, hf_repo_id=None, hf_api_token=None, model_kwargs=None)
```
- `openai_api_key` (optional): The API key for OpenAI's models.
- `hf_repo_id` (optional): The repository ID for the Hugging Face model.
- `hf_api_token` (optional): The API token for the Hugging Face model.
- `model_kwargs` (optional): Additional keyword arguments to pass to the language model.
### Methods
- `run(prompt)`: Runs the language model with the given prompt and returns the generated response.
## Configuration
The Swarms module can be configured by modifying the following parameters:
### WorkerNode
- `llm_class`: The language model class to use for the worker node (default: `ChatOpenAI`).
- `temperature`: The temperature parameter for the language model (default: `0.5`).
### BossNode
- `llm_class`: The language model class to use for the boss node (default: `OpenAI`).
- `max_iterations`: The maximum number of iterations for task execution (default: `5`).
### LLM
- `openai_api_key`: The API key for OpenAI's models.
- `hf_repo_id`: The repository ID for the Hugging Face model.
- `hf_api_token`: The API token for the Hugging Face model.
- `model_kwargs`: Additional keyword arguments to pass to the language model.
## Tool Configuration
The Swarms module supports various tools that can be added to the worker node for performing specific tasks. The following tools are available:
- `DuckDuckGoSearchRun`: A tool for performing web searches.
- `WriteFileTool`: A tool for writing files.
- `ReadFileTool`: A tool for reading files.
- `process_csv`: A tool for processing CSV files.
- `WebpageQATool`: A tool for performing question answering using web pages.
Additional tools can be added by extending the functionality of the `Tool` class.
## Advanced Usage
For more advanced usage, you can customize the tools and parameters according to your specific requirements. The Swarms module provides flexibility and extensibility to accommodate various use cases.
For example, you can add your own custom tools by extending the `Tool` class and adding them to the worker node. You can also modify the prompt templates used by the boss node to customize the interaction between the boss and worker agents.
Please refer to the source code and documentation of the Swarms module for more details and examples.
## Conclusion
The Swarms module provides a powerful framework for creating and managing swarms of autonomous agents to accomplish complex tasks. With the `WorkerNode` and `BossNode` classes, along with the `LLM` utility class, you can easily set up and run a swarm of agents to tackle any objective. The module is highly configurable and extensible, allowing you to tailor it to your specific needs.
## LLM
### Purpose
The `LLM` class provides an interface to different language models (LLMs) such as OpenAI's ChatGPT and Hugging Face models. It allows you to initialize and run a language model with a given prompt and obtain the generated response.
### Systems Understanding
The `LLM` class takes an OpenAI API key or Hugging Face repository ID and API token as input. It uses these credentials to initialize the language model, either from OpenAI's models or from a specific Hugging Face repository. The language model can then be run with a prompt, and the generated response is returned.
### Usage Example
```python
from swarms import LLM
# Create an instance of LLM with OpenAI API key
llm_instance = LLM(openai_api_key="your_openai_key")
# Run the language model with a prompt
result = llm_instance.run("Who won the FIFA World Cup in 1998?")
print(result)
# Create an instance of LLM with Hugging Face repository ID and API token
llm_instance = LLM(hf_repo_id="google/flan-t5-xl", hf_api_token="your_hf_api_token")
# Run the language model with a prompt
result = llm_instance.run("Who won the FIFA World Cup in 1998?")
print(result)
```
### Constructor
```python
def __init__(self, openai_api_key: Optional[str] = None,
hf_repo_id: Optional[str] = None,
hf_api_token: Optional[str] = None,
model_kwargs: Optional[dict] = None)
```
- `openai_api_key` (optional): The API key for OpenAI's models.
- `hf_repo_id` (optional): The repository ID for the Hugging Face model.
- `hf_api_token` (optional): The API token for the Hugging Face model.
- `model_kwargs` (optional): Additional keyword arguments to pass to the language model.
### Methods
- `run(prompt: str) -> str`: Runs the language model with the given prompt and returns the generated response.
### Args
- `prompt` (str): The prompt to be passed to the language model.
### Returns
- `result` (str): The generated response from the language model.
## Conclusion
The `LLM` class provides a convenient way to initialize and run different language models using either OpenAI's API or Hugging Face models. By providing the necessary credentials and a prompt, you can obtain the generated response from the language model.
# `GooglePalm` class:
### Example 1: Using Dictionaries as Messages
```python
from google_palm import GooglePalm
# Initialize the GooglePalm instance
gp = GooglePalm(
client=your_client,
model_name="models/chat-bison-001",
temperature=0.7,
top_p=0.9,
top_k=10,
n=5
)
# Create some messages
messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Who won the world series in 2020?"},
]
# Generate a response
response = gp.generate(messages)
# Print the generated response
print(response)
```
### Example 2: Using BaseMessage and Its Subclasses as Messages
```python
from google_palm import GooglePalm
from langchain.schema.messages import SystemMessage, HumanMessage
# Initialize the GooglePalm instance
gp = GooglePalm(
client=your_client,
model_name="models/chat-bison-001",
temperature=0.7,
top_p=0.9,
top_k=10,
n=5
)
# Create some messages
messages = [
SystemMessage(content="You are a helpful assistant."),
HumanMessage(content="Who won the world series in 2020?"),
]
# Generate a response
response = gp.generate(messages)
# Print the generated response
print(response)
```
### Example 3: Using GooglePalm with Asynchronous Function
```python
import asyncio
from google_palm import GooglePalm
from langchain.schema.messages import SystemMessage, HumanMessage
# Initialize the GooglePalm instance
gp = GooglePalm(
client=your_client,
model_name="models/chat-bison-001",
temperature=0.7,
top_p=0.9,
top_k=10,
n=5
)
# Create some messages
messages = [
SystemMessage(content="You are a helpful assistant."),
HumanMessage(content="Who won the world series in 2020?"),
]
# Define an asynchronous function
async def generate_response():
response = await gp._agenerate(messages)
print(response)
# Run the asynchronous function
asyncio.run(generate_response())
```
Remember to replace `your_client` with an actual instance of your client. Also, ensure the `model_name` is the correct name of the model that you want to use.
The `temperature`, `top_p`, `top_k`, and `n` parameters control the randomness and diversity of the generated responses. You can adjust these parameters based on your application's requirements.
## `CodeInterpreter`:
```python
tool = CodeInterpreter("Code Interpreter", "A tool to interpret code and generate useful outputs.")
tool.run("Plot the bitcoin chart of 2023 YTD")
# Or with file inputs
tool.run("Analyze this dataset and plot something interesting about it.", ["examples/assets/iris.csv"])
```
To use the asynchronous version, simply replace `run` with `arun` and ensure your calling code is in an async context:
```python
import asyncio
tool = CodeInterpreter("Code Interpreter", "A tool to interpret code and generate useful outputs.")
asyncio.run(tool.arun("Plot the bitcoin chart of 2023 YTD"))
# Or with file inputs
asyncio.run(tool.arun("Analyze this dataset and plot something interesting about it.", ["examples/assets/iris.csv"]))
```
The `CodeInterpreter` class is a flexible tool that uses the `CodeInterpreterSession` from the `codeinterpreterapi` package to run the code interpretation and return the result. It provides both synchronous and asynchronous methods for convenience, and ensures that exceptions are handled gracefully. |