pull/498/head
Kye Gomez 7 months ago
parent 3c73261c7c
commit 978f41c245

@ -112,7 +112,7 @@ nav:
- Workflows: "swarms/structs/workflows.md"
- Multi-Agent Architectures: "swarms/structs/multi_agent_architectures.md"
- Reference:
- Overview: "swarms/framework_structure.md"
- Overview: "swarms/framework/reference.md.md"
- Models:
- How to Create A Custom Language Model: "swarms/models/custom_model.md"
- Models Available: "swarms/models/index.md"

@ -0,0 +1,127 @@
## Swarms Framework Conceptual Breakdown
The `swarms` framework is a sophisticated structure designed to orchestrate the collaborative work of multiple agents in a hierarchical manner. This breakdown provides a conceptual and visual representation of the framework, highlighting the interactions between models, tools, memory, agents, and swarms.
### Hierarchical Structure
The framework can be visualized as a multi-layered hierarchy:
1. **Models, Tools, Memory**: These form the foundational components that agents utilize to perform tasks.
2. **Agents**: Individual entities that encapsulate specific functionalities, utilizing models, tools, and memory.
3. **Swarm**: A collection of multiple agents working together in a coordinated manner.
4. **Structs**: High-level structures that organize and manage swarms, enabling complex workflows and interactions.
### Visual Representation
Below are visual graphs illustrating the hierarchical and tree structure of the `swarms` framework.
#### 1. Foundational Components: Models, Tools, Memory
```mermaid
graph TD;
Models --> Agents
Tools --> Agents
Memory --> Agents
subgraph Foundational_Components
Models
Tools
Memory
end
```
#### 2. Agents and Their Interactions
```mermaid
graph TD;
Agents --> Swarm
subgraph Agents_Collection
Agent1
Agent2
Agent3
end
subgraph Individual_Agents
Agent1 --> Models
Agent1 --> Tools
Agent1 --> Memory
Agent2 --> Models
Agent2 --> Tools
Agent2 --> Memory
Agent3 --> Models
Agent3 --> Tools
Agent3 --> Memory
end
```
#### 3. Multiple Agents Form a Swarm
```mermaid
graph TD;
Swarm1 --> Struct
Swarm2 --> Struct
Swarm3 --> Struct
subgraph Swarms_Collection
Swarm1
Swarm2
Swarm3
end
subgraph Individual_Swarms
Swarm1 --> Agent1
Swarm1 --> Agent2
Swarm1 --> Agent3
Swarm2 --> Agent4
Swarm2 --> Agent5
Swarm2 --> Agent6
Swarm3 --> Agent7
Swarm3 --> Agent8
Swarm3 --> Agent9
end
```
#### 4. Structs Organizing Multiple Swarms
```mermaid
graph TD;
Struct --> Swarms_Collection
subgraph High_Level_Structs
Struct1
Struct2
Struct3
end
subgraph Struct1
Swarm1
Swarm2
end
subgraph Struct2
Swarm3
end
subgraph Struct3
Swarm4
Swarm5
end
```
### Directory Breakdown
The directory structure of the `swarms` framework is organized to support its hierarchical architecture:
```sh
swarms/
├── agents/
├── artifacts/
├── marketplace/
├── memory/
├── models/
├── prompts/
├── schemas/
├── structs/
├── telemetry/
├── tools/
├── utils/
└── __init__.py
```
### Summary
The `swarms` framework is designed to facilitate complex multi-agent interactions through a structured and layered approach. By leveraging foundational components like models, tools, and memory, individual agents are empowered to perform specialized tasks. These agents are then coordinated within swarms to achieve collective goals, and swarms are managed within high-level structs to orchestrate sophisticated workflows.
This hierarchical design ensures scalability, flexibility, and robustness, making the `swarms` framework a powerful tool for various applications in AI, data analysis, optimization, and beyond.

