Name | CollabAgents JSON |
Version |
0.0.6
JSON |
| download |
home_page | None |
Summary | CollabAgents is a Python framework developed by Vishnu D. for developing AI agents equipped with specialized roles and tools to handle complex user requests efficiently. Users have 100 percent control over their prompts. |
upload_time | 2024-09-10 11:12:40 |
maintainer | None |
docs_url | None |
author | Vishnu.D |
requires_python | None |
license | MIT |
keywords |
pip install collabagents
pip install collabagents
|
VCS |
|
bugtrack_url |
|
requirements |
No requirements were recorded.
|
Travis-CI |
No Travis.
|
coveralls test coverage |
No coveralls.
|
# CollabAgents
<div style="text-align: center;">
<img src="https://i.postimg.cc/wTCWFxf4/logo.png" alt="logo.png" width="400"/>
</div>
## Overview:
CollabAgents is a versatile Python framework developed by Vishnu Durairaj, designed to facilitate the creation of intelligent AI agents equipped with a diverse range of tools and functionalities. This open-source framework simplifies the development of sophisticated AI systems capable of handling various tasks through role-based agents and supports advanced multi-agent orchestration.
## Features
- **Create AI Agents with Tools**: Easily build AI agents with a diverse set of tools, from Python execution to file operations and terminal commands.
- **Role-Based Agents**: Define agents with specific roles and responsibilities to handle different tasks and collaborate effectively.
- **Interacting Entities**: Simulate scenarios where multiple agents or companies work together to complete user requests.
- **Flexible Integration**: Supports both Anthropic and OpenAI models, providing flexibility in choosing the best AI model for your needs.
- **Memory Management**: Efficiently handle conversation history with various memory options:
- **ConversationBufferMemory**: Retains the entire conversation history. Use this when you need to maintain a complete record of all interactions without any summarization or truncation.
- **ConversationBufferWindowMemory**: Retains only the last K messages in the conversation. Ideal for scenarios where you want to limit memory usage and only keep the most recent interactions. (`memory = ConversationBufferWindowMemory(last_k=3)`)
- **ConversationSummaryMemory**: Automatically summarizes the conversation once it exceeds a specified number of messages. Use this to manage lengthy conversations by creating concise summaries while retaining overall context. (`memory = ConversationSummaryMemory(number_of_messages=5)`)
- **ConversationSummaryBufferMemory**: Combines summarization with selective message retention. Summarizes the conversation after a certain point and retains only the most recent N messages. Perfect for balancing context preservation with memory constraints by keeping key recent interactions while summarizing earlier ones. (`memory = ConversationSummaryBufferMemory(buffer_size=5)`)
## Colab Notebook
You can try out the notebook directly in Google Colab using the following link:
<a href="https://colab.research.google.com/drive/1cRVz-YS8Cf_GO-uTo0WUz5pLYTj_l4pn?usp=sharing" style="display: flex; align-items: center; text-decoration: none;">
<img src="https://colab.research.google.com/img/colab_favicon_256px.png" alt="Open in Google Colab" width="150"/>
</a>
## Installation
You can install the CollabAgents framework using pip:
```bash
pip install CollabAgents
```
## Example Use Case
### 1. Agents With Tools
Here’s an example of how to create a agent with tools using CollabAgents:
#### Step 1: Import Required Modules
```python
import os
import nest_asyncio
from CollabAgents.helper import print_colored
from CollabAgents.agent import StructuredAgent
from CollabAgents.models import OpenaiChatModel
from CollabAgents.memory import ConversationBufferMemory
from CollabAgents.tools.FileOperationsTool import SaveFile, CreateFolder
```
#### Step 2. If you are running this script in a notebook uncomment this
```python
# nest_asyncio.apply()
```
#### Step 3. Prepare Agent Description and Instructions
```python
# This concise description helps in understanding the agent's responsibilities and guides the system
# in determining what types of tasks should be assigned to this agent.
description = "Responsible for writing story."
# Provide instructions for the agent (System Prompt)
instruction = "You are a creative storyteller who crafts imaginative narratives with vivid details, rich characters, and unexpected plot twists."
```
#### Step 4: Load pre-defined tools that the agent will use
```python
# These tools enable the agent to create folders and save files
tools = [CreateFolder, SaveFile]
```
#### Step 5: Set your OpenAI API key
```python
openai_api_key = "Your API Key"
# openai_api_key = os.getenv('OPENAI_API_KEY')
```
#### Step 6: Initialize the large language model for the agent
```python
model = OpenaiChatModel(model_name="gpt-4o-mini", api_key=openai_api_key, temperature=0)
```
#### Step 7: Initialize memory - 4 different techniques are available.
```python
memory = ConversationBufferMemory()
# This option retains the entire conversation history.
# Use this when you need to maintain a complete record of all interactions without any summarization or truncation.
# memory = ConversationBufferWindowMemory(last_k=3)
# This option retains only the last K messages in the conversation.
# Ideal for scenarios where you want to limit memory usage and only keep the most recent interactions.
# memory = ConversationSummaryMemory(number_of_messages=5)
# This option automatically summarizes the conversation once it exceeds a specified number of messages.
# Use this to manage lengthy conversations by creating concise summaries while retaining overall context.
# memory = ConversationSummaryBufferMemory(buffer_size=5)
# This option combines summarization with selective message retention. It summarizes the conversation after a certain point and retains only the most recent N messages.
# Perfect for balancing context preservation with memory constraints by keeping key recent interactions while summarizing earlier ones.
```
#### Step 8: Initialize the agent with the model, description, instructions, and tools. Set verbose to True to see the steps by step actions.
```python
agent = StructuredAgent(model=model, agent_name="AI Assistant", agent_description=description, agent_instructions=instruction, tools=tools, assistant_agents=[],max_allowed_attempts=5, verbose=True,memory=memory)
```
#### Step 9: Start the conversation
```python
print_colored("Starting the application...........", "green")
# Example user input
# user_input = "Create a story about AI agents and save it in a new folder. The story should have two chapters, and each chapter should be saved separately inside the folder"
user_input = input("User : ")
# Initialize the messages list to store conversation history
messages = []
# Step 8: Process user input and interact with the agent
while user_input != "bye":
# The agent processes the user input and generates a response
output = agent.run(user_input, messages)
# Update the messages list with the agent's response
messages = agent.messages
# If verbose=False is set during agent initialization, uncomment the following line to see the agent's responses
# print_colored(f"Assistant : {output}", "purple")
# Prompt the user for the next input
user_input = input("User Input : ")
```
### 2. Creating Custom Tools
Here’s an example of how to create a custom tool using pydantic base model:
```python
import os
from typing import List
from pydantic import BaseModel,Field
class AppendToFile(BaseModel):
# Based on this docstring, the model will determine when to use this tool. Ensure it clearly describes the tool's purpose.
"""
Use this tool to append content to an existing file.
"""
# Provides justification for selecting this tool, helping to ensure it is chosen appropriately and not at random. You can ignore this.
reasoning :List[str] = Field(description="Why you are using this tool")
# Thses are the required argument with its data types clearly declared.
file_name: str = Field(..., description="File name to append to.")
content: str = Field(..., description="Content to append.")
# Every tool must include a `run` method. This method will be called dynamically during interactions to perform the tool's primary function.
def run(self):
try:
with open(self.file_name, "a") as file:
file.write(self.content)
return f"Content appended to file: {self.file_name}"
except Exception as e:
return f"An error occurred while appending to the file: {str(e)}"
AppendToFile(reasoning=["Thoughts"],file_name="path to the file",content="content to append").run()
```
### 3. Multi-Agents
Here’s an example of how to create multiple agents with tools using CollabAgents:
```python
import os,nest_asyncio
from CollabAgents.models import AnthropicModel
from CollabAgents.agent import StructuredAgent
from CollabAgents.tools.FileOperationsTool import CreateFolder,SaveFile,ListFilesInDirectory,ReadTextFile
from CollabAgents.memory import ConversationSummaryBufferMemory,ConversationSummaryMemory,ConversationBufferWindowMemory,ConversationBufferMemory
# If you are running this script in a notebook
# nest_asyncio.apply()
api_key = "Your API KEY"
model = AnthropicModel(model_name="claude-3-sonnet-20240229",api_key=api_key,temperature=0)
memory = ConversationBufferMemory()
# Let's Build a story writing company with 3 agents (CEO, Story Planner, Story Writer)
# ----------------------------------------------Create Story Planner Agent --------------------------------------
# Description for the Story Planner agent
Story_Planner_agent_description = (
"Responsible for creating the story outline and structure. "
"Works with the CEO to understand client requirements and plan the story accordingly."
)
# Instructions for the Story Planner agent
Story_Planner_instructions = (
"As the Story Planner, you will receive the client requirements from the CEO. "
"Create a detailed outline and structure for the story based on these requirements. "
"Save the story outline in the project folder created by the CEO. "
"Ensure that your plan is comprehensive and aligns with the client's vision. "
"Collaborate with the CEO and Story Writer as needed to ensure the story's structure is clear and achievable."
)
# Tools for Story Planner
story_planner_tools = [SaveFile]
story_planner = StructuredAgent(model,"Story Planner",Story_Planner_agent_description,Story_Planner_instructions,tools=story_planner_tools,max_allowed_attempts=20,memory=memory)
# ----------------------------------------------- Create Story Writer Agent ------------------------------------
# Description for the Story Writer agent
Story_Writer_agent_description = (
"Responsible for writing the story based on the outline provided by the Story Planner. "
"Ensures the final story meets client expectations and follows the planned structure."
)
# Instructions for the Story Writer agent
Story_Writer_instructions = (
"As the Story Writer, you will receive the story outline from the Story Planner, which is stored in the project folder created by the CEO. "
"Write the story based on this outline, ensuring it meets the client's requirements and follows the planned structure. "
"Save the completed story as a Markdown (.md) file in the same project folder. "
"Communicate with the CEO for feedback and any necessary revisions to ensure the final story aligns with client expectations."
)
# Tools for Story Writer
story_writter_tools = [ReadTextFile,SaveFile]
story_writter = StructuredAgent(model,"Story Writer",Story_Writer_agent_description,Story_Writer_instructions,tools=story_writter_tools,max_allowed_attempts=20,memory=memory)
# ------------------------------------------------ Create CEO Agent --------------------------------------------
# Description for the CEO agent
CEO_agent_description = (
"Responsible for client communication, task assignments, and coordination with other agents. "
"Creates a new folder for each project to organize story planning and writing, and ensures the final story is stored as a Markdown file."
)
# Instructions for the CEO agent
CEO_agent_instructions = (
"As the CEO of the Story Writing Company, you will manage client interactions and gather detailed requirements. "
"Create a new folder in the current directory for each project based on the client's requirements to keep all related files organized. "
"Delegate tasks to the Story Planner and Story Writer, instructing them to store their respective outputs (story plan and final story content) in the designated folder by providing the exact path. "
"Ensure that the final story is saved as a Markdown (.md) file in the project folder and coordinate with both agents to guarantee smooth progress and timely delivery."
)
# Tools for CEO
CEO_tools = [CreateFolder,ListFilesInDirectory]
CEO_agent = StructuredAgent(model,"CEO",CEO_agent_description,CEO_agent_instructions,tools=CEO_tools,assistant_agents=[story_planner,story_writter],max_allowed_attempts=10,memory=memory)
# Let's ask CEO agent to create a story about AI
if __name__ =="__main__":
# Example user input
# user_input = "Create a story about AI agents. keep 2 chapters and the tone should be horror"
user_input = input("User : ")
# Initialize the messages list to store conversation history
messages = []
# Step 7: Process user input and interact with the agent
while user_input != "bye":
# The agent processes the user input and generates a response
output = CEO_agent.run(user_input, messages)
# Update the messages list with the agent's response
messages = CEO_agent.messages
# If verbose=False is set during agent initialization, uncomment the following line to see the agent's responses
# print_colored(f"Assistant : {output}", "purple")
# Prompt the user for the next input
user_input = input("User Input : ")
```
### 4. Async Implementation
Here’s an example of async implementation:
```python
import os,nest_asyncio,asyncio
from CollabAgents.helper import print_colored
from CollabAgents.agent import StructuredAgent
from CollabAgents.models import OpenaiChatModel
from CollabAgents.tools.FileOperationsTool import SaveFile, CreateFolder
from CollabAgents.memory import ConversationSummaryBufferMemory,ConversationSummaryMemory,ConversationBufferWindowMemory,ConversationBufferMemory
# If you are running this script in a notebook
# nest_asyncio.apply()
# Step 1: This concise description helps in understanding the agent's responsibilities and guides the system
# in determining what types of tasks should be assigned to this agent.
description = "Responsible for writing story."
# Step 2: Provide instructions for the agent (System Prompt)
instruction = "You are a creative storyteller who crafts imaginative narratives with vivid details, rich characters, and unexpected plot twists."
# Step 3: Load pre-defined tools that the agent will use
# These tools enable the agent to create folders and save files
tools = [CreateFolder, SaveFile]
# Step 4: Set your OpenAI API key
openai_api_key = "Your API Key"
# openai_api_key = os.getenv('OPENAI_API_KEY')
# Step 5: Initialize the language model for the agent
model = OpenaiChatModel(model_name="gpt-4o-mini", api_key=openai_api_key, temperature=0)
# Step 6: Initialize memory - 4 different techniques are available.
# This option retains the entire conversation history.
# Use this when you need to maintain a complete record of all interactions without any summarization or truncation.
memory = ConversationBufferMemory()
# This option retains only the last K messages in the conversation.
# Ideal for scenarios where you want to limit memory usage and only keep the most recent interactions.
# memory = ConversationBufferWindowMemory(last_k=3)
# This option automatically summarizes the conversation once it exceeds a specified number of messages.
# Use this to manage lengthy conversations by creating concise summaries while retaining overall context.
# memory = ConversationSummaryMemory(number_of_messages=5)
# This option combines summarization with selective message retention. It summarizes the conversation after a certain point and retains only the most recent N messages.
# Perfect for balancing context preservation with memory constraints by keeping key recent interactions while summarizing earlier ones.
# memory = ConversationSummaryBufferMemory(buffer_size=5)
# Step 7: Initialize the agent with the model, description, instructions, and tools. Set verbose to True to see the steps by step actions.
agent = StructuredAgent(model=model, agent_name="AI Assistant", agent_description=description, agent_instructions=instruction, tools=tools, assistant_agents=[],max_allowed_attempts=50, verbose=True,memory=memory)
if __name__ =="__main__":
async def main():
print_colored("Starting the application...........", "green")
# Example user input
# user_input = "Create a story about AI agents and save it in a new folder. The story should have two chapters, and each chapter should be saved separately inside the folder"
user_input = input("User : ")
# Initialize the messages list to store conversation history
messages = []
# Step 8: Process user input and interact with the agent
while user_input != "bye":
# The agent processes the user input and generates a response
output = await agent.arun(user_input, messages)
# Update the messages list with the agent's response
messages = agent.messages
# If verbose=False is set during agent initialization, uncomment the following line to see the agent's responses
# print_colored(f"Assistant : {output}", "purple")
# Prompt the user for the next input
user_input = input("User Input : ")
asyncio.run(main())
```
## For More Tutorials Visit My:
<a href="https://www.youtube.com/@learnwithvichu" style="display: flex; align-items: center; text-decoration: none;">
<img src="https://img.shields.io/badge/YouTube-%23FF0000.svg?style=for-the-badge&logo=YouTube&logoColor=white" alt="YouTube Channel" width="150"/>
</a>
## Let's stay Connected:
<a href="https://www.linkedin.com/in/vishnu-d-121650167" style="display: flex; align-items: center; text-decoration: none;">
<img src="https://img.shields.io/badge/LinkedIn-%230077B5.svg?style=for-the-badge&logo=LinkedIn&logoColor=white" alt="LinkedIn Profile" width="150"/>
</a>
## License
This project is licensed under the MIT License. - see the LICENSE file for details.
Raw data
{
"_id": null,
"home_page": null,
"name": "CollabAgents",
"maintainer": null,
"docs_url": null,
"requires_python": null,
"maintainer_email": null,
"keywords": "pip install CollabAgents, pip install collabagents",
"author": "Vishnu.D",
"author_email": "vishnujune17@gmail.com",
"download_url": "https://files.pythonhosted.org/packages/41/de/816de8c2120237fe508931de5080a646357fa8354101eb9f9bb42655d5b6/collabagents-0.0.6.tar.gz",
"platform": null,
"description": "# CollabAgents\r\n\r\n<div style=\"text-align: center;\">\r\n <img src=\"https://i.postimg.cc/wTCWFxf4/logo.png\" alt=\"logo.png\" width=\"400\"/>\r\n</div>\r\n\r\n## Overview: \r\nCollabAgents is a versatile Python framework developed by Vishnu Durairaj, designed to facilitate the creation of intelligent AI agents equipped with a diverse range of tools and functionalities. This open-source framework simplifies the development of sophisticated AI systems capable of handling various tasks through role-based agents and supports advanced multi-agent orchestration.\r\n\r\n## Features\r\n\r\n- **Create AI Agents with Tools**: Easily build AI agents with a diverse set of tools, from Python execution to file operations and terminal commands.\r\n- **Role-Based Agents**: Define agents with specific roles and responsibilities to handle different tasks and collaborate effectively.\r\n- **Interacting Entities**: Simulate scenarios where multiple agents or companies work together to complete user requests.\r\n- **Flexible Integration**: Supports both Anthropic and OpenAI models, providing flexibility in choosing the best AI model for your needs.\r\n- **Memory Management**: Efficiently handle conversation history with various memory options:\r\n - **ConversationBufferMemory**: Retains the entire conversation history. Use this when you need to maintain a complete record of all interactions without any summarization or truncation.\r\n - **ConversationBufferWindowMemory**: Retains only the last K messages in the conversation. Ideal for scenarios where you want to limit memory usage and only keep the most recent interactions. (`memory = ConversationBufferWindowMemory(last_k=3)`)\r\n - **ConversationSummaryMemory**: Automatically summarizes the conversation once it exceeds a specified number of messages. Use this to manage lengthy conversations by creating concise summaries while retaining overall context. (`memory = ConversationSummaryMemory(number_of_messages=5)`)\r\n - **ConversationSummaryBufferMemory**: Combines summarization with selective message retention. Summarizes the conversation after a certain point and retains only the most recent N messages. Perfect for balancing context preservation with memory constraints by keeping key recent interactions while summarizing earlier ones. (`memory = ConversationSummaryBufferMemory(buffer_size=5)`)\r\n\r\n\r\n## Colab Notebook\r\n\r\nYou can try out the notebook directly in Google Colab using the following link:\r\n\r\n<a href=\"https://colab.research.google.com/drive/1cRVz-YS8Cf_GO-uTo0WUz5pLYTj_l4pn?usp=sharing\" style=\"display: flex; align-items: center; text-decoration: none;\">\r\n <img src=\"https://colab.research.google.com/img/colab_favicon_256px.png\" alt=\"Open in Google Colab\" width=\"150\"/>\r\n</a>\r\n\r\n\r\n## Installation\r\n\r\nYou can install the CollabAgents framework using pip:\r\n\r\n```bash\r\n\r\npip install CollabAgents\r\n\r\n```\r\n\r\n\r\n\r\n## Example Use Case\r\n\r\n### 1. Agents With Tools\r\n\r\nHere\u2019s an example of how to create a agent with tools using CollabAgents:\r\n\r\n#### Step 1: Import Required Modules\r\n\r\n```python\r\nimport os\r\nimport nest_asyncio\r\nfrom CollabAgents.helper import print_colored\r\nfrom CollabAgents.agent import StructuredAgent\r\nfrom CollabAgents.models import OpenaiChatModel\r\nfrom CollabAgents.memory import ConversationBufferMemory\r\nfrom CollabAgents.tools.FileOperationsTool import SaveFile, CreateFolder\r\n```\r\n\r\n#### Step 2. If you are running this script in a notebook uncomment this\r\n\r\n```python\r\n# nest_asyncio.apply()\r\n```\r\n\r\n#### Step 3. Prepare Agent Description and Instructions\r\n```python\r\n# This concise description helps in understanding the agent's responsibilities and guides the system \r\n# in determining what types of tasks should be assigned to this agent. \r\ndescription = \"Responsible for writing story.\"\r\n\r\n# Provide instructions for the agent (System Prompt)\r\ninstruction = \"You are a creative storyteller who crafts imaginative narratives with vivid details, rich characters, and unexpected plot twists.\"\r\n```\r\n\r\n#### Step 4: Load pre-defined tools that the agent will use\r\n```python\r\n# These tools enable the agent to create folders and save files\r\ntools = [CreateFolder, SaveFile]\r\n```\r\n\r\n#### Step 5: Set your OpenAI API key\r\n```python\r\nopenai_api_key = \"Your API Key\"\r\n# openai_api_key = os.getenv('OPENAI_API_KEY')\r\n```\r\n\r\n#### Step 6: Initialize the large language model for the agent\r\n```python\r\nmodel = OpenaiChatModel(model_name=\"gpt-4o-mini\", api_key=openai_api_key, temperature=0)\r\n```\r\n\r\n#### Step 7: Initialize memory - 4 different techniques are available.\r\n```python\r\n\r\nmemory = ConversationBufferMemory() \r\n# This option retains the entire conversation history. \r\n# Use this when you need to maintain a complete record of all interactions without any summarization or truncation.\r\n\r\n# memory = ConversationBufferWindowMemory(last_k=3) \r\n# This option retains only the last K messages in the conversation.\r\n# Ideal for scenarios where you want to limit memory usage and only keep the most recent interactions.\r\n\r\n# memory = ConversationSummaryMemory(number_of_messages=5) \r\n# This option automatically summarizes the conversation once it exceeds a specified number of messages.\r\n# Use this to manage lengthy conversations by creating concise summaries while retaining overall context.\r\n\r\n# memory = ConversationSummaryBufferMemory(buffer_size=5) \r\n# This option combines summarization with selective message retention. It summarizes the conversation after a certain point and retains only the most recent N messages.\r\n# Perfect for balancing context preservation with memory constraints by keeping key recent interactions while summarizing earlier ones.\r\n```\r\n\r\n#### Step 8: Initialize the agent with the model, description, instructions, and tools. Set verbose to True to see the steps by step actions.\r\n```python\r\nagent = StructuredAgent(model=model, agent_name=\"AI Assistant\", agent_description=description, agent_instructions=instruction, tools=tools, assistant_agents=[],max_allowed_attempts=5, verbose=True,memory=memory)\r\n```\r\n\r\n#### Step 9: Start the conversation\r\n\r\n```python\r\n\r\nprint_colored(\"Starting the application...........\", \"green\")\r\n\r\n# Example user input\r\n# user_input = \"Create a story about AI agents and save it in a new folder. The story should have two chapters, and each chapter should be saved separately inside the folder\"\r\n\r\nuser_input = input(\"User : \")\r\n\r\n# Initialize the messages list to store conversation history\r\nmessages = []\r\n\r\n# Step 8: Process user input and interact with the agent\r\nwhile user_input != \"bye\":\r\n # The agent processes the user input and generates a response\r\n output = agent.run(user_input, messages)\r\n\r\n # Update the messages list with the agent's response\r\n messages = agent.messages\r\n\r\n # If verbose=False is set during agent initialization, uncomment the following line to see the agent's responses\r\n # print_colored(f\"Assistant : {output}\", \"purple\")\r\n\r\n # Prompt the user for the next input\r\n user_input = input(\"User Input : \")\r\n\r\n```\r\n\r\n### 2. Creating Custom Tools\r\n\r\nHere\u2019s an example of how to create a custom tool using pydantic base model:\r\n\r\n```python\r\nimport os\r\nfrom typing import List\r\nfrom pydantic import BaseModel,Field\r\n\r\nclass AppendToFile(BaseModel):\r\n # Based on this docstring, the model will determine when to use this tool. Ensure it clearly describes the tool's purpose.\r\n \"\"\"\r\n Use this tool to append content to an existing file.\r\n \"\"\"\r\n # Provides justification for selecting this tool, helping to ensure it is chosen appropriately and not at random. You can ignore this.\r\n reasoning :List[str] = Field(description=\"Why you are using this tool\")\r\n\r\n # Thses are the required argument with its data types clearly declared.\r\n file_name: str = Field(..., description=\"File name to append to.\") \r\n content: str = Field(..., description=\"Content to append.\")\r\n\r\n # Every tool must include a `run` method. This method will be called dynamically during interactions to perform the tool's primary function.\r\n def run(self):\r\n try:\r\n with open(self.file_name, \"a\") as file:\r\n file.write(self.content)\r\n return f\"Content appended to file: {self.file_name}\"\r\n except Exception as e:\r\n return f\"An error occurred while appending to the file: {str(e)}\"\r\n \r\nAppendToFile(reasoning=[\"Thoughts\"],file_name=\"path to the file\",content=\"content to append\").run()\r\n\r\n```\r\n### 3. Multi-Agents\r\n\r\nHere\u2019s an example of how to create multiple agents with tools using CollabAgents:\r\n\r\n```python\r\n\r\nimport os,nest_asyncio\r\nfrom CollabAgents.models import AnthropicModel\r\nfrom CollabAgents.agent import StructuredAgent\r\nfrom CollabAgents.tools.FileOperationsTool import CreateFolder,SaveFile,ListFilesInDirectory,ReadTextFile\r\nfrom CollabAgents.memory import ConversationSummaryBufferMemory,ConversationSummaryMemory,ConversationBufferWindowMemory,ConversationBufferMemory\r\n\r\n# If you are running this script in a notebook\r\n# nest_asyncio.apply()\r\n\r\napi_key = \"Your API KEY\"\r\n\r\nmodel = AnthropicModel(model_name=\"claude-3-sonnet-20240229\",api_key=api_key,temperature=0)\r\n\r\nmemory = ConversationBufferMemory() \r\n\r\n# Let's Build a story writing company with 3 agents (CEO, Story Planner, Story Writer)\r\n\r\n# ----------------------------------------------Create Story Planner Agent --------------------------------------\r\n\r\n# Description for the Story Planner agent\r\nStory_Planner_agent_description = (\r\n \"Responsible for creating the story outline and structure. \"\r\n \"Works with the CEO to understand client requirements and plan the story accordingly.\"\r\n)\r\n\r\n# Instructions for the Story Planner agent\r\nStory_Planner_instructions = (\r\n \"As the Story Planner, you will receive the client requirements from the CEO. \"\r\n \"Create a detailed outline and structure for the story based on these requirements. \"\r\n \"Save the story outline in the project folder created by the CEO. \"\r\n \"Ensure that your plan is comprehensive and aligns with the client's vision. \"\r\n \"Collaborate with the CEO and Story Writer as needed to ensure the story's structure is clear and achievable.\"\r\n)\r\n\r\n# Tools for Story Planner\r\n\r\nstory_planner_tools = [SaveFile]\r\n\r\nstory_planner = StructuredAgent(model,\"Story Planner\",Story_Planner_agent_description,Story_Planner_instructions,tools=story_planner_tools,max_allowed_attempts=20,memory=memory)\r\n\r\n# ----------------------------------------------- Create Story Writer Agent ------------------------------------\r\n\r\n# Description for the Story Writer agent\r\nStory_Writer_agent_description = (\r\n \"Responsible for writing the story based on the outline provided by the Story Planner. \"\r\n \"Ensures the final story meets client expectations and follows the planned structure.\"\r\n)\r\n\r\n# Instructions for the Story Writer agent\r\nStory_Writer_instructions = (\r\n \"As the Story Writer, you will receive the story outline from the Story Planner, which is stored in the project folder created by the CEO. \"\r\n \"Write the story based on this outline, ensuring it meets the client's requirements and follows the planned structure. \"\r\n \"Save the completed story as a Markdown (.md) file in the same project folder. \"\r\n \"Communicate with the CEO for feedback and any necessary revisions to ensure the final story aligns with client expectations.\"\r\n)\r\n\r\n# Tools for Story Writer\r\nstory_writter_tools = [ReadTextFile,SaveFile]\r\n\r\nstory_writter = StructuredAgent(model,\"Story Writer\",Story_Writer_agent_description,Story_Writer_instructions,tools=story_writter_tools,max_allowed_attempts=20,memory=memory)\r\n\r\n# ------------------------------------------------ Create CEO Agent --------------------------------------------\r\n\r\n# Description for the CEO agent\r\nCEO_agent_description = (\r\n \"Responsible for client communication, task assignments, and coordination with other agents. \"\r\n \"Creates a new folder for each project to organize story planning and writing, and ensures the final story is stored as a Markdown file.\"\r\n)\r\n\r\n# Instructions for the CEO agent\r\nCEO_agent_instructions = (\r\n \"As the CEO of the Story Writing Company, you will manage client interactions and gather detailed requirements. \"\r\n \"Create a new folder in the current directory for each project based on the client's requirements to keep all related files organized. \"\r\n \"Delegate tasks to the Story Planner and Story Writer, instructing them to store their respective outputs (story plan and final story content) in the designated folder by providing the exact path. \"\r\n \"Ensure that the final story is saved as a Markdown (.md) file in the project folder and coordinate with both agents to guarantee smooth progress and timely delivery.\"\r\n)\r\n\r\n# Tools for CEO\r\nCEO_tools = [CreateFolder,ListFilesInDirectory]\r\n\r\nCEO_agent = StructuredAgent(model,\"CEO\",CEO_agent_description,CEO_agent_instructions,tools=CEO_tools,assistant_agents=[story_planner,story_writter],max_allowed_attempts=10,memory=memory)\r\n\r\n# Let's ask CEO agent to create a story about AI\r\n\r\nif __name__ ==\"__main__\":\r\n\r\n # Example user input\r\n # user_input = \"Create a story about AI agents. keep 2 chapters and the tone should be horror\"\r\n\r\n user_input = input(\"User : \")\r\n\r\n # Initialize the messages list to store conversation history\r\n messages = []\r\n\r\n # Step 7: Process user input and interact with the agent\r\n while user_input != \"bye\":\r\n # The agent processes the user input and generates a response\r\n output = CEO_agent.run(user_input, messages)\r\n\r\n # Update the messages list with the agent's response\r\n messages = CEO_agent.messages\r\n\r\n # If verbose=False is set during agent initialization, uncomment the following line to see the agent's responses\r\n # print_colored(f\"Assistant : {output}\", \"purple\")\r\n\r\n # Prompt the user for the next input\r\n user_input = input(\"User Input : \")\r\n\r\n```\r\n\r\n### 4. Async Implementation\r\n\r\nHere\u2019s an example of async implementation:\r\n\r\n```python\r\nimport os,nest_asyncio,asyncio\r\nfrom CollabAgents.helper import print_colored\r\nfrom CollabAgents.agent import StructuredAgent\r\nfrom CollabAgents.models import OpenaiChatModel\r\nfrom CollabAgents.tools.FileOperationsTool import SaveFile, CreateFolder\r\nfrom CollabAgents.memory import ConversationSummaryBufferMemory,ConversationSummaryMemory,ConversationBufferWindowMemory,ConversationBufferMemory\r\n\r\n# If you are running this script in a notebook\r\n# nest_asyncio.apply()\r\n\r\n# Step 1: This concise description helps in understanding the agent's responsibilities and guides the system \r\n# in determining what types of tasks should be assigned to this agent. \r\ndescription = \"Responsible for writing story.\"\r\n\r\n# Step 2: Provide instructions for the agent (System Prompt)\r\ninstruction = \"You are a creative storyteller who crafts imaginative narratives with vivid details, rich characters, and unexpected plot twists.\"\r\n\r\n# Step 3: Load pre-defined tools that the agent will use\r\n# These tools enable the agent to create folders and save files\r\ntools = [CreateFolder, SaveFile]\r\n\r\n# Step 4: Set your OpenAI API key\r\nopenai_api_key = \"Your API Key\"\r\n# openai_api_key = os.getenv('OPENAI_API_KEY')\r\n\r\n# Step 5: Initialize the language model for the agent\r\nmodel = OpenaiChatModel(model_name=\"gpt-4o-mini\", api_key=openai_api_key, temperature=0)\r\n\r\n# Step 6: Initialize memory - 4 different techniques are available.\r\n\r\n# This option retains the entire conversation history. \r\n# Use this when you need to maintain a complete record of all interactions without any summarization or truncation.\r\nmemory = ConversationBufferMemory() \r\n\r\n# This option retains only the last K messages in the conversation.\r\n# Ideal for scenarios where you want to limit memory usage and only keep the most recent interactions.\r\n# memory = ConversationBufferWindowMemory(last_k=3) \r\n\r\n# This option automatically summarizes the conversation once it exceeds a specified number of messages.\r\n# Use this to manage lengthy conversations by creating concise summaries while retaining overall context.\r\n# memory = ConversationSummaryMemory(number_of_messages=5) \r\n\r\n\r\n# This option combines summarization with selective message retention. It summarizes the conversation after a certain point and retains only the most recent N messages.\r\n# Perfect for balancing context preservation with memory constraints by keeping key recent interactions while summarizing earlier ones.\r\n# memory = ConversationSummaryBufferMemory(buffer_size=5) \r\n\r\n# Step 7: Initialize the agent with the model, description, instructions, and tools. Set verbose to True to see the steps by step actions.\r\nagent = StructuredAgent(model=model, agent_name=\"AI Assistant\", agent_description=description, agent_instructions=instruction, tools=tools, assistant_agents=[],max_allowed_attempts=50, verbose=True,memory=memory)\r\n\r\nif __name__ ==\"__main__\":\r\n\r\n async def main():\r\n\r\n print_colored(\"Starting the application...........\", \"green\")\r\n\r\n # Example user input\r\n # user_input = \"Create a story about AI agents and save it in a new folder. The story should have two chapters, and each chapter should be saved separately inside the folder\"\r\n\r\n user_input = input(\"User : \")\r\n\r\n # Initialize the messages list to store conversation history\r\n messages = []\r\n\r\n # Step 8: Process user input and interact with the agent\r\n while user_input != \"bye\":\r\n\r\n # The agent processes the user input and generates a response\r\n output = await agent.arun(user_input, messages)\r\n\r\n # Update the messages list with the agent's response\r\n messages = agent.messages\r\n\r\n # If verbose=False is set during agent initialization, uncomment the following line to see the agent's responses\r\n # print_colored(f\"Assistant : {output}\", \"purple\")\r\n\r\n # Prompt the user for the next input\r\n user_input = input(\"User Input : \")\r\n\r\n asyncio.run(main())\r\n\r\n```\r\n\r\n## For More Tutorials Visit My:\r\n\r\n<a href=\"https://www.youtube.com/@learnwithvichu\" style=\"display: flex; align-items: center; text-decoration: none;\">\r\n <img src=\"https://img.shields.io/badge/YouTube-%23FF0000.svg?style=for-the-badge&logo=YouTube&logoColor=white\" alt=\"YouTube Channel\" width=\"150\"/>\r\n</a>\r\n\r\n## Let's stay Connected:\r\n\r\n<a href=\"https://www.linkedin.com/in/vishnu-d-121650167\" style=\"display: flex; align-items: center; text-decoration: none;\">\r\n <img src=\"https://img.shields.io/badge/LinkedIn-%230077B5.svg?style=for-the-badge&logo=LinkedIn&logoColor=white\" alt=\"LinkedIn Profile\" width=\"150\"/>\r\n</a>\r\n\r\n\r\n## License\r\nThis project is licensed under the MIT License. - see the LICENSE file for details.\r\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "CollabAgents is a Python framework developed by Vishnu D. for developing AI agents equipped with specialized roles and tools to handle complex user requests efficiently. Users have 100 percent control over their prompts.",
"version": "0.0.6",
"project_urls": null,
"split_keywords": [
"pip install collabagents",
" pip install collabagents"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "a9471e7c61f25cc4c96be2b9efb6acd4292a556e518fb25c5df62f2fde1ebc02",
"md5": "ddbe49008301bea4d6e57ae6a0519b9b",
"sha256": "119221a23ad23ec7108c86ad99ef4d971c73306752bad7df9f3ac2fc4702e090"
},
"downloads": -1,
"filename": "CollabAgents-0.0.6-py3-none-any.whl",
"has_sig": false,
"md5_digest": "ddbe49008301bea4d6e57ae6a0519b9b",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": null,
"size": 40148,
"upload_time": "2024-09-10T11:12:38",
"upload_time_iso_8601": "2024-09-10T11:12:38.399820Z",
"url": "https://files.pythonhosted.org/packages/a9/47/1e7c61f25cc4c96be2b9efb6acd4292a556e518fb25c5df62f2fde1ebc02/CollabAgents-0.0.6-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "41de816de8c2120237fe508931de5080a646357fa8354101eb9f9bb42655d5b6",
"md5": "2d53b159d8d9097b48eef8459ac3bc59",
"sha256": "eb9e72f716ae02b90906e6f8cbefa9da0012d7baca9077c853348c3af677f41b"
},
"downloads": -1,
"filename": "collabagents-0.0.6.tar.gz",
"has_sig": false,
"md5_digest": "2d53b159d8d9097b48eef8459ac3bc59",
"packagetype": "sdist",
"python_version": "source",
"requires_python": null,
"size": 38615,
"upload_time": "2024-09-10T11:12:40",
"upload_time_iso_8601": "2024-09-10T11:12:40.433224Z",
"url": "https://files.pythonhosted.org/packages/41/de/816de8c2120237fe508931de5080a646357fa8354101eb9f9bb42655d5b6/collabagents-0.0.6.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-09-10 11:12:40",
"github": false,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"lcname": "collabagents"
}