From 7091518a342d98916c48c2e1964e6dddb9b316a0 Mon Sep 17 00:00:00 2001 From: Kye Gomez Date: Thu, 11 Jul 2024 16:58:02 -0700 Subject: [PATCH] [DOCS] --- CONTRIBUTING.md | 191 +++++++++------------------ README.md | 69 +++++++--- docs/mkdocs.yml | 3 + docs/swarms_platform/index.md | 122 +++++++++++++++++ docs/swarms_platform/prompts_api.md | 198 ++++++++++++++++++++++++++++ example.py | 4 +- multi_modal_example.py | 35 +++++ requirements.txt | 1 + swarms/structs/agent.py | 167 +++++++++++++++-------- 9 files changed, 589 insertions(+), 201 deletions(-) create mode 100644 docs/swarms_platform/index.md create mode 100644 docs/swarms_platform/prompts_api.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9c9a6c11..8242d437 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,155 +1,82 @@ # Contributing to Swarms 🛠️ -Thank you for your interest in contributing to Swarms! +Thank you for your interest in contributing to Swarms! This guide will help you get started with your contribution. -We are actively improving this library to reduce the amount of work you need to do to solve common computer vision problems. +## Essential Steps for Contributing -## Contribution Guidelines +### 1. Fork and Clone the Repository -We welcome contributions to: - -1. Add a new feature to the library (guidance below). -2. Improve our documentation and add examples to make it clear how to leverage the swarms library. -3. Report bugs and issues in the project. -4. Submit a request for a new feature. -5. Improve our test coverage. - -### Contributing Features ✨ - -Swarms is designed to provide modular building blocks to build scalable swarms of autonomous agents! - -Before you contribute a new feature, consider submitting an Issue to discuss the feature so the community can weigh in and assist. - -### Requirements: -- New class and or function Module with documentation in docstrings with error handling -- Tests using pytest in tests folder in the same module folder -- Documentation in the docs/swarms/module_name folder and then added into the mkdocs.yml - - -## How to Contribute Changes - -First, fork this repository to your own GitHub account. Click "fork" in the top corner of the `swarms` repository to get started: - -Then, run `git clone` to download the project code to your computer. - -Move to a new branch using the `git checkout` command: - -```bash -git checkout -b -``` - -The name you choose for your branch should describe the change you want to make (i.e. `line-counter-docs`). - -Make any changes you want to the project code, then run the following commands to commit your changes: - -```bash -git add . -git commit -m "Your commit message" -git push -u origin main -``` - -## 🎨 Code quality -- Follow the following guide on code quality a python guide or your PR will most likely be overlooked: [CLICK HERE](https://google.github.io/styleguide/pyguide.html) - - - -### Pre-commit tool - -This project utilizes the [pre-commit](https://pre-commit.com/) tool to maintain code quality and consistency. Before submitting a pull request or making any commits, it is important to run the pre-commit tool to ensure that your changes meet the project's guidelines. - - -- Install pre-commit (https://pre-commit.com/) - -```bash -pip install pre-commit -``` - -- Check that it's installed - -```bash -pre-commit --version -``` - -Now when you make a git commit, the black code formatter and ruff linter will run. - -Furthermore, we have integrated a pre-commit GitHub Action into our workflow. This means that with every pull request opened, the pre-commit checks will be automatically enforced, streamlining the code review process and ensuring that all contributions adhere to our quality standards. - -To run the pre-commit tool, follow these steps: - -1. Install pre-commit by running the following command: `poetry install`. It will not only install pre-commit but also install all the deps and dev-deps of project - -2. Once pre-commit is installed, navigate to the project's root directory. - -3. Run the command `pre-commit run --all-files`. This will execute the pre-commit hooks configured for this project against the modified files. If any issues are found, the pre-commit tool will provide feedback on how to resolve them. Make the necessary changes and re-run the pre-commit command until all issues are resolved. - -4. You can also install pre-commit as a git hook by execute `pre-commit install`. Every time you made `git commit` pre-commit run automatically for you. - - -### Docstrings - -All new functions and classes in `swarms` should include docstrings. This is a prerequisite for any new functions and classes to be added to the library. - -`swarms` adheres to the [Google Python docstring style](https://google.github.io/styleguide/pyguide.html#383-functions-and-methods). Please refer to the style guide while writing docstrings for your contribution. - -### Type checking - -Then, go back to your fork of the `swarms` repository, click "Pull Requests", and click "New Pull Request". - -Make sure the `base` branch is `develop` before submitting your PR. +1. Fork the Swarms repository to your GitHub account by clicking the "Fork" button in the top-right corner of the repository page. +2. Clone your forked repository to your local machine: + ``` + git clone https://github.com/kyegomez/swarms.git + ``` -On the next page, review your changes then click "Create pull request": +### 2. Make Changes -Next, write a description for your pull request, and click "Create pull request" again to submit it for review: +1. Create a new branch for your changes: + ``` + git checkout -b your-branch-name + ``` +2. Make your desired changes to the codebase. -When creating new functions, please ensure you have the following: +### 3. Commit and Push Changes -1. Docstrings for the function and all parameters. -2. Unit tests for the function. -3. Examples in the documentation for the function. -4. Created an entry in our docs to autogenerate the documentation for the function. -5. Please share a Google Colab with minimal code to test new feature or reproduce PR whenever it is possible. Please ensure that Google Colab can be accessed without any issue. +1. Stage your changes: + ``` + git add . + ``` +2. Commit your changes: + ``` + git commit -m "Your descriptive commit message" + ``` +3. Push your changes to your fork: + ``` + git push -u origin your-branch-name + ``` -All pull requests will be reviewed by the maintainers of the project. We will provide feedback and ask for changes if necessary. +### 4. Create a Pull Request -PRs must pass all tests and linting requirements before they can be merged. +1. Go to the original Swarms repository on GitHub. +2. Click on "Pull Requests" and then "New Pull Request". +3. Select your fork and branch as the compare branch. +4. Click "Create Pull Request". +5. Fill in the pull request description and submit. -## 📝 documentation +## Important Considerations -The `swarms` documentation is stored in a folder called `docs`. The project documentation is built using `mkdocs`. +- Ensure your code follows the project's coding standards. +- Include tests for new features or bug fixes. +- Update documentation as necessary. +- Make sure your branch is up-to-date with the main repository before submitting a pull request. -To run the documentation, install the project requirements with `poetry install dev`. Then, run `mkdocs serve` to start the documentation server. +## Additional Information -You can learn more about mkdocs on the [mkdocs website](https://www.mkdocs.org/). +### Code Quality -## 🧪 tests -- Run all the tests in the tests folder - ```pytest``` - -## Code Quality -`code-quality.sh` runs 4 different code formatters for ultra reliable code cleanup using Autopep8, Black, Ruff, YAPF -1. Open your terminal. +We use pre-commit hooks to maintain code quality. To set up pre-commit: -2. Change directory to where `code-quality.sh` is located using `cd` command: - ```sh - cd /path/to/directory +1. Install pre-commit: ``` - -3. Make sure the script has execute permissions: - ```sh - chmod +x code_quality.sh + pip install pre-commit ``` - -4. Run the script: - ```sh - ./code-quality.sh +2. Set up the git hook scripts: ``` - -If the script requires administrative privileges, you might need to run it with `sudo`: -```sh -sudo ./code-quality.sh -``` + pre-commit install + ``` + +### Documentation + +- We use mkdocs for documentation. To serve the docs locally: + ``` + mkdocs serve + ``` -Please replace `/path/to/directory` with the actual path where the `code-quality.sh` script is located on your system. +### Testing -If you're asking for a specific content or functionality inside `code-quality.sh` related to YAPF or other code quality tools, you would need to edit the `code-quality.sh` script to include the desired commands, such as running YAPF on a directory. The contents of `code-quality.sh` would dictate exactly what happens when you run it. +- Run tests using pytest: + ``` + pytest + ``` +For more detailed information on code quality, documentation, and testing, please refer to the full contributing guidelines in the repository. \ No newline at end of file diff --git a/README.md b/README.md index a6223b40..2d0582d1 100644 --- a/README.md +++ b/README.md @@ -125,7 +125,6 @@ agent.run( ``` ------ ### `Agent` + Long Term Memory `Agent` equipped with quasi-infinite long term memory. Great for long document understanding, analysis, and retrieval. @@ -172,7 +171,7 @@ agent.run("Generate a 10,000 word blog on health and wellness.") ``` ------ + ### `Agent` ++ Long Term Memory ++ Tools! An LLM equipped with long term memory and tools, a full stack agent capable of automating all and any digital tasks given a good prompt. @@ -285,7 +284,7 @@ out = agent("Create a new file for a plan to take over the world.") print(out) ``` ----- + ### Devin Implementation of Devin in less than 90 lines of code with several tools: @@ -391,7 +390,7 @@ agent = Agent( out = agent("Create a new file for a plan to take over the world.") print(out) ``` ---------------- + ### `Agent`with Pydantic BaseModel as Output Type The following is an example of an agent that intakes a pydantic basemodel and outputs it at the same time: @@ -454,28 +453,22 @@ print(f"Generated data: {generated_data}") ``` ------ ### Multi Modal Autonomous Agent Run the agent with multiple modalities useful for various real-world tasks in manufacturing, logistics, and health. ```python -# Description: This is an example of how to use the Agent class to run a multi-modal workflow import os - from dotenv import load_dotenv - from swarms import GPT4VisionAPI, Agent # Load the environment variables load_dotenv() -# Get the API key from the environment -api_key = os.environ.get("OPENAI_API_KEY") # Initialize the language model llm = GPT4VisionAPI( - openai_api_key=api_key, + openai_api_key=os.environ.get("OPENAI_API_KEY"), max_tokens=500, ) @@ -490,11 +483,16 @@ img = "assembly_line.jpg" ## Initialize the workflow agent = Agent( - llm=llm, max_loops="auto", autosave=True, dashboard=True, multi_modal=True + agent_name = "Multi-ModalAgent", + llm=llm, + max_loops="auto", + autosave=True, + dashboard=True, + multi_modal=True ) # Run the workflow on a task -agent.run(task=task, img=img) +agent.run(task, img) ``` ---- @@ -555,7 +553,7 @@ generated_data = agent.run(task) print(f"Generated data: {generated_data}") ``` ----------------- + ### `Task` For deeper control of your agent stack, `Task` is a simple structure for task execution with the `Agent`. Imagine zapier like LLM-based workflow automation. @@ -761,8 +759,49 @@ print(output) ## `HierarhicalSwarm` Coming soon... + ## `GraphSwarm` -Coming soon... + +```python +import os + +from dotenv import load_dotenv + +from swarms import Agent, Edge, GraphWorkflow, Node, NodeType, OpenAIChat + +load_dotenv() + +api_key = os.environ.get("OPENAI_API_KEY") + +llm = OpenAIChat( + temperature=0.5, openai_api_key=api_key, max_tokens=4000 +) +agent1 = Agent(llm=llm, max_loops=1, autosave=True, dashboard=True) +agent2 = Agent(llm=llm, max_loops=1, autosave=True, dashboard=True) + +def sample_task(): + print("Running sample task") + return "Task completed" + +wf_graph = GraphWorkflow() +wf_graph.add_node(Node(id="agent1", type=NodeType.AGENT, agent=agent1)) +wf_graph.add_node(Node(id="agent2", type=NodeType.AGENT, agent=agent2)) +wf_graph.add_node( + Node(id="task1", type=NodeType.TASK, callable=sample_task) +) +wf_graph.add_edge(Edge(source="agent1", target="task1")) +wf_graph.add_edge(Edge(source="agent2", target="task1")) + +wf_graph.set_entry_points(["agent1", "agent2"]) +wf_graph.set_end_points(["task1"]) + +print(wf_graph.visualize()) + +# Run the workflow +results = wf_graph.run() +print("Execution results:", results) + +``` ## `MixtureOfAgents` This is an implementation from the paper: "Mixture-of-Agents Enhances Large Language Model Capabilities" by together.ai, it achieves SOTA on AlpacaEval 2.0, MT-Bench and FLASK, surpassing GPT-4 Omni. Great for tasks that need to be parallelized and then sequentially fed into another loop diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml index 85f35aa8..911d7841 100644 --- a/docs/mkdocs.yml +++ b/docs/mkdocs.yml @@ -175,6 +175,9 @@ nav: # - Redis: "swarms_memory/redis.md" - Faiss: "swarms_memory/faiss.md" # - HNSW: "swarms_memory/hnsw.md" + - Swarms Platform: + - Overview: "swarms_platform/index.md" + - Prompts API: "swarms_platform/prompts_api.md" - References: - Agent Glossary: "swarms/glossary.md" - List of The Best Multi-Agent Papers: "swarms/papers.md" diff --git a/docs/swarms_platform/index.md b/docs/swarms_platform/index.md new file mode 100644 index 00000000..4347c639 --- /dev/null +++ b/docs/swarms_platform/index.md @@ -0,0 +1,122 @@ +# Swarms Platform Documentation + +Welcome to the Swarms Platform, a dynamic ecosystem where users can share, discover, and host agents and agent swarms. This documentation will guide you through the various features of the platform, providing you with the information you need to get started and make the most out of your experience. + +## Table of Contents + +1. [Introduction](#introduction) +2. [Getting Started](#getting-started) +3. [Account Management](#account-management) +4. [Usage Monitoring](#usage-monitoring) +5. [API Key Generation](#api-key-generation) +6. [Explorer](#explorer) +7. [Dashboard](#dashboard) +8. [Creating an Organization](#creating-an-organization) +9. [Additional Resources](#additional-resources) + +## Introduction + +The Swarms Platform is designed to facilitate the sharing, discovery, and hosting of intelligent agents and swarms of agents. Whether you are a developer looking to deploy your own agents, or an organization seeking to leverage collective intelligence, the Swarms Platform provides the tools and community support you need. + +## Getting Started + +To begin using the Swarms Platform, follow these steps: + +1. **Create an Account**: Sign up on the platform to access its features. +2. **Explore the Dashboard**: Familiarize yourself with the user interface and available functionalities. +3. **Generate API Keys**: Securely interact with the platform's API. +4. **Create and Join Organizations**: Collaborate with others to deploy and manage agents and swarms. +5. **Share and Discover**: Use the Explorer to find and share agents and swarms. + +## Account Management + +### Account Page + +Access and manage your account settings through the account page. + +- **URL**: [Account Page](https://swarms.world/platform/account) + +Here, you can update your profile information, manage security settings, and configure notifications. + +## Usage Monitoring + +### Check Your Usage + +Monitor your usage statistics to keep track of your activities and resource consumption on the platform. + +- **URL**: [Usage Monitoring](https://swarms.world/platform/usage) + +This page provides detailed insights into your usage patterns, helping you optimize your resource allocation and stay within your limits. + +## API Key Generation + +### Generate Your API Keys + +Generate API keys to securely interact with the Swarms Platform API. + +- **URL**: [API Key Generation](https://swarms.world/platform/api-keys) + +Follow the steps on this page to create, manage, and revoke API keys as needed. Ensure that your keys are kept secure and only share them with trusted applications. + +## Explorer + +### Explorer: Share, Discover, and Deploy + +The Explorer is a central hub for sharing, discovering, and deploying prompts, agents, and swarms. + +- **URL**: [Explorer](https://swarms.world/) + +Use the Explorer to: + +- **Share**: Upload and share your own prompts, agents, and swarms with the community. +- **Discover**: Browse and discover new and innovative agents and swarms created by others. +- **Deploy**: Quickly deploy agents and swarms for your own use or organizational needs. + +## Dashboard + +### Dashboard + +The Dashboard is your control center for managing all aspects of your Swarms Platform experience. + +- **URL**: [Dashboard](https://swarms.world/platform/dashboard) + +From the Dashboard, you can: + +- Monitor real-time metrics and analytics. +- Manage your agents and swarms. +- Access your account settings and usage information. +- Navigate to other sections of the platform. + +## Creating an Organization + +### Create an Organization + +Collaborate with others by creating and joining organizations on the Swarms Platform. + +- **URL**: [Create an Organization](https://swarms.world/platform/organization) + +Creating an organization allows you to: + +- Pool resources with team members. +- Manage shared agents and swarms. +- Set permissions and roles for organization members. + +## Additional Resources + +To further enhance your understanding and usage of the Swarms Platform, explore the following resources: + +- **API Documentation**: Comprehensive documentation on the platform's API. +- **Community Forums**: Engage with other users, share insights, and get support. +- **Tutorials and Guides**: Step-by-step tutorials to help you get started with specific features and use cases. +- **Support**: Contact the support team for any issues or inquiries. + +### Links + +- [API Documentation](https://docs.swarms.world) +- [Community Forums](https://discord.com/servers/agora-999382051935506503) +- [Tutorials and Guides](https://docs.swarms.world)) +- [Support](https://discord.com/servers/agora-999382051935506503) + +## Conclusion + +The Swarms Platform is a versatile and powerful ecosystem for managing intelligent agents and swarms. By following this documentation, you can effectively navigate the platform, leverage its features, and collaborate with others to create innovative solutions. Happy swarming! \ No newline at end of file diff --git a/docs/swarms_platform/prompts_api.md b/docs/swarms_platform/prompts_api.md new file mode 100644 index 00000000..7100fb38 --- /dev/null +++ b/docs/swarms_platform/prompts_api.md @@ -0,0 +1,198 @@ + +# Prompts API Documentation + +The `https://swarms.world/api/add-prompt` endpoint allows users to add a new prompt to the Swarms platform. This API accepts a POST request with a JSON body containing details of the prompt, such as its name, description, use cases, and tags. The request must be authenticated using an API key. + +## Endpoint + +- **URL:** `https://swarms.world/api/add-prompt` +- **Method:** POST +- **Content-Type:** `application/json` +- **Authorization:** Bearer token required in the header + +## Request Parameters + +The request body should be a JSON object with the following attributes: + +| Attribute | Type | Description | Required | +|-------------|----------|---------------------------------------------------------|----------| +| `name` | `string` | The name of the prompt. | Yes | +| `prompt` | `string` | The prompt text. | Yes | +| `description`| `string` | A brief description of the prompt. | Yes | +| `useCases` | `array` | An array of use cases, each containing a title and description. | Yes | +| `tags` | `string` | Comma-separated tags for the prompt. | No | + +### `useCases` Structure + +Each use case in the `useCases` array should be an object with the following attributes: + +| Attribute | Type | Description | Required | +|---------------|----------|---------------------------------|----------| +| `title` | `string` | The title of the use case. | Yes | +| `description` | `string` | A brief description of the use case. | Yes | + +## Example Usage + +### Python + +```python +import requests +import json + +url = "https://swarms.world/api/add-prompt" +headers = { + "Content-Type": "application/json", + "Authorization": "Bearer {apiKey}" +} +data = { + "name": "Example Prompt", + "prompt": "This is an example prompt from an API route.", + "description": "Description of the prompt.", + "useCases": [ + {"title": "Use case 1", "description": "Description of use case 1"}, + {"title": "Use case 2", "description": "Description of use case 2"} + ], + "tags": "example, prompt" +} + +response = requests.post(url, headers=headers, data=json.dumps(data)) +print(response.json()) +``` + +### Node.js + +```javascript +const fetch = require('node-fetch'); + +async function addPromptsHandler() { + try { + const response = await fetch('https://swarms.world/api/add-prompt', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Authorization': 'Bearer {apiKey}' + }, + body: JSON.stringify({ + name: 'Example Prompt', + prompt: 'This is an example prompt from an API route.', + description: 'Description of the prompt.', + useCases: [ + { title: 'Use case 1', description: 'Description of use case 1' }, + { title: 'Use case 2', description: 'Description of use case 2' } + ], + tags: 'example, prompt' + }) + }); + + const result = await response.json(); + console.log(result); + } catch (error) { + console.error('An error has occurred', error); + } +} + +addPromptsHandler(); +``` + +### Go + +```go +package main + +import ( + "bytes" + "encoding/json" + "fmt" + "net/http" +) + +func main() { + url := "https://swarms.world/api/add-prompt" + payload := map[string]interface{}{ + "name": "Example Prompt", + "prompt": "This is an example prompt from an API route.", + "description": "Description of the prompt.", + "useCases": []map[string]string{ + {"title": "Use case 1", "description": "Description of use case 1"}, + {"title": "Use case 2", "description": "Description of use case 2"}, + }, + "tags": "example, prompt", + } + jsonPayload, _ := json.Marshal(payload) + + req, _ := http.NewRequest("POST", url, bytes.NewBuffer(jsonPayload)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Authorization", "Bearer {apiKey}") + + client := &http.Client{} + resp, err := client.Do(req) + if err != nil { + fmt.Println("An error has occurred", err) + return + } + defer resp.Body.Close() + + var result map[string]interface{} + json.NewDecoder(resp.Body).Decode(&result) + fmt.Println(result) +} +``` + +### cURL + +```bash +curl -X POST https://swarms.world/api/add-prompt \ +-H "Content-Type: application/json" \ +-H "Authorization: Bearer {apiKey}" \ +-d '{ + "name": "Example Prompt", + "prompt": "This is an example prompt from an API route.", + "description": "Description of the prompt.", + "useCases": [ + { "title": "Use case 1", "description": "Description of use case 1" }, + { "title": "Use case 2", "description": "Description of use case 2" } + ], + "tags": "example, prompt" +}' +``` + +## Response + +The response will be a JSON object containing the result of the operation. Example response: + +```json +{ + "success": true, + "message": "Prompt added successfully", + "data": { + "id": "prompt_id", + "name": "Example Prompt", + "prompt": "This is an example prompt from an API route.", + "description": "Description of the prompt.", + "useCases": [ + { "title": "Use case 1", "description": "Description of use case 1" }, + { "title": "Use case 2", "description": "Description of use case 2" } + ], + "tags": "example, prompt" + } +} +``` + +In case of an error, the response will contain an error message detailing the issue. + +## Common Issues and Tips + +- **Authentication Error:** Ensure that the `Authorization` header is correctly set with a valid API key. +- **Invalid JSON:** Make sure the request body is a valid JSON object. +- **Missing Required Fields:** Ensure that all required fields (`name`, `prompt`, `description`, `useCases`) are included in the request body. +- **Network Issues:** Verify network connectivity and endpoint URL. + +## References and Resources + +- [API Authentication Guide](https://swarms.world/docs/authentication) +- [JSON Structure Standards](https://json.org/) +- [Fetch API Documentation (Node.js)](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) +- [Requests Library (Python)](https://requests.readthedocs.io/) +- [Net/HTTP Package (Go)](https://pkg.go.dev/net/http) + +This comprehensive documentation provides all the necessary information to effectively use the `https://swarms.world/api/add-prompt` endpoint, including details on request parameters, example code snippets in multiple programming languages, and troubleshooting tips. \ No newline at end of file diff --git a/example.py b/example.py index fc67a36e..cbd34051 100644 --- a/example.py +++ b/example.py @@ -1,11 +1,13 @@ from swarms import Agent, Anthropic +import os + # 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=Anthropic(), + llm=Anthropic(anthropic_api_key=os.getenv("ANTHROPIC_API_KEY")), max_loops="auto", autosave=True, # dynamic_temperature_enabled=True, diff --git a/multi_modal_example.py b/multi_modal_example.py index e69de29b..1235e7ac 100644 --- a/multi_modal_example.py +++ b/multi_modal_example.py @@ -0,0 +1,35 @@ +import os +from dotenv import load_dotenv +from swarms import GPT4VisionAPI, Agent + +# Load the environment variables +load_dotenv() + + +# Initialize the language model +llm = GPT4VisionAPI( + openai_api_key=os.environ.get("OPENAI_API_KEY"), + max_tokens=500, +) + +# Initialize the task +task = ( + "Analyze this image of an assembly line and identify any issues such as" + " misaligned parts, defects, or deviations from the standard assembly" + " process. IF there is anything unsafe in the image, explain why it is" + " unsafe and how it could be improved." +) +img = "assembly_line.jpg" + +## Initialize the workflow +agent = Agent( + agent_name="Multi-ModalAgent", + llm=llm, + max_loops="auto", + autosave=True, + dashboard=True, + multi_modal=True, +) + +# Run the workflow on a task +agent.run(task, img) diff --git a/requirements.txt b/requirements.txt index 22ba41f8..c153c5b0 100644 --- a/requirements.txt +++ b/requirements.txt @@ -30,3 +30,4 @@ pandas>=2.2.2 fastapi>=0.110.1 networkx swarms-memory +pre-commit \ No newline at end of file diff --git a/swarms/structs/agent.py b/swarms/structs/agent.py index 7204679f..0cd4f49c 100644 --- a/swarms/structs/agent.py +++ b/swarms/structs/agent.py @@ -258,6 +258,9 @@ class Agent(BaseStructure): custom_planning_prompt: str = None, memory_chunk_size: int = 2000, agent_ops_on: bool = False, + log_directory: str = None, + project_path: str = None, + tool_system_prompt: str = tool_sop_prompt(), *args, **kwargs, ): @@ -340,6 +343,9 @@ class Agent(BaseStructure): self.custom_tools_prompt = custom_tools_prompt self.memory_chunk_size = memory_chunk_size self.agent_ops_on = agent_ops_on + self.log_directory = log_directory + self.project_path = project_path + self.tool_system_prompt = tool_system_prompt # Name self.name = agent_name @@ -392,7 +398,9 @@ class Agent(BaseStructure): "Tools provided make sure the functions have documentation ++ type hints, otherwise tool execution won't be reliable." ) # Add the tool prompt to the memory - self.short_memory.add(role="System", content=tool_sop_prompt()) + self.short_memory.add( + role="Instructions", content=tool_system_prompt + ) # Log the tools logger.info(f"Tools provided: Accessing {len(tools)} tools") @@ -429,23 +437,8 @@ class Agent(BaseStructure): role=self.user_name, content=tool_schema_str ) - # If a list of tool schemas is provided - if exists(self.list_base_models): - logger.info( - "List of tool schemas provided, Automatically converting to OpenAI function" - ) - tool_schemas = multi_base_model_to_openai_function( - self.list_base_models - ) - - # Convert the tool schemas to a string - tool_schemas = json.dumps(tool_schemas, indent=4) - - # Add the tool schema to the short memory - logger.info("Adding tool schema to short memory") - self.short_memory.add( - role=self.user_name, content=tool_schemas - ) + # If multiple base models, then conver them. + self.handle_multiple_base_models() # If the algorithm of thoughts is enabled then set the sop to the algorithm of thoughts if self.algorithm_of_thoughts is not False: @@ -468,29 +461,8 @@ class Agent(BaseStructure): if exists(self.sop): self.short_memory.add(role=self.user_name, content=self.sop) - # If the device is not provided then get the device data - - # if agent ops is enabled then import agent ops - if agent_ops_on is True: - try: - from swarms.utils.agent_ops_check import ( - try_import_agentops, - ) - - # Try importing agent ops - logger.info( - "Agent Ops Initializing, ensure that you have the agentops API key and the pip package installed." - ) - try_import_agentops() - except ImportError: - logger.error( - "Could not import agentops, try installing agentops: $ pip3 install agentops" - ) - - # if tokenizer is None: - # self.tokenizer = TikTokenizer() - # else: - # self.tokenizer = None + # If agent_ops is on => activate agentops + self.activate_agentops() def set_system_prompt(self, system_prompt: str): """Set the system prompt""" @@ -789,17 +761,7 @@ class Agent(BaseStructure): # Check if tools is not None if self.tools is not None: - # self.parse_and_execute_tools(response) - tool_call_output = parse_and_execute_json( - self.tools, response, parse_md=True - ) - logger.info( - f"Tool Call Output: {tool_call_output}" - ) - self.short_memory.add( - role=self.agent_name, - content=tool_call_output, - ) + self.parse_function_call_and_execute(response) if self.code_interpreter is not False: self.code_interpreter_execution(response) @@ -1813,8 +1775,9 @@ class Agent(BaseStructure): self.short_memory.return_history_as_string() ) logger.info( - f"Tokens available: {tokens_used - self.context_length}" + f"Tokens available: {self.context_length - tokens_used}" ) + return tokens_used def tokens_checks(self): @@ -1899,3 +1862,101 @@ class Agent(BaseStructure): f"Tokens available: {tokens_used - self.context_length}" ) return input_string + + def parse_function_call_and_execute(self, response: str): + """ + Parses a function call from the given response and executes it. + + Args: + response (str): The response containing the function call. + + Returns: + None + + Raises: + Exception: If there is an error parsing and executing the function call. + """ + try: + if self.tools is not None: + tool_call_output = parse_and_execute_json( + self.tools, response, parse_md=True + ) + + if tool_call_output is not str: + tool_call_output = str(tool_call_output) + + logger.info(f"Tool Call Output: {tool_call_output}") + self.short_memory.add( + role=self.agent_name, + content=tool_call_output, + ) + + return tool_call_output + except Exception as error: + logger.error( + f"Error parsing and executing function call: {error}" + ) + print( + colored( + f"Error parsing and executing function call: {error}", + "red", + ) + ) + # Add better logging and extreme handling here + # Log the error with more details + logger.exception( + "An error occurred during parsing and executing function call" + ) + # Raise a custom exception with the error message + raise Exception( + "Error parsing and executing function call" + ) from error + + def activate_agentops(self): + if self.agent_ops_on is True: + try: + from swarms.utils.agent_ops_check import ( + try_import_agentops, + ) + + # Try importing agent ops + logger.info( + "Agent Ops Initializing, ensure that you have the agentops API key and the pip package installed." + ) + try_import_agentops() + + logger.info("Agentops successfully activated!") + except ImportError: + logger.error( + "Could not import agentops, try installing agentops: $ pip3 install agentops" + ) + + def handle_multiple_base_models(self) -> None: + try: + # If a list of tool schemas is provided + logger.info("Adding multiple base models as tools --->") + if exists(self.list_base_models): + logger.info( + "List of tool schemas provided, Automatically converting to OpenAI function" + ) + tool_schemas = multi_base_model_to_openai_function( + self.list_base_models + ) + + # Convert the tool schemas to a string + tool_schemas = json.dumps(tool_schemas, indent=4) + + # Add the tool schema to the short memory + logger.info("Adding tool schema to short memory") + self.short_memory.add( + role=self.user_name, content=tool_schemas + ) + + return logger.info( + "Successfully integrated multiple tools" + ) + except Exception as error: + logger.info( + f"Error with the base models, check the base model types and make sure they are initialized {error}" + ) + raise error