@ -1,127 +0,0 @@
## Swarms Framework Conceptual Breakdown
The `swarms` framework is a sophisticated structure designed to orchestrate the collaborative work of multiple agents in a hierarchical manner. This breakdown provides a conceptual and visual representation of the framework, highlighting the interactions between models, tools, memory, agents, and swarms.
### Hierarchical Structure
The framework can be visualized as a multi-layered hierarchy:
1. **Models, Tools, Memory**: These form the foundational components that agents utilize to perform tasks.
2. **Agents**: Individual entities that encapsulate specific functionalities, utilizing models, tools, and memory.
3. **Swarm**: A collection of multiple agents working together in a coordinated manner.
4. **Structs**: High-level structures that organize and manage swarms, enabling complex workflows and interactions.
### Visual Representation
Below are visual graphs illustrating the hierarchical and tree structure of the `swarms` framework.
#### 1. Foundational Components: Models, Tools, Memory
```mermaid
graph TD;
Models --> Agents
Tools --> Agents
Memory --> Agents
subgraph Foundational_Components
Models
Tools
Memory
end
```
#### 2. Agents and Their Interactions
```mermaid
graph TD;
Agents --> Swarm
subgraph Agents_Collection
Agent1
Agent2
Agent3
end
subgraph Individual_Agents
Agent1 --> Models
Agent1 --> Tools
Agent1 --> Memory
Agent2 --> Models
Agent2 --> Tools
Agent2 --> Memory
Agent3 --> Models
Agent3 --> Tools
Agent3 --> Memory
end
```
#### 3. Multiple Agents Form a Swarm
```mermaid
graph TD;
Swarm1 --> Struct
Swarm2 --> Struct
Swarm3 --> Struct
subgraph Swarms_Collection
Swarm1
Swarm2
Swarm3
end
subgraph Individual_Swarms
Swarm1 --> Agent1
Swarm1 --> Agent2
Swarm1 --> Agent3
Swarm2 --> Agent4
Swarm2 --> Agent5
Swarm2 --> Agent6
Swarm3 --> Agent7
Swarm3 --> Agent8
Swarm3 --> Agent9
end
```
#### 4. Structs Organizing Multiple Swarms
```mermaid
graph TD;
Struct --> Swarms_Collection
subgraph High_Level_Structs
Struct1
Struct2
Struct3
end
subgraph Struct1
Swarm1
Swarm2
end
subgraph Struct2
Swarm3
end
subgraph Struct3
Swarm4
Swarm5
end
```
### Directory Breakdown
The directory structure of the `swarms` framework is organized to support its hierarchical architecture:
```sh
swarms/
├── agents/
├── artifacts/
├── marketplace/
├── memory/
├── models/
├── prompts/
├── schemas/
├── structs/
├── telemetry/
├── tools/
├── utils/
└── __init__.py
```
### Summary
The `swarms` framework is designed to facilitate complex multi-agent interactions through a structured and layered approach. By leveraging foundational components like models, tools, and memory, individual agents are empowered to perform specialized tasks. These agents are then coordinated within swarms to achieve collective goals, and swarms are managed within high-level structs to orchestrate sophisticated workflows.
This hierarchical design ensures scalability, flexibility, and robustness, making the `swarms` framework a powerful tool for various applications in AI, data analysis, optimization, and beyond.

File diff suppressed because it is too large Load Diff

@ -1,12 +1,7 @@
# `Agent` Documentation
## Overview
Swarm Agent is a powerful autonomous agent framework designed to connect Language Models (LLMs) with various tools and long-term memory. This framework provides the ability to ingest and process various types of documents such as PDFs, text files, Markdown files, JSON files, and more. The Swarm Agent offers a wide range of features to enhance the capabilities of LLMs and facilitate efficient task execution.
The `Agent` class is a Python module designed to facilitate interactions with a language model, particularly one that operates as an autonomous agent. This class is part of a larger framework aimed at creating conversational agents using advanced language models like GPT-3. It enables you to establish a conversational loop with the model, generate responses, collect feedback, and control the agent of the conversation.
In this documentation, you will learn how to use the `Agent` class effectively, its purpose, and how it can be integrated into your projects.
## Purpose
The `Agent` class serves several key purposes:
@ -18,146 +13,266 @@ The `Agent` class serves several key purposes:
4. **Retry Mechanism**: The class includes a retry mechanism that can be helpful if there are issues generating responses from the model. It attempts to generate a response multiple times before raising an error.
## Class Definition
The `Agent` class has the following constructor:
```python
class Agent:
def __init__(
self,
llm: Any,
max_loops: int = 5,
stopping_condition: Optional[Callable[[str], bool]] = None,
loop_interval: int = 1,
retry_attempts: int = 3,
retry_interval: int = 1,
interactive: bool = False,
**kwargs: Any,
):
```
### Parameters
- `llm` (Any): The language model with which you want to interact.
- `max_loops` (int): The maximum number of conversation loops. Default is 5.
- `stopping_condition` (Optional[Callable[[str], bool]]): A custom stopping condition function. Default is `None`.
- `loop_interval` (int): The time interval (in seconds) between conversation loops. Default is 1 second.
- `retry_attempts` (int): The number of retry attempts if response generation fails. Default is 3.
- `retry_interval` (int): The time interval (in seconds) between retry attempts. Default is 1 second.
- `interactive` (bool): Set to `True` if the conversation is interactive, meaning the user is involved. Default is `False`.
## Usage
The `Agent` class can be used to create a conversational loop with the language model. Here's how you can use it:
### `Agent` Attributes
| Attribute | Description |
|------------|-------------|
| `id` | A unique identifier for the agent instance. |
| `llm` | The language model instance used by the agent. |
| `template` | The template used for formatting responses. |
| `max_loops` | The maximum number of loops the agent can run. |
| `stopping_condition` | A callable function that determines when the agent should stop looping. |
| `loop_interval` | The interval (in seconds) between loops. |
| `retry_attempts` | The number of retry attempts for failed LLM calls. |
| `retry_interval` | The interval (in seconds) between retry attempts. |
| `return_history` | A boolean indicating whether the agent should return the conversation history. |
| `stopping_token` | A token that, when present in the response, stops the agent from looping. |
| `dynamic_loops` | A boolean indicating whether the agent should dynamically determine the number of loops. |
| `interactive` | A boolean indicating whether the agent should run in interactive mode. |
| `dashboard` | A boolean indicating whether the agent should display a dashboard. |
| `agent_name` | The name of the agent instance. |
| `agent_description` | A description of the agent instance. |
| `system_prompt` | The system prompt used to initialize the conversation. |
| `tools` | A list of callable functions representing tools the agent can use. |
| `dynamic_temperature_enabled` | A boolean indicating whether the agent should dynamically adjust the temperature of the LLM. |
| `sop` | The standard operating procedure for the agent. |
| `sop_list` | A list of strings representing the standard operating procedure. |
| `saved_state_path` | The file path for saving and loading the agent's state. |
| `autosave` | A boolean indicating whether the agent should automatically save its state. |
| `context_length` | The maximum length of the context window (in tokens) for the LLM. |
| `user_name` | The name used to represent the user in the conversation. |
| `self_healing_enabled` | A boolean indicating whether the agent should attempt to self-heal in case of errors. |
| `code_interpreter` | A boolean indicating whether the agent should interpret and execute code snippets. |
| `multi_modal` | A boolean indicating whether the agent should support multimodal inputs (e.g., text and images). |
| `pdf_path` | The file path of a PDF document to be ingested. |
| `list_of_pdf` | A list of file paths for PDF documents to be ingested. |
| `tokenizer` | An instance of a tokenizer used for token counting and management. |
| `long_term_memory` | An instance of a `BaseVectorDatabase` implementation for long-term memory management. |
| `preset_stopping_token` | A boolean indicating whether the agent should use a preset stopping token. |
| `traceback` | An object used for traceback handling. |
| `traceback_handlers` | A list of traceback handlers. |
| `streaming_on` | A boolean indicating whether the agent should stream its responses. |
| `docs` | A list of document paths or contents to be ingested. |
| `docs_folder` | The path to a folder containing documents to be ingested. |
| `verbose` | A boolean indicating whether the agent should print verbose output. |
| `parser` | A callable function used for parsing input data. |
| `best_of_n` | An integer indicating the number of best responses to generate (for sampling). |
| `callback` | A callable function to be called after each agent loop. |
| `metadata` | A dictionary containing metadata for the agent. |
| `callbacks` | A list of callable functions to be called during the agent's execution. |
| `logger_handler` | A handler for logging messages. |
| `search_algorithm` | A callable function representing the search algorithm for long-term memory retrieval. |
| `logs_to_filename` | The file path for logging agent activities. |
| `evaluator` | A callable function used for evaluating the agent's responses. |
| `output_json` | A boolean indicating whether the agent's output should be in JSON format. |
| `stopping_func` | A callable function used as a stopping condition for the agent. |
| `custom_loop_condition` | A callable function used as a custom loop condition for the agent. |
| `sentiment_threshold` | A float value representing the sentiment threshold for evaluating responses. |
| `custom_exit_command` | A string representing a custom command for exiting the agent's loop. |
| `sentiment_analyzer` | A callable function used for sentiment analysis on the agent's outputs. |
| `limit_tokens_from_string` | A callable function used for limiting the number of tokens in a string. |
| `custom_tools_prompt` | A callable function used for generating a custom prompt for tool usage. |
| `tool_schema` | A data structure representing the schema for the agent's tools. |
| `output_type` | A type representing the expected output type of the agent's responses. |
| `function_calling_type` | A string representing the type of function calling (e.g., "json"). |
| `output_cleaner` | A callable function used for cleaning the agent's output. |
| `function_calling_format_type` | A string representing the format type for function calling (e.g., "OpenAI"). |
| `list_base_models` | A list of base models used for generating tool schemas. |
| `metadata_output_type` | A string representing the output type for metadata. |
| `state_save_file_type` | A string representing the file type for saving the agent's state (e.g., "json", "yaml"). |
| `chain_of_thoughts` | A boolean indicating whether the agent should use the chain of thoughts technique. |
| `algorithm_of_thoughts` | A boolean indicating whether the agent should use the algorithm of thoughts technique. |
| `tree_of_thoughts` | A boolean indicating whether the agent should use the tree of thoughts technique. |
| `tool_choice` | A string representing the method for tool selection (e.g., "auto"). |
| `execute_tool` | A boolean indicating whether the agent should execute tools. |
| `rules` | A string representing the rules for the agent's behavior. |
| `planning` | A boolean indicating whether the agent should perform planning. |
| `planning_prompt` | A string representing the prompt for planning. |
| `device` | A string representing the device on which the agent should run. |
| `custom_planning_prompt` | A string representing a custom prompt for planning. |
| `memory_chunk_size` | An integer representing the maximum size of memory chunks for long-term memory retrieval. |
| `agent_ops_on` | A boolean indicating whether agent operations should be enabled. |
### `Agent` Methods
| Method | Description | Inputs | Usage Example |
|--------|-------------|--------|----------------|
| `run(task, img=None, *args, **kwargs)` | Runs the autonomous agent loop to complete the given task. | `task` (str): The task to be performed.<br>`img` (str, optional): Path to an image file, if the task involves image processing.<br>`*args`, `**kwargs`: Additional arguments to pass to the language model. | `response = agent.run("Generate a report on financial performance.")` |
| `__call__(task, img=None, *args, **kwargs)` | An alternative way to call the `run` method. | Same as `run`. | `response = agent("Generate a report on financial performance.")` |
| `parse_and_execute_tools(response, *args, **kwargs)` | Parses the agent's response and executes any tools mentioned in it. | `response` (str): The agent's response to be parsed.<br>`*args`, `**kwargs`: Additional arguments to pass to the tool execution. | `agent.parse_and_execute_tools(response)` |
| `long_term_memory_prompt(query, *args, **kwargs)` | Generates a prompt for querying the agent's long-term memory. | `query` (str): The query to search for in long-term memory.<br>`*args`, `**kwargs`: Additional arguments to pass to the long-term memory retrieval. | `memory_retrieval = agent.long_term_memory_prompt("financial performance")` |
| `add_memory(message)` | Adds a message to the agent's memory. | `message` (str): The message
## Features
- **Language Model Integration**: The Swarm Agent allows seamless integration with different language models, enabling users to leverage the power of state-of-the-art models.
- **Tool Integration**: The framework supports the integration of various tools, enabling the agent to perform a wide range of tasks, from code execution to data analysis and beyond.
- **Long-term Memory Management**: The Swarm Agent incorporates long-term memory management capabilities, allowing it to store and retrieve relevant information for effective decision-making and task execution.
- **Document Ingestion**: The agent can ingest and process various types of documents, including PDFs, text files, Markdown files, JSON files, and more, enabling it to extract relevant information for task completion.
- **Interactive Mode**: Users can interact with the agent in an interactive mode, enabling real-time communication and task execution.
- **Dashboard**: The framework provides a visual dashboard for monitoring the agent's performance and activities.
- **Dynamic Temperature Control**: The Swarm Agent supports dynamic temperature control, allowing for adjustments to the model's output diversity during task execution.
- **Autosave and State Management**: The agent can save its state automatically, enabling seamless resumption of tasks after interruptions or system restarts.
- **Self-Healing and Error Handling**: The framework incorporates self-healing and error-handling mechanisms to ensure robust and reliable operation.
- **Code Interpretation**: The agent can interpret and execute code snippets, expanding its capabilities for tasks involving programming or scripting.
- **Multimodal Support**: The framework supports multimodal inputs, enabling the agent to process and reason about various data types, such as text, images, and audio.
- **Tokenization and Token Management**: The Swarm Agent provides tokenization capabilities, enabling efficient management of token usage and context window truncation.
- **Sentiment Analysis**: The agent can perform sentiment analysis on its generated outputs, allowing for evaluation and adjustment of responses based on sentiment thresholds.
- **Output Filtering and Cleaning**: The framework supports output filtering and cleaning, ensuring that generated responses adhere to specific criteria or guidelines.
- **Asynchronous and Concurrent Execution**: The Swarm Agent supports asynchronous and concurrent task execution, enabling efficient parallelization and scaling of operations.
- **Planning and Reasoning**: The agent can engage in planning and reasoning processes, leveraging techniques such as algorithm of thoughts and chain of thoughts to enhance decision-making and task execution.
- **Agent Operations and Monitoring**: The framework provides integration with agent operations and monitoring tools, enabling real-time monitoring and management of the agent's activities.
## Getting Started
To get started with the Swarm Agent, follow these steps:
1. Install the required dependencies by running `pip install swarms`.
2. Import the necessary modules and classes from the `swarms` package.
3. Initialize an instance of the `Agent` class, providing the necessary configuration parameters such as the language model, system prompt, tools, and memory components.
4. Define the tasks you want the agent to perform and pass them to the `run()` method.
5. Optionally, customize the agent's behavior by adjusting parameters such as the maximum number of loops, stopping conditions, and tool integration.
Here's a basic example to illustrate the usage of the Swarm Agent:
```python
from swarms.models import OpenAIChat
from swarms.structs import Agent
agent = Agent(llm=my_language_model, max_loops=5)
# Initialize the language model
llm = OpenAIChat()
# Define a starting task or message
initial_task = "Generate a 10,000 word blog on health and wellness."
# Initialize the agent
agent = Agent(llm=llm, max_loops=3)
# Run the conversation loop
final_response = agent.run(initial_task)
# Run a task
response = agent.run("Generate a report on the financial performance of a company.")
print(response)
```
### Feedback
This example initializes an instance of the `Agent` class with an OpenAI language model and a maximum of 3 loops. The `run()` method is then called with a task to generate a report on financial performance, and the agent's response is printed.
You can collect feedback during the conversation using the `provide_feedback` method:
## Advanced Usage
```python
agent.provide_feedback(
"Generate an SOP for new sales employees on the best cold sales practices"
)
```
The Swarm Agent provides numerous advanced features and customization options. Here are a few examples of how to leverage these features:
### Stopping Condition
### Tool Integration
You can define a custom stopping condition using a function. For example, you can stop the conversation if the response contains the word "Stop":
To integrate tools with the Swarm Agent, you can pass a list of callable functions to the `tools` parameter when initializing the `Agent` instance. The agent will automatically convert these functions into an OpenAI function calling schema and make them available for use during task execution.
```python
from swarms.structs import Agent
from my_tools import tool_function_1, tool_function_2
def stop_when_repeats(response: str) -> bool:
return "Stop" in response.lower()
agent = Agent(llm=my_language_model, max_loops=5, stopping_condition=stop_when_repeats)
# Initialize the agent with tools
agent = Agent(llm=llm, max_loops=3, tools=[tool_function_1, tool_function_2])
```
### Retry Mechanism
### Long-term Memory Management
If the response generation fails, the class will retry up to the specified number of attempts:
The Swarm Agent supports integration with various vector databases for long-term memory management. You can pass an instance of a `BaseVectorDatabase` implementation to the `long_term_memory` parameter when initializing the `Agent`.
```python
agent = Agent(llm=my_language_model, max_loops=5, retry_attempts=3)
```
from swarms.structs import Agent
from swarms.memory.chroma import ChromaVectorDatabase
## Additional Information
# Initialize a vector database
vector_db = ChromaVectorDatabase(persist_directory="path/to/db")
- To save the conversation history to a file, you can use the `save` method.
# Initialize the agent with long-term memory
agent = Agent(llm=llm, max_loops=3, long_term_memory=vector_db)
```
- To load a previously saved conversation history, you can use the `load` method.
### Document Ingestion
- The class includes methods for bulk running conversations with multiple input sets.
The Swarm Agent can ingest various types of documents, such as PDFs, text files, Markdown files, and JSON files. You can pass a list of document paths or contents to the `docs` parameter when initializing the `Agent`.
## Examples
```python
from swarms.structs import Agent
# Initialize the agent with documents
agent = Agent(llm=llm, max_loops=3, docs=["path/to/doc1.pdf", "path/to/doc2.txt"])
```
Here are three usage examples:
### Interactive Mode
### Example 1: Simple Conversation
The Swarm Agent supports an interactive mode, where users can engage in real-time communication with the agent. To enable interactive mode, set the `interactive` parameter to `True` when initializing the `Agent`.
```python
# Select any Language model from the models folder
from swarms.models import Mistral, OpenAIChat
from swarms.structs import Agent
llm = Mistral()
# llm = OpenAIChat()
# Initialize the agent in interactive mode
agent = Agent(llm=llm, max_loops=3, interactive=True)
agent = Agent(llm=llm, max_loops=5)
# Define a starting task or message
initial_task = "Generate an long form analysis on the transformer model architecture."
# Run the conversation loop
final_response = agent.run(initial_task)
# Run the agent in interactive mode
agent.interactive_run()
```
### Example 2: Custom Stopping Condition
### Sentiment Analysis
The Swarm Agent can perform sentiment analysis on its generated outputs using a sentiment analyzer function. You can pass a callable function to the `sentiment_analyzer` parameter when initializing the `Agent`.
```python
from swarms.structs import Agent
from my_sentiment_analyzer import sentiment_analyzer_function
# Initialize the agent with a sentiment analyzer
agent = Agent(llm=llm, max_loops=3, sentiment_analyzer=sentiment_analyzer_function)
```
def stop_when_repeats(response: str) -> bool:
return "Stop" in response.lower()
## Documentation Examples
The Swarm Agent provides numerous examples and usage scenarios throughout the documentation. Here are a few examples to illustrate various features and functionalities:
agent = Agent(llm=llm, max_loops=5, stopping_condition=stop_when_repeats)
### Undo Functionality
```python
# Feature 2: Undo functionality
response = agent.run("Another task")
print(f"Response: {response}")
previous_state, message = agent.undo_last()
print(message)
```
### Example 3: Interactive Conversation
### Response Filtering
```python
from swarms.structs import Agent
# Feature 3: Response filtering
agent.add_response_filter("report")
response = agent.filtered_run("Generate a report on finance")
print(response)
```
agent = Agent(llm=llm, max_loops=5, interactive=True)
### Saving and Loading State
# Provide initial task
initial_task = "Rank and prioritize the following financial documents and cut out 30% of our expenses"
```python
# Save the agent state
agent.save_state('saved_flow.json')
# Run the conversation loop
final_response = agent.run(initial_task)
# Load the agent state
agent = Agent(llm=llm_instance, max_loops=5)
agent.load_state('saved_flow.json')
agent.run("Continue with the task")
```
## References and Resources
- [GitHub Repository](https://github.com/kyegomez/swarms)
### Async and Concurrent Execution
## Conclusion
```python
# Run a task concurrently
response = await agent.run_concurrent("Concurrent task")
print(response)
# Run multiple tasks concurrently
tasks = [
{"task": "Task 1"},
{"task": "Task 2", "img": "path/to/image.jpg"},
{"task": "Task 3", "custom_param": 42}
]
responses = agent.bulk_run(tasks)
print(responses)
```
The `Agent` class provides a powerful way to interact with language models in a conversational manner. By defining custom stopping conditions, collecting feedback, and controlling the agent of the conversation, you can create engaging and interactive applications that make use of advanced language models.
These examples demonstrate just a few of the many features and capabilities offered by the Swarm Agent framework. For more detailed information and additional examples, please refer to the comprehensive documentation provided within the codebase.

@ -1,78 +0,0 @@
import time
import uuid
from fastapi import FastAPI, HTTPException
from swarms import Agent, OpenAIChat
from swarms.schemas.assistants_api import (
AssistantRequest,
AssistantResponse,
)
# Create an instance of the FastAPI application
app = FastAPI(debug=True, title="Assistant API", version="1.0")
# In-memory store for assistants
assistants_db = {}
# Health check endpoint
@app.get("/v1/health")
def health():
return {"status": "healthy"}
# Create an agent endpoint
@app.post("/v1/agents")
def create_agent(request: AssistantRequest):
try:
# Example initialization, in practice, you'd pass in more parameters
agent = Agent(
agent_name=request.name,
agent_description=request.description,
system_prompt=request.instructions,
llm=OpenAIChat(),
max_loops="auto",
autosave=True,
verbose=True,
# long_term_memory=memory,
stopping_condition="finish",
temperature=request.temperature,
# output_type="json_object"
)
# Simulating running a task
task = ("What are the symptoms of COVID-19?",)
out = agent.run(task)
return {
"status": "Agent created and task run successfully",
"output": out,
}
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
# Create an assistant endpoint
@app.post("/v1/assistants", response_model=AssistantResponse)
def create_assistant(request: AssistantRequest):
assistant_id = str(uuid.uuid4())
assistant_data = request.dict()
assistant_data.update(
{
"id": assistant_id,
"object": "assistant",
"created_at": int(time.time()),
}
)
assistants_db[assistant_id] = assistant_data
return AssistantResponse(**assistant_data)
# Get assistant by ID endpoint
@app.get("/v1/assistants/{assistant_id}", response_model=AssistantResponse)
def get_assistant(assistant_id: str):
assistant = assistants_db.get(assistant_id)
if not assistant:
raise HTTPException(status_code=404, detail="Assistant not found")
return AssistantResponse(**assistant)
Loading…
Cancel
Save