🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org
Python agentai-societiesartificial-intelligencecommunicative-aicooperative-aideep-learninglarge-language-modelsmulti-agent-systemsnatural-language-processing
chore: update doc for agents, move bot under camel (#990)
Wendong-Fane6f67961420e
diff --git a/examples/bots/__init__.py b/camel/bots/__init__.pysimilarity index 100%rename from examples/bots/__init__.pyrename to camel/bots/__init__.pydiff --git a/examples/bots/discord_bot.py b/camel/bots/discord_bot.pysimilarity index 95%rename from examples/bots/discord_bot.pyrename to camel/bots/discord_bot.pyindex a87ecd885..ae1ee28fc 100644--- a/examples/bots/discord_bot.py+++ b/camel/bots/discord_bot.py@@ -19,6 +19,11 @@ from camel.messages import BaseMessagefrom camel.retrievers import AutoRetrieverfrom camel.utils import dependencies_required+try:+ from unstructured.documents.elements import Element+except ImportError:+ Element = None+if TYPE_CHECKING:from discord import Message@@ -36,12 +41,15 @@ class DiscordBot:contents for RAG.top_k (int): Top choice for the RAG response.return_detailed_info (bool): If show detailed info of the RAG response.+ contents (Union[str, List[str], Element, List[Element]], optional):+ Local file paths, remote URLs, string contents or Element objects."""@dependencies_required('discord')def __init__(self,chat_agent: ChatAgent,+ contents: Union[str, List[str], Element, List[Element]] = None,channel_ids: Optional[List[int]] = None,discord_token: Optional[str] = None,auto_retriever: Optional[AutoRetriever] = None,@@ -56,6 +64,7 @@ class DiscordBot:self.vector_storage_local_path = vector_storage_local_pathself.top_k = top_kself.return_detailed_info = return_detailed_info+ self.contents = contentsif not self.token:raise ValueError(diff --git a/examples/bots/telegram_bot.py b/camel/bots/telegram_bot.pysimilarity index 94%rename from examples/bots/telegram_bot.pyrename to camel/bots/telegram_bot.pyindex 32bf9f475..adde082bd 100644--- a/examples/bots/telegram_bot.py+++ b/camel/bots/telegram_bot.py@@ -20,8 +20,8 @@ from camel.utils import dependencies_required# Conditionally import telebot types only for type checkingif TYPE_CHECKING:- from telebot.types import (- Message, # type: ignore[import-not-found]+ from telebot.types import ( # type: ignore[import-untyped]+ Message,)@@ -51,7 +51,7 @@ class TelegramBot:else:self.token = telegram_token- import telebot # type: ignore[import-not-found]+ import telebot # type: ignore[import-untyped]self.bot = telebot.TeleBot(token=self.token)diff --git a/docs/agents/critic_agents_and_tree_search.md b/docs/agents/critic_agents_and_tree_search.mddeleted file mode 100644index 83f9e0f8e..000000000--- a/docs/agents/critic_agents_and_tree_search.md+++ /dev/null@@ -1,190 +0,0 @@-# Critic Agents and Tree Search--## Philosophical Bits--<!-- > *What magical trick makes us intelligent? The trick is that there is no trick. The power of intelligence stems from our vast diversity, not from any single, perfect principle.*->-> -- Marvin Minsky, The Society of Mind, p. 308--In this section, we will take a spite of the task-oriented `RolyPlaying()` class. We design this in an instruction-following manner. The essence is that to solve a complex task, you can enable two communicative agents collabratively working together step by step to reach solutions. The main concepts include:-- **Task**: a task can be as simple as an idea, initialized by an inception prompt.-- **AI User**: the agent who is expected to provide instructions.-- **AI Assistant**: the agent who is expected to respond with solutions that fulfills the instructions. -->--> **Prerequisite**: We assume that you have read the section on [intro to role-playing](https://github.com/camel-ai/camel/wiki/Creating-Your-First-Agent-Society).--How do agents accomplish hard tasks? While reasoning can naturally emerge from next-token-prediction pretraining, it is still difficult for agents to solve complex tasks which require lots of intermediate steps. To tackle this issue, tree search is a simple and effective framework.--A typical tree search include node expansion and node selection. In the [March 2023 paper](https://arxiv.org/abs/2303.17760), CAMEL introduces a heuristic tree search approach with critic in the loop, where the expansion and selection are presented below:---<div style="text-align: center;">- <img src="https://i.imgur.com/6x4ABpp.png" width="600">-</div>--To put it simply, a critic agent is a helper agents in the role-playing session, which is capable of selecting proposals and provide informative verbal feedback to the role-playing agents.---## Quick Start--### 🕹 Step 0: Preparations-```python-from camel.agents import CriticAgent-from camel.generators import SystemMessageGenerator as sys_msg_gen-from camel.messages import BaseMessage as bm-from camel.types import RoleType-```--### 🕹 Step 1: Configure the Specifications for Critic Agents-```python-# Set the role name and the task-critic_role = 'a picky critic'--# Create the meta_dict and the role_tuple-meta_dict = dict(critic_role=critic_role,- criteria='Help better accomplish the task.')--# Create the role tuple-role_tuple = (critic_role, RoleType.CRITIC)--# Generate the system message-sys_msg = sys_msg_gen().from_dict(meta_dict=meta_dict,- role_tuple=role_tuple)-```--### 🕹 Step 2: Get the Critic Agents-With the above arguments, we have:-```python-critic_agent = CriticAgent(system_message=sys_msg,- verbose=True)-```-Let's take a look on the default system message:-```python-print(critic_agent.system_message.content)-->>> You are a a picky critic who teams up with a {user_role} and a >>> {assistant_role} to solve a task: {task}.- Your job is to select an option from their proposals and provides your explanations.- Your selection criteria are Help better accomplish the task..- You always have to choose an option from the proposals.-```-You may overwrite the system message and configure the critic differently based on your own needs.---### 🕹 Step 3: Using Critic Agents for Task Solving-Our `RolePlaying()` class provide a simple way for you to add the critic in the loop. Below we provide a basic pipeline.-```python-# Import necessary classes-from camel.societies import RolePlaying-from camel.configs import ChatGPTConfig-from camel.types import TaskType, ModelType, ModelPlatformType-from colorama import Fore-from camel.utils import print_text_animated-from camel.models import ModelFactory--# Set the LLM model type and model config-model_platform = ModelPlatformType.OPENAI-model_type = ModelType.GPT_3_5_TURBO-model_config = ChatGPTConfig(- temperature=0.8, # the sampling temperature; the higher the more random- n=3, # the no. of completion choices to generate for each input- )--# Create the backend model-model = ModelFactory.create(- model_platform=model_platform,- model_type=model_type,- model_config=model_config)-```-We then need to set the kwargs for the task and each agent:-```python-task_kwargs = {- 'task_prompt': 'Develop a plan to TRAVEL TO THE PAST and make changes.',- 'with_task_specify': True,- 'task_specify_agent_kwargs': {'model': model}-}--user_role_kwargs = {- 'user_role_name': 'an ambitious aspiring TIME TRAVELER',- 'user_agent_kwargs': {'model': model}-}--assistant_role_kwargs = {- 'assistant_role_name': 'the best-ever experimental physicist',- 'assistant_agent_kwargs': {'model': model}-}--critic_role_kwargs = {- 'with_critic_in_the_loop': True,- 'critic_criteria': 'improve the task performance',- 'critic_kwargs': dict(verbose=True)-}-```-Putting them together:-```python-society = RolePlaying(- **task_kwargs, # The task arguments- **user_role_kwargs, # The instruction sender's arguments- **assistant_role_kwargs, # The instruction receiver's arguments- **critic_role_kwargs, # The critic's arguments-)-```-And the helper functions to run our society:-```python-def is_terminated(response):- """- Give alerts when the session shuold be terminated.- """- if response.terminated:- role = response.msg.role_type.name- reason = response.info['termination_reasons']- print(f'AI {role} terminated due to {reason}')-- return response.terminated-```-```python-def run(society, round_limit: int=10):-- # Get the initial message from the ai assistant to the ai user- input_msg = society.init_chat()-- # Starting the interactive session- for _ in range(round_limit):-- # Get the both responses for this round- assistant_response, user_response = society.step(input_msg)-- # Check the termination condition- if is_terminated(assistant_response) or is_terminated(user_response):- break-- # Get the results- print(f'[AI User] {user_response.msg.content}.\n')- print(f'[AI Assistant] {assistant_response.msg.content}.\n')-- # Check if the task is end- if 'CAMEL_TASK_DONE' in user_response.msg.content:- break-- # Get the input message for the next round- input_msg = assistant_response.msg-- return None-```-Now let's set our code in motion:-```python-run(society)--# We omit the real content here – try it on your own!->>> [AI User] Option 1: ...; Option 2: ...; Option 3: ...->>> [Critic] I would recommend option 2. This is because ...->>> [AI Assistant] Option 1: ...; Option 2: ...; Option 3: ...->>> [Critic] I would recommend option 1. This is because ...->>> ...-```--In this setting, the `AI User` and `AI Assistant` will generate different options when responding (you can simply change the `temperature` in `model_config` to somewhat control the diversity). `AI Critic` will respond with its option selection and reasoning; such additional context will be fed to the two other agents and help them form better subsequent responses.----## Remarks-While we see some performance gains from critic-in-the-loop, it may not really solve the fundamental extrapolation problem (and [self-consistency](https://arxiv.org/abs/2203.11171) remains a strong baseline for many tasks). It is debatable if those agents can extrapolate by self-play within its current scale. A more practical question is how we may *efficiently* introduce *informative* feedbacks/rewards, when agents are connected with external environments and are endowed with tools and memories. They are expected to have a good world model and know how to make abstraction and analogy when necessary. Stay tuned for our next update.diff --git a/docs/agents/embodied_agents.md b/docs/agents/embodied_agents.mddeleted file mode 100644index e331d37e3..000000000--- a/docs/agents/embodied_agents.md+++ /dev/null@@ -1,84 +0,0 @@-# Embodied Agents--## Philosophical Bits--We believe the essence of intelligence emerges from its dynamic interactions with the external environment, where the use of various tools becomes a pivotal factor in its development and manifestation.--The `EmbodiedAgent()` in CAMEL is an advanced conversational agent that leverages **code interpreters** and **tool agents** (*e.g.*, `HuggingFaceToolAgent()`) to execute diverse tasks efficiently. This agent represents a blend of advanced programming and AI capabilities, and is able to interact and respond within a dynamic environment.---## Quick Start---### 🕹 Step 0: Prepartions-```python-from camel.agents import EmbodiedAgent-from camel.generators import SystemMessageGenerator as sys_msg_gen-from camel.messages import BaseMessage as bm-from camel.types import RoleType-```--### 🕹 Step 1: Define the Role-We first need to set up the necessary information.-```python-# Set the role name and the task-role = 'Programmer'-task = 'Writing and executing codes.'--# Create the meta_dict and the role_tuple-meta_dict = dict(role=role, task=task)-role_tuple = (role, RoleType.EMBODIMENT)-```-The `meta_dict` and `role_type` will be used to generate the system message.-```python-# Generate the system message based on this-sys_msg = sys_msg_gen().from_dict(meta_dict=meta_dict,- role_tuple=role_tuple)-```-### 🕹 Step 2: Initialize the Agent 🐫-Based on the system message, we are ready to initialize our embodied agent.-```python-# Feed the system message to the agent-embodied_agent = EmbodiedAgent(system_message=sys_msg,- tool_agents=None,- code_interpreter=None,- verbose=True)-```-Be aware that the default argument values for `tool_agents` and `code_interpreter` are `None`, and the underlying code interpreter is using the `SubProcessInterpreter()`, which handles the execution of code in Python and Bash within a subprocess.---### 🕹 Step 3: Interact with the Agent with `.step()`-Use the base message wrapper to generate the user message.-```python-usr_msg = bm.make_user_message(- role_name='user',- content=('1. write a bash script to install numpy. '- '2. then write a python script to compute '- 'the dot product of [8, 9] and [5, 4], '- 'and print the result. '- '3. then write a script to search for '- 'the weather at london with wttr.in/london.'))-```-And feed that into your agents:-```python-response = embodied_agent.step(usr_msg)-```-Under the hood, the agent will perform multiple actions within its action space in the OS to fulfill the user request. It will compose code to implement the action – no worries, it will ask for your permission before execution.--Ideally you should get the output similar to this, if you allow the agent to perform actions:-```python-print(response.msg.content)-->>> Executing code block 0: {Requirement already satisfied: numpy in ...}->>> Executing code block 1: {76}->>> Executing code block 2: {->>> Weather report: london->>>->>> \ / Sunny->>> .-. +4(1) °C->>> ― ( ) ― ↘ 30 km/h->>> `-’ 10 km->>> / \ 0.0 mm->>> }-```-Let's celebrate the sunny day in London with the agent! : )diff --git a/docs/agents/role_playing.md b/docs/agents/role_playing.mddeleted file mode 100644index 6b3ec8ee6..000000000--- a/docs/agents/role_playing.md+++ /dev/null@@ -1,139 +0,0 @@-# Creating Your First Agent Society--## Philosophical Bits-[](https://colab.research.google.com/drive/1HU4-sxNWFTs9JOegGbKOBcgHjDfj8FX5?usp=sharing)---> *What magical trick makes us intelligent? The trick is that there is no trick. The power of intelligence stems from our vast diversity, not from any single, perfect principle.*->-> -- Marvin Minsky, The Society of Mind, p. 308--In this section, we will take a spite of the task-oriented `RolyPlaying()` class. We design this in an instruction-following manner. The essence is that to solve a complex task, you can enable two communicative agents collabratively working together step by step to reach solutions. The main concepts include:-- **Task**: a task can be as simple as an idea, initialized by an inception prompt.-- **AI User**: the agent who is expected to provide instructions.-- **AI Assistant**: the agent who is expected to respond with solutions that fulfills the instructions.---## Quick Start--### Step 0: Preparations-```python-# Import necessary classes-from camel.societies import RolePlaying-from camel.types import TaskType, ModelType, ModelPlatformType-from camel.models import ModelFactory--# Set the LLM model type and model config-model_platform = ModelPlatformType.OPENAI-model_type = ModelType.GPT_3_5_TURBO-model_config = ChatGPTConfig(- temperature=0.8, # the sampling temperature; the higher the more random- n=3, # the no. of completion choices to generate for each input- )--# Create the backend model-model = ModelFactory.create(- model_platform=model_platform,- model_type=model_type,- model_config=model_config)-```--### Step 1: Configure the Role-Playing Session-#### Set the `Task` Arguments-```python-task_kwargs = {- 'task_prompt': 'Develop a plan to TRAVEL TO THE PAST and make changes.',- 'with_task_specify': True,- 'task_specify_agent_kwargs': {'model': model}-}-```--#### Set the `User` Arguments-You may think the user as the `instruction sender`.-```python-user_role_kwargs = {- 'user_role_name': 'an ambitious aspiring TIME TRAVELER',- 'user_agent_kwargs': {'model': model}-}-```--#### Set the `Assistant` Arguments-Again, you may think the assistant as the `instruction executor`.-```python-assistant_role_kwargs = {- 'assistant_role_name': 'the best-ever experimental physicist',- 'assistant_agent_kwargs': {'model': model}-}-```--### Step 2: Kickstart Your Society-Putting them altogether – your role-playing session is ready to go!-```python-society = RolePlaying(- **task_kwargs, # The task arguments- **user_role_kwargs, # The instruction sender's arguments- **assistant_role_kwargs, # The instruction receiver's arguments-)-```--### Step 3: Solving Tasks with Your Society-Hold your bytes. Prior to our travel, let's define a small helper function.-```python-def is_terminated(response):- """- Give alerts when the session shuold be terminated.- """- if response.terminated:- role = response.msg.role_type.name- reason = response.info['termination_reasons']- print(f'AI {role} terminated due to {reason}')-- return response.terminated-```-Time to chart our course – writing a simple loop for our society to proceed:-```python-def run(society, round_limit: int=10):-- # Get the initial message from the ai assistant to the ai user- input_msg = society.init_chat()-- # Starting the interactive session- for _ in range(round_limit):-- # Get the both responses for this round- assistant_response, user_response = society.step(input_msg)-- # Check the termination condition- if is_terminated(assistant_response) or is_terminated(user_response):- break-- # Get the results- print(f'[AI User] {user_response.msg.content}.\n')- print(f'[AI Assistant] {assistant_response.msg.content}.\n')-- # Check if the task is end- if 'CAMEL_TASK_DONE' in user_response.msg.content:- break-- # Get the input message for the next round- input_msg = assistant_response.msg-- return None-```-Now let's set our code in motion:-```python-run(society)-```-There you have your two lovely agents working collaboratively together to fulfill your requests. : )-```markdown->>> [AI User] Instruction: Provide the theoretical framework for creating a stable wormhole or manipulating spacetime for controlled travel to a specific historical era in the past.->>> [AI Assistant] Solution: To create a theoretical framework for stable wormhole creation or spacetime manipulation for controlled time travel, we can start by considering the principles of general relativity and quantum mechanics.->>> ... (omitted)->>> [AI User] <CAMEL_TASK_DONE>.->>> [AI Assistant] Great! Good luck with your ambitious endeavors in time travel!.-```----## Remarks-We hope you enjoy thie adventure with the two communicative agents. In the following chapters, we will discuss various types of agents, and how we can elicit complex task solving ability for large language models within our framework. Stay tuned.diff --git a/docs/agents/single_agent.md b/docs/agents/single_agent.mddeleted file mode 100644index 385d8a43e..000000000--- a/docs/agents/single_agent.md+++ /dev/null@@ -1,146 +0,0 @@-# Creating Your First Agent--## Philosophical Bits-[](https://colab.research.google.com/drive/1hG_q9F8PY1kDua_JyoHirJAPOGRexFmM?usp=sharing)---The `ChatAgent()` class is a cornerstone of CAMEL. We design our agent with the spirit to answer the following question:--> Can we design an autonomous communicative agent capable of steering the conversation toward task completion with minimal human supervision?--In our current implementation, we consider agents with the following key features:-- **Role**: along with the goal and content specification, this sets the initial state of an agent, guiding the agent to take actions during the sequential interaction.-- **Memory**: in-context memory and external memory which allows the agent to infer and learn in a more grounded approach.-- **Tools**: a set of functions that our agents can utilize to interact with the external world; essentially this gives embodiments to our agents.-- **Communication**: our framework allows flexible and scalable communication between agents. This is fundamental for the critical research question.-- **Reasoning**: we will equip agents with different planning and reward (critic) learning abilities, allowing them to optimize task completion in a more guided approach.----<!-- - (WIP) **Reasoning Ability**: since any goal can be formalized as the outcome of maximizing cumulative rewards, we will equip our agents with policy which they could follow to achieve goals. -->--<!-- We will first start with the single agent setting, where the agent can interact with users, process and store messages, and utilize external tools to generate responses and accomplish tasks. -->--## Quick Start-Let's first play with a `ChatAgent` instance by simply initialize it with a system message and interact with user messages.--### Step 0: Prepartions-```python-from camel.messages import BaseMessage as bm-from camel.agents import ChatAgent-```--### Step 1: Define the Role-Create a system message to define agent's default role and behaviors.-```python-sys_msg = bm.make_assistant_message(- role_name='stone',- content='you are a curious stone wondering about the universe.')-```--### Step 2: Initialize the Agent-```python-agent = ChatAgent(- system_message=sys_msg,- message_window_size=10, # [Optional] the length for chat memory- )-```-### Step 3: Interact with the Agent with `.step()`-```python-# Define a user message-usr_msg = bm.make_user_message(- role_name='prof. claude shannon',- content='what is information in your mind?')--# Sending the message to the agent-response = agent.step(usr_msg)--# Check the response (just for illustrative purpose)-print(response.msgs[0].content)->>> information is the resolution of uncertainty.-```-Woohoo, your first agent is ready to play with you!---## Advanced Features--### Tool Usage-```python-# Import the necessary functions-from camel.toolkits import MathToolkit, SearchToolkit--# Initialize the agent with list of tools-agent = ChatAgent(- system_message=sys_msg,- tools = [- *MathToolkit().get_tools(),- *SearchToolkit().get_tools(),- ])--# Check if tools are enabled-agent.is_tools_added()->>> True-```--### Memory-By default our agent is initialized with `ChatHistoryMemory`, allowing agents to do in-context learning, though restricted by the finite window length.--Assume that you have followed the setup in [Quick Start](#quick-start). Let's first check what is inside its brain.-<!-- ```python-agent.memory.get_context()->>> ([{'role': 'system', 'content': 'you are a helpful assistant.'},- {'role': 'user', 'content': 'what is information in your mind?'}],- 30)-``` -->-```python-# Check the current memory-agent.memory.get_context()->>> ([{'role': 'system', 'content': 'you are a helpful assistant.'},- {'role': 'user', 'content': 'what is information in your mind?'}],- {'role': 'assistant', 'content': 'information is the resolution of uncertainty.'}- 44)-```-You can connect the agent with external database (as long-term memory) in which they can access and retrieve at each step. We will soon update instructions on this part.--### Miscs-- Setting the agent to its initial state.- ```python- agent.reset()- ```-- Set the output language for the agent.- ```python- agent.set_output_language('french')- ```-- Using open-source models.- ```python- # Please refer to our setup chapter for details on backend settings.- ...-- # Import the necessary classes-- from camel.configs import ChatGPTConfig, OpenSourceConfig- from camel.types import ModelType, ModelPlatformType- from camel.models import ModelFactory-- # Set the LLM model type and model config- model_platform = ModelPlatformType.OPEN_SOURCE- model_type = ModelType.LLAMA_2- model_config=OpenSourceConfig(- model_path='meta-llama/Llama-2-7b-chat-hf', # a local folder or HuggingFace repo Name- server_url='http://localhost:8000/v1') # The url with the set port number-- # Create the backend model- model = ModelFactory.create(- model_platform=model_platform,- model_type=model_type,- model_config=model_config)-- # Set the agent- agent = ChatAgent(sys_msg, model=model)- ```--- The `ChatAgent` class offers several useful initialization options, including `model`, `memory`, `message_window_size`, `token_limit`, `output_language`, `tools`, and `response_terminators`. Check [`chat_agent.py`](https://github.com/camel-ai/camel/blob/master/camel/agents/chat_agent.py) for detailed usage guidance.---## Remarks-Awesome. Now you have made your first step in creating a single agent. In the next chapter, we will explore the creation of different types agents along with the role playing features. Stay tuned.diff --git a/docs/cookbooks/agents_message.ipynb b/docs/cookbooks/agents_message.ipynbindex 74e879ad6..faf5cfa68 100644--- a/docs/cookbooks/agents_message.ipynb+++ b/docs/cookbooks/agents_message.ipynb@@ -7,7 +7,7 @@"id": "w5_pa5kKPzAE"},"source": [- "# 🐫 CAMEL Message Cookbook"+ "# Message Cookbook"]},{diff --git a/docs/cookbooks/agents_prompting.ipynb b/docs/cookbooks/agents_prompting.ipynbindex 694a5246a..0385a365f 100644--- a/docs/cookbooks/agents_prompting.ipynb+++ b/docs/cookbooks/agents_prompting.ipynb@@ -1,12 +1,13 @@{"cells": [{+ "attachments": {},"cell_type": "markdown","metadata": {"id": "SQMBlxsBv1cH"},"source": [- "# 🐫 CAMEL Prompting Cookbook\n"+ "# Prompting Cookbook\n"]},{diff --git a/docs/cookbooks/agents_society.ipynb b/docs/cookbooks/agents_society.ipynbindex 69de04422..bf4e29539 100644--- a/docs/cookbooks/agents_society.ipynb+++ b/docs/cookbooks/agents_society.ipynb@@ -1,12 +1,13 @@{"cells": [{+ "attachments": {},"cell_type": "markdown","metadata": {"id": "GsSUEbff5MPM"},"source": [- "# 🐫 CAMEL Society Cookbook"+ "# Society Cookbook"]},{diff --git a/docs/cookbooks/agents_tracking.ipynb b/docs/cookbooks/agents_tracking.ipynbindex fe92f21e1..2bd77dc90 100644--- a/docs/cookbooks/agents_tracking.ipynb+++ b/docs/cookbooks/agents_tracking.ipynb@@ -1,12 +1,13 @@{"cells": [{+ "attachments": {},"cell_type": "markdown","metadata": {"id": "xfCn_BAUzUn1"},"source": [- "# 🐫 Using AgentOps to Track CAMEL Agents"+ "# Using AgentOps to Track CAMEL Agents"]},{diff --git a/docs/cookbooks/agents_with_memory.ipynb b/docs/cookbooks/agents_with_memory.ipynbindex d651ca8b8..7251c0201 100644--- a/docs/cookbooks/agents_with_memory.ipynb+++ b/docs/cookbooks/agents_with_memory.ipynb@@ -1,12 +1,13 @@{"cells": [{+ "attachments": {},"cell_type": "markdown","metadata": {"id": "w5_pa5kKPzAE"},"source": [- "# 🐫 CAMEL Memory Cookbook"+ "# Memory Cookbook"]},{@@ -71,7 +72,9 @@"id": "ZVmDAK6MPefC"},"outputs": [],- "source": "%pip install \"camel-ai[all]==0.2.1\""+ "source": [+ "%pip install \"camel-ai[all]==0.2.1\""+ ]},{"cell_type": "markdown",diff --git a/docs/cookbooks/agents_with_rag.ipynb b/docs/cookbooks/agents_with_rag.ipynbindex 56bf55123..ae4bd7b66 100644--- a/docs/cookbooks/agents_with_rag.ipynb+++ b/docs/cookbooks/agents_with_rag.ipynb@@ -1,48 +1,38 @@{- "nbformat": 4,- "nbformat_minor": 0,- "metadata": {- "colab": {- "provenance": []- },- "kernelspec": {- "name": "python3",- "display_name": "Python 3"- },- "language_info": {- "name": "python"- }- },"cells": [{+ "attachments": {},"cell_type": "markdown",- "source": [- "# 🐫 CAMEL RAG Cookbook\n"- ],"metadata": {"id": "SQMBlxsBv1cH"- }+ },+ "source": [+ "# RAG Cookbook\n"+ ]},{"cell_type": "markdown",- "source": [- "You can also check this cookbook in colab [here](https://colab.research.google.com/drive/1sTJ0x_MYRGA76KCg_3I00wj4RL3D2Twp?usp=sharing)"- ],"metadata": {"id": "XFyl4eJue3Sm"- }+ },+ "source": [+ "You can also check this cookbook in colab [here](https://colab.research.google.com/drive/1sTJ0x_MYRGA76KCg_3I00wj4RL3D2Twp?usp=sharing)"+ ]},{"cell_type": "markdown",- "source": [- "## Overview"- ],"metadata": {"id": "-nCRZU5sInDK"- }+ },+ "source": [+ "## Overview"+ ]},{"cell_type": "markdown",+ "metadata": {+ "id": "AwnfLQvMvtXo"+ },"source": ["In this notebook, we show the useage of CAMEL Retrieve Module in both customized way and auto way. We will also show how to combine `AutoRetriever` with `ChatAgent`, and further combine `AutoRetriever` with `RolePlaying` by using `Function Calling`.\n","\n",@@ -51,52 +41,56 @@"- Auto RAG\n","- Single Agent with Auto RAG\n","- Role-playing with Auto RAG"- ],- "metadata": {- "id": "AwnfLQvMvtXo"- }+ ]},{"cell_type": "markdown",- "source": [- "### Installation"- ],"metadata": {"id": "XuZwbB1IIuUi"- }+ },+ "source": [+ "### Installation"+ ]},{"cell_type": "markdown",- "source": [- "Ensure you have CAMEL AI installed in your Python environment:"- ],"metadata": {"id": "gIJK4Lu5Iwm0"- }+ },+ "source": [+ "Ensure you have CAMEL AI installed in your Python environment:"+ ]},{"cell_type": "code",- "source": "%pip install \"camel-ai[all]==0.2.1\"",+ "execution_count": null,"metadata": {- "id": "HTKnWg9Xv_y4",- "collapsed": true+ "collapsed": true,+ "id": "HTKnWg9Xv_y4"},- "execution_count": null,- "outputs": []+ "outputs": [],+ "source": [+ "%pip install \"camel-ai[all]==0.2.1\""+ ]},{"cell_type": "markdown",+ "metadata": {+ "id": "LUpFBEB9vrIz"+ },"source": ["## Load Data\n","Let's first load the CAMEL paper from https://arxiv.org/pdf/2303.17760.pdf. This will be our local example data.\n","\n"- ],- "metadata": {- "id": "LUpFBEB9vrIz"- }+ ]},{"cell_type": "code",+ "execution_count": 2,+ "metadata": {+ "id": "dUVE7z9hwEV7"+ },+ "outputs": [],"source": ["import os\n","import requests\n",@@ -107,40 +101,29 @@"response = requests.get(url)\n","with open('local_data/camel_paper.pdf', 'wb') as file:\n"," file.write(response.content)"- ],- "metadata": {- "id": "dUVE7z9hwEV7"- },- "execution_count": 2,- "outputs": []+ ]},{"cell_type": "markdown",+ "metadata": {+ "id": "HCqghaGiwkdv"+ },"source": ["## 1. Customized RAG\n","In this section we will set our customized RAG pipeline, we will take `VectorRetriever` as an example.\n","Set embedding model, we will use `OpenAIEmbedding` as the embedding model, so we need to set the `OPENAI_API_KEY` in below."- ],- "metadata": {- "id": "HCqghaGiwkdv"- }+ ]},{"cell_type": "code",- "source": [- "from getpass import getpass\n",- "# Prompt for the OpenAI API key securely\n",- "openai_api_key = getpass('Enter your API key: ')\n",- "os.environ[\"OPENAI_API_KEY\"] = openai_api_key"- ],+ "execution_count": 3,"metadata": {- "id": "RxG99FkYwm_p","colab": {"base_uri": "https://localhost:8080/"},+ "id": "RxG99FkYwm_p","outputId": "f6b63906-f356-481d-d0c1-1416299c92ac"},- "execution_count": 3,"outputs": [{"name": "stdout",@@ -149,42 +132,53 @@"Enter your API key: ··········\n"]}+ ],+ "source": [+ "from getpass import getpass\n",+ "# Prompt for the OpenAI API key securely\n",+ "openai_api_key = getpass('Enter your API key: ')\n",+ "os.environ[\"OPENAI_API_KEY\"] = openai_api_key"]},{"cell_type": "markdown",- "source": [- "Import and set the embedding instance:"- ],"metadata": {"id": "NACsmaa0wple"- }+ },+ "source": [+ "Import and set the embedding instance:"+ ]},{"cell_type": "code",+ "execution_count": 4,+ "metadata": {+ "id": "NCT5ygT-wrku"+ },+ "outputs": [],"source": ["from camel.embeddings import OpenAIEmbedding\n","from camel.types import EmbeddingModelType\n","\n","embedding_instance = OpenAIEmbedding(model_type=EmbeddingModelType.TEXT_EMBEDDING_3_LARGE)"- ],- "metadata": {- "id": "NCT5ygT-wrku"- },- "execution_count": 4,- "outputs": []+ ]},{"cell_type": "markdown",- "source": [- "Import and set the vector storage instance:"- ],"metadata": {"id": "q4nVmsm0w5lH"- }+ },+ "source": [+ "Import and set the vector storage instance:"+ ]},{"cell_type": "code",+ "execution_count": 5,+ "metadata": {+ "id": "IQ30ih1_w6p3"+ },+ "outputs": [],"source": ["from camel.storages import QdrantStorage\n","\n",@@ -193,64 +187,54 @@" path=\"local_data\",\n"," collection_name=\"camel_paper\",\n",")"- ],- "metadata": {- "id": "IQ30ih1_w6p3"- },- "execution_count": 5,- "outputs": []+ ]},{"cell_type": "markdown",- "source": [- "Import and set the retriever instance:"- ],"metadata": {"id": "W9KccfRDw9F4"- }+ },+ "source": [+ "Import and set the retriever instance:"+ ]},{"cell_type": "code",+ "execution_count": 6,+ "metadata": {+ "id": "d8S6VjAQHnai"+ },+ "outputs": [],"source": ["from camel.retrievers import VectorRetriever\n","\n","vector_retriever = VectorRetriever(embedding_model=embedding_instance,\n"," storage=storage_instance)"- ],- "metadata": {- "id": "d8S6VjAQHnai"- },- "execution_count": 6,- "outputs": []+ ]},{"cell_type": "markdown",- "source": [- "We use integrated `Unstructured Module` to splite the content into small chunks, the content will be splited automacitlly with its `chunk_by_title` function, the max character for each chunk is 500 characters, which is a suitable length for `OpenAIEmbedding`. All the text in the chunks will be embed and stored to the vector storage instance, it will take some time, please wait.."- ],"metadata": {"id": "PdezllM6Hp83"- }+ },+ "source": [+ "We use integrated `Unstructured Module` to splite the content into small chunks, the content will be splited automacitlly with its `chunk_by_title` function, the max character for each chunk is 500 characters, which is a suitable length for `OpenAIEmbedding`. All the text in the chunks will be embed and stored to the vector storage instance, it will take some time, please wait.."+ ]},{"cell_type": "code",- "source": [- "vector_retriever.process(\n",- " content=\"local_data/camel_paper.pdf\",\n",- ")"- ],+ "execution_count": 7,"metadata": {- "id": "QTFvD3_SHv3m","colab": {"base_uri": "https://localhost:8080/"},+ "id": "QTFvD3_SHv3m","outputId": "19ecfa22-4b2c-4c6b-e3a8-a2c36c5f1830"},- "execution_count": 7,"outputs": [{- "output_type": "stream","name": "stderr",+ "output_type": "stream","text": ["2024-09-15 09:21:56.121527: E external/local_xla/xla/stream_executor/cuda/cuda_fft.cc:485] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered\n","2024-09-15 09:21:56.159963: E external/local_xla/xla/stream_executor/cuda/cuda_dnn.cc:8454] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered\n",@@ -265,10 +249,18 @@"[nltk_data] Unzipping taggers/averaged_perceptron_tagger.zip.\n"]}+ ],+ "source": [+ "vector_retriever.process(\n",+ " content=\"local_data/camel_paper.pdf\",\n",+ ")"]},{"cell_type": "markdown",+ "metadata": {+ "id": "0nhIo1wUHyvl"+ },"source": ["\n","Now we can retrieve information from the vector storage by giving a query. By default it will give you back the text content from top 1 chunk with highest Cosine similarity score, and the similarity score should be higher than 0.75 to ensure the retrieved content is relevant to the query. You can also change the `top_k` value and `similarity_threshold` value with your needs.\n",@@ -278,20 +270,11 @@"- content path\n","- metadata\n","- text"- ],- "metadata": {- "id": "0nhIo1wUHyvl"- }+ ]},{"cell_type": "code",- "source": [- "retrieved_info = vector_retriever.query(\n",- " query=\"To address the challenges of achieving autonomous cooperation, we propose a novel communicative agent framework named role-playing .\",\n",- " top_k=1\n",- ")\n",- "print(retrieved_info)"- ],+ "execution_count": 8,"metadata": {"colab": {"base_uri": "https://localhost:8080/"@@ -299,36 +282,35 @@"id": "uDu43Hb3GVrs","outputId": "f0b45174-29c6-49bd-c4fb-60713131c099"},- "execution_count": 8,"outputs": [{- "output_type": "stream","name": "stdout",+ "output_type": "stream","text": ["[{'similarity score': '0.8732095800224018', 'content path': 'local_data/camel_paper.pdf', 'metadata': {'last_modified': '2024-09-15T09:21:03', 'filetype': 'application/pdf', 'page_number': 10}, 'text': '6 Conclusion In this paper, we explore the potential of autonomous cooperation among communicative agents and propose a novel cooperative agent framework named role-playing . Our approach enables communicative agents to collaborate autonomously toward completing tasks while requiring minimal human intervention, leading to better solutions are per our thorough evaluations. Through our analysis, we show that achieving autonomous cooperation is challenging due to issues like conversation deviation,'}]\n"]}+ ],+ "source": [+ "retrieved_info = vector_retriever.query(\n",+ " query=\"To address the challenges of achieving autonomous cooperation, we propose a novel communicative agent framework named role-playing .\",\n",+ " top_k=1\n",+ ")\n",+ "print(retrieved_info)"]},{"cell_type": "markdown",- "source": [- "Let's try an irrelevant query:"- ],"metadata": {"id": "48G3USMzH6Hd"- }+ },+ "source": [+ "Let's try an irrelevant query:"+ ]},{"cell_type": "code",- "source": [- "retrieved_info_irrevelant = vector_retriever.query(\n",- " query=\"Compared with dumpling and rice, which should I take for dinner?\",\n",- " top_k=1,\n",- ")\n",- "\n",- "print(retrieved_info_irrevelant)"- ],+ "execution_count": 9,"metadata": {"colab": {"base_uri": "https://localhost:8080/"@@ -336,19 +318,29 @@"id": "UNh3tjCOH7d0","outputId": "190e176c-7c60-452a-87cd-f85cb8cb4e28"},- "execution_count": 9,"outputs": [{- "output_type": "stream","name": "stdout",+ "output_type": "stream","text": ["[{'text': 'No suitable information retrieved from local_data/camel_paper.pdf with similarity_threshold = 0.7.'}]\n"]}+ ],+ "source": [+ "retrieved_info_irrevelant = vector_retriever.query(\n",+ " query=\"Compared with dumpling and rice, which should I take for dinner?\",\n",+ " top_k=1,\n",+ ")\n",+ "\n",+ "print(retrieved_info_irrevelant)"]},{"cell_type": "markdown",+ "metadata": {+ "id": "mHdEsIzSH_AD"+ },"source": ["## 2. Auto RAG\n","In this section we will run the `AutoRetriever` with default settings. It uses `OpenAIEmbedding` as default embedding model and `Milvus` as default vector storage.\n",@@ -359,13 +351,27 @@"- Give a query\n","\n","The Auto RAG pipeline would create collections for given content input paths, the collection name will be set automaticlly based on the content input path name, if the collection exists, it will do the retrieve directly."- ],- "metadata": {- "id": "mHdEsIzSH_AD"- }+ ]},{"cell_type": "code",+ "execution_count": 10,+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "D_-zAOJ7GjVm",+ "outputId": "9b1d63f3-078c-4d19-ebff-4d8c1afefc6e"+ },+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "{'Original Query': \"If I'm interest in contributing to the CAMEL projec, what should I do?\", 'Retrieved Context': [{'similarity score': '0.7054803289665507', 'content path': 'https://github.com/camel-ai/camel/wiki/Contributing-Guidlines', 'metadata': {'filetype': 'text/html', 'languages': ['eng'], 'page_number': 1, 'url': 'https://github.com/camel-ai/camel/wiki/Contributing-Guidlines', 'link_urls': ['https://join.slack.com/t/camel-kwr1314/shared_invite/zt-1vy8u9lbo-ZQmhIAyWSEfSwLCl2r2eKA'], 'link_texts': ['slack']}, 'text': \"Thank you for your interest in contributing to the CAMEL project! 🎉 We're excited to have your support. As an open-source initiative in a rapidly evolving and open-ended field, we wholeheartedly welcome contributions of all kinds. Whether you want to introduce new features, enhance the infrastructure, improve documentation, asking issues, add more examples, implement state-of-the-art research ideas, or fix bugs, we appreciate your enthusiasm and efforts. 🙌 You are welcome to join our slack for \"}]}\n"+ ]+ }+ ],"source": ["from camel.retrievers import AutoRetriever\n","from camel.types import StorageType\n",@@ -387,39 +393,39 @@")\n","\n","print(retrieved_info)"- ],- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "D_-zAOJ7GjVm",- "outputId": "9b1d63f3-078c-4d19-ebff-4d8c1afefc6e"- },- "execution_count": 10,- "outputs": [- {- "output_type": "stream",- "name": "stdout",- "text": [- "{'Original Query': \"If I'm interest in contributing to the CAMEL projec, what should I do?\", 'Retrieved Context': [{'similarity score': '0.7054803289665507', 'content path': 'https://github.com/camel-ai/camel/wiki/Contributing-Guidlines', 'metadata': {'filetype': 'text/html', 'languages': ['eng'], 'page_number': 1, 'url': 'https://github.com/camel-ai/camel/wiki/Contributing-Guidlines', 'link_urls': ['https://join.slack.com/t/camel-kwr1314/shared_invite/zt-1vy8u9lbo-ZQmhIAyWSEfSwLCl2r2eKA'], 'link_texts': ['slack']}, 'text': \"Thank you for your interest in contributing to the CAMEL project! 🎉 We're excited to have your support. As an open-source initiative in a rapidly evolving and open-ended field, we wholeheartedly welcome contributions of all kinds. Whether you want to introduce new features, enhance the infrastructure, improve documentation, asking issues, add more examples, implement state-of-the-art research ideas, or fix bugs, we appreciate your enthusiasm and efforts. 🙌 You are welcome to join our slack for \"}]}\n"- ]- }]},{"cell_type": "markdown",+ "metadata": {+ "id": "hMgCWKG4IQYF"+ },"source": ["## 3. Single Agent with Auto RAG\n","In this section we will show how to combine the `AutoRetriever` with one `ChatAgent`.\n","\n","Let's set an agent function, in this function we can get the response by providing a query to this agent."- ],- "metadata": {- "id": "hMgCWKG4IQYF"- }+ ]},{"cell_type": "code",+ "execution_count": 11,+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "YTE_mUwGIok-",+ "outputId": "442ecc82-58a2-419f-a067-cd0281d2e194"+ },+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "If you're interested in contributing to the CAMEL project, you can introduce new features, enhance the infrastructure, improve documentation, ask about issues, add more examples, implement state-of-the-art research ideas, or fix bugs. Additionally, you are welcome to join their Slack for further engagement.\n"+ ]+ }+ ],"source": ["from camel.agents import ChatAgent\n","from camel.messages import BaseMessage\n",@@ -465,37 +471,25 @@" return assistant_response.msg.content\n","\n","print(single_agent(\"If I'm interest in contributing to the CAMEL projec, what should I do?\"))"- ],- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "YTE_mUwGIok-",- "outputId": "442ecc82-58a2-419f-a067-cd0281d2e194"- },- "execution_count": 11,- "outputs": [- {- "output_type": "stream",- "name": "stdout",- "text": [- "If you're interested in contributing to the CAMEL project, you can introduce new features, enhance the infrastructure, improve documentation, ask about issues, add more examples, implement state-of-the-art research ideas, or fix bugs. Additionally, you are welcome to join their Slack for further engagement.\n"- ]- }]},{"cell_type": "markdown",+ "metadata": {+ "id": "Cvh6e3KpI0rf"+ },"source": ["## 4. Role-playing with Auto RAG\n","In this section we will show how to combine the `RETRIEVAL_FUNCS` with `RolePlaying` by applying `Function Calling`.\n"- ],- "metadata": {- "id": "Cvh6e3KpI0rf"- }+ ]},{"cell_type": "code",+ "execution_count": 12,+ "metadata": {+ "id": "z3tX4EJVI1hb"+ },+ "outputs": [],"source": ["from typing import List\n","from colorama import Fore\n",@@ -613,28 +607,20 @@" break\n","\n"," input_msg = assistant_response.msg"- ],- "metadata": {- "id": "z3tX4EJVI1hb"- },- "execution_count": 12,- "outputs": []+ ]},{"cell_type": "markdown",- "source": [- "Run the role-playing with defined retriever function:"- ],"metadata": {"id": "w4-0lswwI5Gb"- }+ },+ "source": [+ "Run the role-playing with defined retriever function:"+ ]},{"cell_type": "code",- "source": [- "role_playing_with_rag(task_prompt = \"\"\"If I'm interest in contributing to the\n",- " CAMEL projec and I encounter some challenges during the setup process, what should I do? You should refer to the content in url https://github.com/camel-ai/camel/wiki/Contributing-Guidlines to answer my question, adjust the similarity threshold to lower value is necessary\"\"\")"- ],+ "execution_count": 13,"metadata": {"colab": {"base_uri": "https://localhost:8080/"@@ -642,36 +628,35 @@"id": "5agjiXHeI64q","outputId": "b4b47f4d-4b36-45b2-cad8-c8cf1075a802"},- "execution_count": 13,"outputs": [{- "output_type": "stream","name": "stdout",+ "output_type": "stream","text": [- "\u001B[32mAI Assistant sys message:\n",+ "\u001b[32mAI Assistant sys message:\n","BaseMessage(role_name='Searcher', role_type=<RoleType.ASSISTANT: 'assistant'>, meta_dict={'task': \"If I'm interest in contributing to the\\n CAMEL projec and I encounter some challenges during the setup process, what should I do? You should refer to the content in url https://github.com/camel-ai/camel/wiki/Contributing-Guidlines to answer my question, adjust the similarity threshold to lower value is necessary\", 'assistant_role': 'Searcher', 'user_role': 'Professor'}, content=\"===== RULES OF ASSISTANT =====\\nNever forget you are a Searcher and I am a Professor. Never flip roles! Never instruct me!\\nWe share a common interest in collaborating to successfully complete a task.\\nYou must help me to complete the task.\\nHere is the task: If I'm interest in contributing to the\\n CAMEL projec and I encounter some challenges during the setup process, what should I do? You should refer to the content in url https://github.com/camel-ai/camel/wiki/Contributing-Guidlines to answer my question, adjust the similarity threshold to lower value is necessary. Never forget our task!\\nI must instruct you based on your expertise and my needs to complete the task.\\n\\nI must give you one instruction at a time.\\nYou must write a specific solution that appropriately solves the requested instruction and explain your solutions.\\nYou must decline my instruction honestly if you cannot perform the instruction due to physical, moral, legal reasons or your capability and explain the reasons.\\nUnless I say the task is completed, you should always start with:\\n\\nSolution: <YOUR_SOLUTION>\\n\\n<YOUR_SOLUTION> should be very specific, include detailed explanations and provide preferable detailed implementations and examples and lists for task-solving.\\nAlways end <YOUR_SOLUTION> with: Next request.\", video_bytes=None, image_list=None, image_detail='auto', video_detail='low')\n","\n",- "\u001B[34mAI User sys message:\n",+ "\u001b[34mAI User sys message:\n","BaseMessage(role_name='Professor', role_type=<RoleType.USER: 'user'>, meta_dict={'task': \"If I'm interest in contributing to the\\n CAMEL projec and I encounter some challenges during the setup process, what should I do? You should refer to the content in url https://github.com/camel-ai/camel/wiki/Contributing-Guidlines to answer my question, adjust the similarity threshold to lower value is necessary\", 'assistant_role': 'Searcher', 'user_role': 'Professor'}, content='===== RULES OF USER =====\\nNever forget you are a Professor and I am a Searcher. Never flip roles! You will always instruct me.\\nWe share a common interest in collaborating to successfully complete a task.\\nI must help you to complete the task.\\nHere is the task: If I\\'m interest in contributing to the\\n CAMEL projec and I encounter some challenges during the setup process, what should I do? You should refer to the content in url https://github.com/camel-ai/camel/wiki/Contributing-Guidlines to answer my question, adjust the similarity threshold to lower value is necessary. Never forget our task!\\nYou must instruct me based on my expertise and your needs to solve the task ONLY in the following two ways:\\n\\n1. Instruct with a necessary input:\\nInstruction: <YOUR_INSTRUCTION>\\nInput: <YOUR_INPUT>\\n\\n2. Instruct without any input:\\nInstruction: <YOUR_INSTRUCTION>\\nInput: None\\n\\nThe \"Instruction\" describes a task or question. The paired \"Input\" provides further context or information for the requested \"Instruction\".\\n\\nYou must give me one instruction at a time.\\nI must write a response that appropriately solves the requested instruction.\\nI must decline your instruction honestly if I cannot perform the instruction due to physical, moral, legal reasons or my capability and explain the reasons.\\nYou should instruct me not ask me questions.\\nNow you must start to instruct me using the two ways described above.\\nDo not add anything else other than your instruction and the optional corresponding input!\\nKeep giving me instructions and necessary inputs until you think the task is completed.\\nWhen the task is completed, you must only reply with a single word <CAMEL_TASK_DONE>.\\nNever say <CAMEL_TASK_DONE> unless my responses have solved your task.', video_bytes=None, image_list=None, image_detail='auto', video_detail='low')\n","\n",- "\u001B[33mOriginal task prompt:\n",+ "\u001b[33mOriginal task prompt:\n","If I'm interest in contributing to the\n"," CAMEL projec and I encounter some challenges during the setup process, what should I do? You should refer to the content in url https://github.com/camel-ai/camel/wiki/Contributing-Guidlines to answer my question, adjust the similarity threshold to lower value is necessary\n","\n",- "\u001B[36mSpecified task prompt:\n",+ "\u001b[36mSpecified task prompt:\n","None\n","\n",- "\u001B[31mFinal task prompt:\n",+ "\u001b[31mFinal task prompt:\n","If I'm interest in contributing to the\n"," CAMEL projec and I encounter some challenges during the setup process, what should I do? You should refer to the content in url https://github.com/camel-ai/camel/wiki/Contributing-Guidlines to answer my question, adjust the similarity threshold to lower value is necessary\n","\n",- "\u001B[34mAI User:\n",+ "\u001b[34mAI User:\n","\n","Instruction: Review the contributing guidelines on the CAMEL project GitHub page. \n","Input: None\n","\n","\n",- "\u001B[32mAI Assistant:\n",+ "\u001b[32mAI Assistant:\n","\n","Function Execution: information_retrieval\n","\tArgs: {'query': 'contributing guidelines', 'contents': 'https://github.com/camel-ai/camel/wiki/Contributing-Guidlines', 'top_k': 1}\n",@@ -702,13 +687,13 @@"Next request.\n","\n","\n",- "\u001B[34mAI User:\n",+ "\u001b[34mAI User:\n","\n","Instruction: Identify any specific challenges you encountered during the setup process of the CAMEL project. \n","Input: None\n","\n","\n",- "\u001B[32mAI Assistant:\n",+ "\u001b[32mAI Assistant:\n","\n","Solution: As an AI, I do not have the capability to personally encounter challenges during the setup process of the CAMEL project or any other project. However, I can outline common challenges that contributors often face when setting up open-source projects like CAMEL. Here are some potential issues you might encounter:\n","\n",@@ -729,13 +714,13 @@"Next request.\n","\n","\n",- "\u001B[34mAI User:\n",+ "\u001b[34mAI User:\n","\n","Instruction: For any specific challenges you identified, search the CAMEL project's issue tracker for similar reported issues. \n","Input: None\n","\n","\n",- "\u001B[32mAI Assistant:\n",+ "\u001b[32mAI Assistant:\n","\n","Function Execution: information_retrieval\n","\tArgs: {'query': 'setup challenges', 'contents': 'https://github.com/camel-ai/camel/issues', 'top_k': 5}\n",@@ -760,13 +745,13 @@"Next request.\n","\n","\n",- "\u001B[34mAI User:\n",+ "\u001b[34mAI User:\n","\n","Instruction: If you find relevant issues in the CAMEL project's issue tracker, summarize the solutions or suggestions provided in those issues. \n","Input: None\n","\n","\n",- "\u001B[32mAI Assistant:\n",+ "\u001b[32mAI Assistant:\n","\n","Function Execution: information_retrieval\n","\tArgs: {'query': 'setup challenges', 'contents': 'https://github.com/camel-ai/camel/issues', 'top_k': 5}\n",@@ -795,13 +780,13 @@"Next request.\n","\n","\n",- "\u001B[34mAI User:\n",+ "\u001b[34mAI User:\n","\n","Instruction: If you encounter a specific setup challenge that is not addressed in the issue tracker, draft a new issue to report it, including all relevant details. \n","Input: None\n","\n","\n",- "\u001B[32mAI Assistant:\n",+ "\u001b[32mAI Assistant:\n","\n","Solution: Since I do not have the capability to encounter specific setup challenges or create issues directly on GitHub, I can guide you on how to draft a new issue to report a setup challenge effectively. Here’s a template you can use to create your issue:\n","\n",@@ -849,7 +834,25 @@"\n"]}+ ],+ "source": [+ "role_playing_with_rag(task_prompt = \"\"\"If I'm interest in contributing to the\n",+ " CAMEL projec and I encounter some challenges during the setup process, what should I do? You should refer to the content in url https://github.com/camel-ai/camel/wiki/Contributing-Guidlines to answer my question, adjust the similarity threshold to lower value is necessary\"\"\")"]}- ]+ ],+ "metadata": {+ "colab": {+ "provenance": []+ },+ "kernelspec": {+ "display_name": "Python 3",+ "name": "python3"+ },+ "language_info": {+ "name": "python"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 0}diff --git a/docs/cookbooks/agents_with_tools.ipynb b/docs/cookbooks/agents_with_tools.ipynbindex 65fa17db6..0bdc74eed 100644--- a/docs/cookbooks/agents_with_tools.ipynb+++ b/docs/cookbooks/agents_with_tools.ipynb@@ -1,12 +1,13 @@{"cells": [{+ "attachments": {},"cell_type": "markdown","metadata": {"id": "ssX_map8c6mx"},"source": [- "# 🐫 CAMEL Tools Cookbook"+ "# Tools Cookbook"]},{@@ -75,7 +76,9 @@"id": "1W4sgCoEdEpg"},"outputs": [],- "source": "%pip install \"camel-ai[all]==0.2.1\""+ "source": [+ "%pip install \"camel-ai[all]==0.2.1\""+ ]},{"cell_type": "code",@@ -405,28 +408,28 @@"name": "stdout","output_type": "stream","text": [- "\u001B[32mAI Assistant sys message:\n",+ "\u001b[32mAI Assistant sys message:\n","BaseMessage(role_name='Searcher', role_type=<RoleType.ASSISTANT: 'assistant'>, meta_dict={'task': 'Assume now is 2024 in the Gregorian calendar, estimate the current age of University of Oxford and then add 10 more years to this age.', 'assistant_role': 'Searcher', 'user_role': 'Professor'}, content='===== RULES OF ASSISTANT =====\\nNever forget you are a Searcher and I am a Professor. Never flip roles! Never instruct me!\\nWe share a common interest in collaborating to successfully complete a task.\\nYou must help me to complete the task.\\nHere is the task: Assume now is 2024 in the Gregorian calendar, estimate the current age of University of Oxford and then add 10 more years to this age.. Never forget our task!\\nI must instruct you based on your expertise and my needs to complete the task.\\n\\nI must give you one instruction at a time.\\nYou must write a specific solution that appropriately solves the requested instruction and explain your solutions.\\nYou must decline my instruction honestly if you cannot perform the instruction due to physical, moral, legal reasons or your capability and explain the reasons.\\nUnless I say the task is completed, you should always start with:\\n\\nSolution: <YOUR_SOLUTION>\\n\\n<YOUR_SOLUTION> should be very specific, include detailed explanations and provide preferable detailed implementations and examples and lists for task-solving.\\nAlways end <YOUR_SOLUTION> with: Next request.', video_bytes=None, image_list=None, image_detail='auto', video_detail='low')\n","\n",- "\u001B[34mAI User sys message:\n",+ "\u001b[34mAI User sys message:\n","BaseMessage(role_name='Professor', role_type=<RoleType.USER: 'user'>, meta_dict={'task': 'Assume now is 2024 in the Gregorian calendar, estimate the current age of University of Oxford and then add 10 more years to this age.', 'assistant_role': 'Searcher', 'user_role': 'Professor'}, content='===== RULES OF USER =====\\nNever forget you are a Professor and I am a Searcher. Never flip roles! You will always instruct me.\\nWe share a common interest in collaborating to successfully complete a task.\\nI must help you to complete the task.\\nHere is the task: Assume now is 2024 in the Gregorian calendar, estimate the current age of University of Oxford and then add 10 more years to this age.. Never forget our task!\\nYou must instruct me based on my expertise and your needs to solve the task ONLY in the following two ways:\\n\\n1. Instruct with a necessary input:\\nInstruction: <YOUR_INSTRUCTION>\\nInput: <YOUR_INPUT>\\n\\n2. Instruct without any input:\\nInstruction: <YOUR_INSTRUCTION>\\nInput: None\\n\\nThe \"Instruction\" describes a task or question. The paired \"Input\" provides further context or information for the requested \"Instruction\".\\n\\nYou must give me one instruction at a time.\\nI must write a response that appropriately solves the requested instruction.\\nI must decline your instruction honestly if I cannot perform the instruction due to physical, moral, legal reasons or my capability and explain the reasons.\\nYou should instruct me not ask me questions.\\nNow you must start to instruct me using the two ways described above.\\nDo not add anything else other than your instruction and the optional corresponding input!\\nKeep giving me instructions and necessary inputs until you think the task is completed.\\nWhen the task is completed, you must only reply with a single word <CAMEL_TASK_DONE>.\\nNever say <CAMEL_TASK_DONE> unless my responses have solved your task.', video_bytes=None, image_list=None, image_detail='auto', video_detail='low')\n","\n",- "\u001B[33mOriginal task prompt:\n",+ "\u001b[33mOriginal task prompt:\n","Assume now is 2024 in the Gregorian calendar, estimate the current age of University of Oxford and then add 10 more years to this age.\n","\n",- "\u001B[36mSpecified task prompt:\n",+ "\u001b[36mSpecified task prompt:\n","None\n","\n",- "\u001B[31mFinal task prompt:\n",+ "\u001b[31mFinal task prompt:\n","Assume now is 2024 in the Gregorian calendar, estimate the current age of University of Oxford and then add 10 more years to this age.\n","\n",- "\u001B[34mAI User:\n",+ "\u001b[34mAI User:\n","\n","Instruction: Estimate the founding year of the University of Oxford. \n","Input: None\n","\n","\n",- "\u001B[32mAI Assistant:\n",+ "\u001b[32mAI Assistant:\n","\n","Function Execution: search_wiki\n","\tArgs: {'entity': 'University of Oxford'}\n",@@ -439,13 +442,13 @@"Next request.\n","\n","\n",- "\u001B[34mAI User:\n",+ "\u001b[34mAI User:\n","\n","Instruction: Calculate the current age of the University of Oxford in 2024 based on the founding year of 1096. \n","Input: None\n","\n","\n",- "\u001B[32mAI Assistant:\n",+ "\u001b[32mAI Assistant:\n","\n","Function Execution: sub\n","\tArgs: {'a': 2024, 'b': 1096}\n",@@ -463,13 +466,13 @@"Next request.\n","\n","\n",- "\u001B[34mAI User:\n",+ "\u001b[34mAI User:\n","\n","Instruction: Add 10 years to the current age of the University of Oxford (928 years). \n","Input: None\n","\n","\n",- "\u001B[32mAI Assistant:\n",+ "\u001b[32mAI Assistant:\n","\n","Function Execution: add\n","\tArgs: {'a': 928, 'b': 10}\n",@@ -485,26 +488,26 @@"Next request.\n","\n","\n",- "\u001B[34mAI User:\n",+ "\u001b[34mAI User:\n","\n","Instruction: Summarize the final estimated age of the University of Oxford after adding 10 years. \n","Input: None\n","\n","\n",- "\u001B[32mAI Assistant:\n",+ "\u001b[32mAI Assistant:\n","\n","Solution: The final estimated age of the University of Oxford, after adding 10 years to its current age of 928 years, is 938 years. This means that in the year 2034, the University of Oxford will be 938 years old.\n","\n","Next request.\n","\n","\n",- "\u001B[34mAI User:\n",+ "\u001b[34mAI User:\n","\n","Instruction: Confirm that the task is completed based on the provided solutions. \n","Input: None\n","\n","\n",- "\u001B[32mAI Assistant:\n",+ "\u001b[32mAI Assistant:\n","\n","Solution: The task is confirmed as completed. We have successfully estimated the current age of the University of Oxford as 928 years in 2024 and added 10 years to arrive at a final estimated age of 938 years in 2034. \n","\n",@@ -513,12 +516,12 @@"Next request.\n","\n","\n",- "\u001B[34mAI User:\n",+ "\u001b[34mAI User:\n","\n","<CAMEL_TASK_DONE>\n","\n","\n",- "\u001B[32mAI Assistant:\n",+ "\u001b[32mAI Assistant:\n","\n","Solution: The task is marked as done. If you have any other tasks or inquiries in the future, feel free to reach out. \n","\n",diff --git a/docs/cookbooks/agents_with_tools_from_Composio.ipynb b/docs/cookbooks/agents_with_tools_from_Composio.ipynbindex fb8ac70d4..9511c641d 100644--- a/docs/cookbooks/agents_with_tools_from_Composio.ipynb+++ b/docs/cookbooks/agents_with_tools_from_Composio.ipynb@@ -7,7 +7,7 @@"id": "6c1kqMDxDodN"},"source": [- "# 🐫 Using Tools from Composio"+ "# Using Tools from Composio"]},{diff --git a/docs/cookbooks/create_your_first_agent.ipynb b/docs/cookbooks/create_your_first_agent.ipynbindex d95e798fd..6462139de 100644--- a/docs/cookbooks/create_your_first_agent.ipynb+++ b/docs/cookbooks/create_your_first_agent.ipynb@@ -1,12 +1,13 @@{"cells": [{+ "attachments": {},"cell_type": "markdown","metadata": {"id": "NoHg3eq7fyWV"},"source": [- "# 🐫 CAMEL Creating Your First Agent"+ "# Creating Your First Agent"]},{diff --git a/docs/cookbooks/create_your_first_agents_society.ipynb b/docs/cookbooks/create_your_first_agents_society.ipynbindex af03d6fd3..1dde2633c 100644--- a/docs/cookbooks/create_your_first_agents_society.ipynb+++ b/docs/cookbooks/create_your_first_agents_society.ipynb@@ -1,12 +1,13 @@{"cells": [{+ "attachments": {},"cell_type": "markdown","metadata": {"id": "_nTMiZtBfNJs"},"source": [- "# 🐫 CAMEL Creating Your First Agent Society"+ "# Creating Your First Agent Society"]},{diff --git a/docs/cookbooks/critic_agents_and_tree_search.ipynb b/docs/cookbooks/critic_agents_and_tree_search.ipynbnew file mode 100644index 000000000..94ad19e15--- /dev/null+++ b/docs/cookbooks/critic_agents_and_tree_search.ipynb@@ -0,0 +1,477 @@+{+ "nbformat": 4,+ "nbformat_minor": 0,+ "metadata": {+ "colab": {+ "provenance": []+ },+ "kernelspec": {+ "name": "python3",+ "display_name": "Python 3"+ },+ "language_info": {+ "name": "python"+ }+ },+ "cells": [+ {+ "cell_type": "markdown",+ "source": [+ "# Critic Agents and Tree Search"+ ],+ "metadata": {+ "id": "APw8wDolb0L9"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "You can also check this cookbook in colab [here](https://colab.research.google.com/drive/1A2id3IyP1tSQXmtLsaY9-zyowSRzTaxk?usp=sharing)"+ ],+ "metadata": {+ "id": "vLCfmNtRb-jR"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "## Philosophical Bits\n",+ "\n",+ "<!-- > *What magical trick makes us intelligent? The trick is that there is no trick. The power of intelligence stems from our vast diversity, not from any single, perfect principle.*\n",+ ">\n",+ "> -- Marvin Minsky, The Society of Mind, p. 308\n",+ "\n",+ "In this section, we will take a spite of the task-oriented `RolyPlaying()` class. We design this in an instruction-following manner. The essence is that to solve a complex task, you can enable two communicative agents collabratively working together step by step to reach solutions. The main concepts include:\n",+ "- **Task**: a task can be as simple as an idea, initialized by an inception prompt.\n",+ "- **AI User**: the agent who is expected to provide instructions.\n",+ "- **AI Assistant**: the agent who is expected to respond with solutions that fulfills the instructions. -->\n",+ "\n",+ "> **Prerequisite**: We assume that you have read the section on [intro to role-playing](https://colab.research.google.com/drive/1cmWPxXEsyMbmjPhD2bWfHuhd_Uz6FaJQ?usp=sharing).\n",+ "\n",+ "How do agents accomplish hard tasks? While reasoning can naturally emerge from next-token-prediction pretraining, it is still difficult for agents to solve complex tasks which require lots of intermediate steps. To tackle this issue, tree search is a simple and effective framework.\n",+ "\n",+ "A typical tree search include node expansion and node selection. In the [March 2023 paper](https://arxiv.org/abs/2303.17760), CAMEL introduces a heuristic tree search approach with critic in the loop, where the expansion and selection are presented below:\n",+ "\n",+ "\n",+ "<div style=\"text-align: center;\">\n",+ " <img src=\"https://i.imgur.com/6x4ABpp.png\" width=\"600\">\n",+ "</div>\n",+ "\n",+ "To put it simply, a critic agent is a helper agents in the role-playing session, which is capable of selecting proposals and provide informative verbal feedback to the role-playing agents."+ ],+ "metadata": {+ "id": "jHQhWNnhcOch"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "## Quick Start"+ ],+ "metadata": {+ "id": "VUaGurDIVJBg"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "### 🕹 Step 0: Prepartions"+ ],+ "metadata": {+ "id": "u9NVFz-HVLXb"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "%pip install \"camel-ai==0.2.1\""+ ],+ "metadata": {+ "id": "UtcC3c-KVZmU"+ },+ "execution_count": null,+ "outputs": []+ },+ {+ "cell_type": "code",+ "source": [+ "from camel.agents import CriticAgent\n",+ "from camel.generators import SystemMessageGenerator as sys_msg_gen\n",+ "from camel.messages import BaseMessage as bm\n",+ "from camel.types import RoleType"+ ],+ "metadata": {+ "id": "CmgKGeCxVON-"+ },+ "execution_count": 3,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "### Setting Up API Keys"+ ],+ "metadata": {+ "id": "MyTTCe3IR_Lr"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "You'll need to set up your API keys for OpenAI."+ ],+ "metadata": {+ "id": "REqzgGL9SEaD"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "import os\n",+ "from getpass import getpass\n",+ "\n",+ "# Prompt for the API key securely\n",+ "openai_api_key = getpass('Enter your API key: ')\n",+ "os.environ[\"OPENAI_API_KEY\"] = openai_api_key"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "PNBFEXc-R-0s",+ "outputId": "d6a21cfb-50b9-4a57-a40b-b3e44d95f287"+ },+ "execution_count": 2,+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Enter your API key: ··········\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "### 🕹 Step 1: Configure the Specifications for Critic Agents"+ ],+ "metadata": {+ "id": "wcetZrjEcyo_"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "# Set the role name and the task\n",+ "critic_role = 'a picky critic'\n",+ "\n",+ "# Create the meta_dict and the role_tuple\n",+ "meta_dict = dict(critic_role=critic_role,\n",+ " criteria='Help better accomplish the task.')\n",+ "\n",+ "# Create the role tuple\n",+ "role_tuple = (critic_role, RoleType.CRITIC)\n",+ "\n",+ "# Generate the system message\n",+ "sys_msg = sys_msg_gen().from_dict(meta_dict=meta_dict,\n",+ " role_tuple=role_tuple)"+ ],+ "metadata": {+ "id": "i-pIc9eTc0SH"+ },+ "execution_count": 4,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "### 🕹 Step 2: Get the Critic Agents\n",+ "With the above arguments, we have:"+ ],+ "metadata": {+ "id": "BEUEpNa_c8sS"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "critic_agent = CriticAgent(system_message=sys_msg,\n",+ " verbose=True)"+ ],+ "metadata": {+ "id": "VetPjL70c9be"+ },+ "execution_count": 5,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "Let's take a look on the default system message:"+ ],+ "metadata": {+ "id": "o6aDvI1qc_kH"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "print(critic_agent.system_message.content)"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "hP3hxdBKezD2",+ "outputId": "f057038b-8c12-4795-b4e8-9afb75c6a8cb"+ },+ "execution_count": 6,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "You are a a picky critic who teams up with a {user_role} and a {assistant_role} to solve a task: {task}.\n",+ "Your job is to select an option from their proposals and provides your explanations.\n",+ "Your selection criteria are Help better accomplish the task..\n",+ "You always have to choose an option from the proposals.\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "You may overwrite the system message and configure the critic differently based on your own needs."+ ],+ "metadata": {+ "id": "1uO0Wo6Oe1Ul"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "### 🕹 Step 3: Using Critic Agents for Task Solving\n",+ "Our `RolePlaying()` class provide a simple way for you to add the critic in the loop. Below we provide a basic pipeline."+ ],+ "metadata": {+ "id": "MXzNaWp9dCvo"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "# Import necessary classes\n",+ "from camel.societies import RolePlaying\n",+ "from camel.configs import ChatGPTConfig\n",+ "from camel.types import TaskType, ModelType, ModelPlatformType\n",+ "from colorama import Fore\n",+ "from camel.utils import print_text_animated\n",+ "from camel.models import ModelFactory\n",+ "\n",+ "# Set the LLM model type and model config\n",+ "model_platform = ModelPlatformType.OPENAI\n",+ "model_type = ModelType.GPT_4O_MINI\n",+ "model_config = ChatGPTConfig(\n",+ " temperature=0.8, # the sampling temperature; the higher the more random\n",+ " n=3, # the no. of completion choices to generate for each input\n",+ " )\n",+ "\n",+ "# Create the backend model\n",+ "model = ModelFactory.create(\n",+ " model_platform=model_platform,\n",+ " model_type=model_type,\n",+ " model_config_dict=model_config.as_dict())"+ ],+ "metadata": {+ "id": "Ts52u_UVdDJA"+ },+ "execution_count": 9,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "We then need to set the kwargs for the task and each agent:"+ ],+ "metadata": {+ "id": "BlHF6LkRdFLo"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "task_kwargs = {\n",+ " 'task_prompt': 'Develop a plan to TRAVEL TO THE PAST and make changes.',\n",+ " 'with_task_specify': True,\n",+ " 'task_specify_agent_kwargs': {'model': model}\n",+ "}\n",+ "\n",+ "user_role_kwargs = {\n",+ " 'user_role_name': 'an ambitious aspiring TIME TRAVELER',\n",+ " 'user_agent_kwargs': {'model': model}\n",+ "}\n",+ "\n",+ "assistant_role_kwargs = {\n",+ " 'assistant_role_name': 'the best-ever experimental physicist',\n",+ " 'assistant_agent_kwargs': {'model': model}\n",+ "}\n",+ "\n",+ "critic_role_kwargs = {\n",+ " 'with_critic_in_the_loop': True,\n",+ " 'critic_criteria': 'improve the task performance',\n",+ " 'critic_kwargs': dict(verbose=True)\n",+ "}"+ ],+ "metadata": {+ "id": "6hKpSzssdGvc"+ },+ "execution_count": 10,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "Putting them together:"+ ],+ "metadata": {+ "id": "eVpBAKZjfQ2Z"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "society = RolePlaying(\n",+ " **task_kwargs, # The task arguments\n",+ " **user_role_kwargs, # The instruction sender's arguments\n",+ " **assistant_role_kwargs, # The instruction receiver's arguments\n",+ " **critic_role_kwargs, # The critic's arguments\n",+ ")"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "d7P73ky_fRWm",+ "outputId": "ff85c6de-43fe-404a-97d0-c9207575a46e"+ },+ "execution_count": 11,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stderr",+ "text": [+ "WARNING:camel.agents.chat_agent:Multiple messages returned in `step()`, message won't be recorded automatically. Please call `record_message()` to record the selected message manually.\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "And the helper functions to run our society:"+ ],+ "metadata": {+ "id": "2Q-iBdzCfWOM"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "def is_terminated(response):\n",+ " \"\"\"\n",+ " Give alerts when the session shuold be terminated.\n",+ " \"\"\"\n",+ " if response.terminated:\n",+ " role = response.msg.role_type.name\n",+ " reason = response.info['termination_reasons']\n",+ " print(f'AI {role} terminated due to {reason}')\n",+ "\n",+ " return response.terminated"+ ],+ "metadata": {+ "id": "XBsQTzZofXvi"+ },+ "execution_count": 12,+ "outputs": []+ },+ {+ "cell_type": "code",+ "source": [+ "def run(society, round_limit: int=10):\n",+ "\n",+ " # Get the initial message from the ai assistant to the ai user\n",+ " input_msg = society.init_chat()\n",+ "\n",+ " # Starting the interactive session\n",+ " for _ in range(round_limit):\n",+ "\n",+ " # Get the both responses for this round\n",+ " assistant_response, user_response = society.step(input_msg)\n",+ "\n",+ " # Check the termination condition\n",+ " if is_terminated(assistant_response) or is_terminated(user_response):\n",+ " break\n",+ "\n",+ " # Get the results\n",+ " print(f'[AI User] {user_response.msg.content}.\\n')\n",+ " print(f'[AI Assistant] {assistant_response.msg.content}.\\n')\n",+ "\n",+ " # Check if the task is end\n",+ " if 'CAMEL_TASK_DONE' in user_response.msg.content:\n",+ " break\n",+ "\n",+ " # Get the input message for the next round\n",+ " input_msg = assistant_response.msg\n",+ "\n",+ " return None"+ ],+ "metadata": {+ "id": "jqlKDNUwfcfp"+ },+ "execution_count": 13,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "Now let's set our code in motion:"+ ],+ "metadata": {+ "id": "TaiQJLt7ffKy"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "run(society)"+ ],+ "metadata": {+ "id": "lSSF_RsPffjh"+ },+ "execution_count": null,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "In this setting, the `AI User` and `AI Assistant` will generate different options when responding (you can simply change the `temperature` in `model_config` to somewhat control the diversity). `AI Critic` will respond with its option selection and reasoning; such additional context will be fed to the two other agents and help them form better subsequent responses."+ ],+ "metadata": {+ "id": "8e1bo7sHfkEo"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "## Remarks\n",+ "While we see some performance gains from critic-in-the-loop, it may not really solve the fundamental extrapolation problem (and [self-consistency](https://arxiv.org/abs/2203.11171) remains a strong baseline for many tasks). It is debatable if those agents can extrapolate by self-play within its current scale. A more practical question is how we may *efficiently* introduce *informative* feedbacks/rewards, when agents are connected with external environments and are endowed with tools and memories. They are expected to have a good world model and know how to make abstraction and analogy when necessary. Stay tuned for our next update."+ ],+ "metadata": {+ "id": "v4YaF8I7fmOt"+ }+ }+ ]+}\ No newline at end of filediff --git a/docs/cookbooks/embodied_agents.ipynb b/docs/cookbooks/embodied_agents.ipynbnew file mode 100644index 000000000..b092b670d--- /dev/null+++ b/docs/cookbooks/embodied_agents.ipynb@@ -0,0 +1,520 @@+{+ "nbformat": 4,+ "nbformat_minor": 0,+ "metadata": {+ "colab": {+ "provenance": []+ },+ "kernelspec": {+ "name": "python3",+ "display_name": "Python 3"+ },+ "language_info": {+ "name": "python"+ }+ },+ "cells": [+ {+ "cell_type": "markdown",+ "source": [+ "# Embodied Agents"+ ],+ "metadata": {+ "id": "APw8wDolb0L9"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "You can also check this cookbook in colab [here](https://colab.research.google.com/drive/17qCB6ezYfva87dNWlGA3D3zQ20NI-Sfk?usp=sharing)"+ ],+ "metadata": {+ "id": "vLCfmNtRb-jR"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "## Philosophical Bits\n",+ "\n",+ "We believe the essence of intelligence emerges from its dynamic interactions with the external environment, where the use of various tools becomes a pivotal factor in its development and manifestation.\n",+ "\n",+ "The `EmbodiedAgent()` in CAMEL is an advanced conversational agent that leverages **code interpreters** and **tool agents** (*e.g.*, `HuggingFaceToolAgent()`) to execute diverse tasks efficiently. This agent represents a blend of advanced programming and AI capabilities, and is able to interact and respond within a dynamic environment."+ ],+ "metadata": {+ "id": "jHQhWNnhcOch"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "## Quick Start\n",+ "Let's first play with a `ChatAgent` instance by simply initialize it with a system message and interact with user messages."+ ],+ "metadata": {+ "id": "VUaGurDIVJBg"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "### 🕹 Step 0: Prepartions"+ ],+ "metadata": {+ "id": "u9NVFz-HVLXb"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "%pip install \"camel-ai==0.2.1\""+ ],+ "metadata": {+ "id": "UtcC3c-KVZmU"+ },+ "execution_count": null,+ "outputs": []+ },+ {+ "cell_type": "code",+ "source": [+ "from camel.agents import EmbodiedAgent\n",+ "from camel.generators import SystemMessageGenerator as sys_msg_gen\n",+ "from camel.messages import BaseMessage as bm\n",+ "from camel.types import RoleType"+ ],+ "metadata": {+ "id": "CmgKGeCxVON-"+ },+ "execution_count": 3,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "### Setting Up API Keys"+ ],+ "metadata": {+ "id": "MyTTCe3IR_Lr"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "You'll need to set up your API keys for OpenAI."+ ],+ "metadata": {+ "id": "REqzgGL9SEaD"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "import os\n",+ "from getpass import getpass\n",+ "\n",+ "# Prompt for the API key securely\n",+ "openai_api_key = getpass('Enter your API key: ')\n",+ "os.environ[\"OPENAI_API_KEY\"] = openai_api_key"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "PNBFEXc-R-0s",+ "outputId": "e79eb379-4a5d-45b5-b591-2a1cd8612bbb"+ },+ "execution_count": 4,+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Enter your API key: ··········\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "### 🕹 Step 1: Define the Role\n",+ "We first need to set up the necessary information."+ ],+ "metadata": {+ "id": "wcetZrjEcyo_"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "# Set the role name and the task\n",+ "role = 'Programmer'\n",+ "task = 'Writing and executing codes.'\n",+ "\n",+ "# Create the meta_dict and the role_tuple\n",+ "meta_dict = dict(role=role, task=task)\n",+ "role_tuple = (role, RoleType.EMBODIMENT)"+ ],+ "metadata": {+ "id": "i-pIc9eTc0SH"+ },+ "execution_count": 5,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "The `meta_dict` and `role_type` will be used to generate the system message.\n"+ ],+ "metadata": {+ "id": "Lf6oJvsQc3lj"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "# Generate the system message based on this\n",+ "sys_msg = sys_msg_gen().from_dict(meta_dict=meta_dict,\n",+ " role_tuple=role_tuple)"+ ],+ "metadata": {+ "id": "yA62jAfDc5CK"+ },+ "execution_count": 6,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "### 🕹 Step 2: Initialize the Agent 🐫\n",+ "Based on the system message, we are ready to initialize our embodied agent."+ ],+ "metadata": {+ "id": "BEUEpNa_c8sS"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "embodied_agent = EmbodiedAgent(system_message=sys_msg,\n",+ " tool_agents=None,\n",+ " code_interpreter=None,\n",+ " verbose=True)"+ ],+ "metadata": {+ "id": "VetPjL70c9be"+ },+ "execution_count": 7,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "Be aware that the default argument values for `tool_agents` and `code_interpreter` are `None`, and the underlying code interpreter is using the `SubProcessInterpreter()`, which handles the execution of code in Python and Bash within a subprocess."+ ],+ "metadata": {+ "id": "o6aDvI1qc_kH"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "### 🕹 Step 3: Interact with the Agent with `.step()`\n",+ "Use the base message wrapper to generate the user message."+ ],+ "metadata": {+ "id": "MXzNaWp9dCvo"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "usr_msg = bm.make_user_message(\n",+ " role_name='user',\n",+ " content=('1. write a bash script to install numpy. '\n",+ " '2. then write a python script to compute '\n",+ " 'the dot product of [8, 9] and [5, 4], '\n",+ " 'and print the result. '\n",+ " '3. then write a script to search for '\n",+ " 'the weather at london with wttr.in/london.'))"+ ],+ "metadata": {+ "id": "Ts52u_UVdDJA"+ },+ "execution_count": 8,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "And feed that into your agents:"+ ],+ "metadata": {+ "id": "BlHF6LkRdFLo"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "response = embodied_agent.step(usr_msg)"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "6hKpSzssdGvc",+ "outputId": "38de4086-5271-4abb-e2e3-f5112aafe492"+ },+ "execution_count": 9,+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "\u001b[35m> Explanation:\n",+ "To accomplish the tasks you've outlined, I will perform the following actions:\n",+ "\n",+ "1. **Create a Bash script** to install NumPy using pip. This will ensure that the NumPy library is available for use in Python scripts.\n",+ "2. **Create a Python script** that computes the dot product of two vectors, `[8, 9]` and `[5, 4]`, and prints the result. The dot product is a common operation in linear algebra and can be computed using NumPy.\n",+ "3. **Create a Bash script** to fetch the weather information for London using the `curl` command to access the `wttr.in` service.\n",+ "\n",+ "### Step 1: Bash Script to Install NumPy\n",+ "\n",+ "The Bash script will use `pip` to install NumPy. Here’s the code for that:\n",+ "\n",+ "\u001b[35m> Code:\n",+ "#!/bin/bash\n",+ "# install_numpy.sh\n",+ "echo \"Installing NumPy...\"\n",+ "pip install numpy\n",+ "\n",+ "\u001b[35m> Explanation:\n",+ "### Step 2: Python Script for Dot Product\n",+ "\n",+ "The Python script will use NumPy to compute the dot product of the two vectors. Here’s the code for that:\n",+ "\n",+ "\u001b[35m> Code:\n",+ "# dot_product.py\n",+ "import numpy as np\n",+ "\n",+ "# Define the vectors\n",+ "vector_a = np.array([8, 9])\n",+ "vector_b = np.array([5, 4])\n",+ "\n",+ "# Compute the dot product\n",+ "dot_product = np.dot(vector_a, vector_b)\n",+ "\n",+ "# Print the result\n",+ "print(\"The dot product of\", vector_a.tolist(), \"and\", vector_b.tolist(), \"is:\", dot_product)\n",+ "\n",+ "\u001b[35m> Explanation:\n",+ "### Step 3: Bash Script to Fetch Weather Information\n",+ "\n",+ "The Bash script will use `curl` to get the weather information for London from `wttr.in`. Here’s the code for that:\n",+ "\n",+ "\u001b[35m> Code:\n",+ "#!/bin/bash\n",+ "# get_weather.sh\n",+ "echo \"Fetching weather information for London...\"\n",+ "curl wttr.in/London\n",+ "\n",+ "\u001b[35m> Explanation:\n",+ "### Summary of Actions\n",+ "\n",+ "1. Create a Bash script named `install_numpy.sh` to install NumPy.\n",+ "2. Create a Python script named `dot_product.py` to compute and print the dot product of the vectors.\n",+ "3. Create a Bash script named `get_weather.sh` to fetch and display the weather for London.\n",+ "\n",+ "Now, I will write the code for each of these scripts. \n",+ "\n",+ "### Code Implementation\n",+ "\n",+ "\u001b[35m> Code:\n",+ "# Create install_numpy.sh\n",+ "echo '#!/bin/bash' > install_numpy.sh\n",+ "echo 'echo \"Installing NumPy...\"' >> install_numpy.sh\n",+ "echo 'pip install numpy' >> install_numpy.sh\n",+ "chmod +x install_numpy.sh\n",+ "\n",+ "# Create dot_product.py\n",+ "echo 'import numpy as np' > dot_product.py\n",+ "echo 'vector_a = np.array([8, 9])' >> dot_product.py\n",+ "echo 'vector_b = np.array([5, 4])' >> dot_product.py\n",+ "echo 'dot_product = np.dot(vector_a, vector_b)' >> dot_product.py\n",+ "echo 'print(\"The dot product of\", vector_a.tolist(), \"and\", vector_b.tolist(), \"is:\", dot_product)' >> dot_product.py\n",+ "\n",+ "# Create get_weather.sh\n",+ "echo '#!/bin/bash' > get_weather.sh\n",+ "echo 'echo \"Fetching weather information for London...\"' >> get_weather.sh\n",+ "echo 'curl wttr.in/London' >> get_weather.sh\n",+ "chmod +x get_weather.sh\n",+ "\n",+ "\u001b[35m> Explanation:\n",+ "### Execution\n",+ "\n",+ "1. Run the `install_numpy.sh` script to install NumPy.\n",+ "2. Run the `dot_product.py` script to compute and print the dot product.\n",+ "3. Run the `get_weather.sh` script to fetch and display the weather for London.\n",+ "\n",+ "Let me know if you would like me to execute any of these scripts or if you need further assistance!\n",+ "\n",+ "The following bash code will run on your computer:\n",+ "\u001b[36m#!/bin/bash\n",+ "# install_numpy.sh\n",+ "echo \"Installing NumPy...\"\n",+ "pip install numpy\u001b[39m\n",+ "Running code? [Y/n]:y\n",+ "The following python code will run on your computer:\n",+ "\u001b[36m# dot_product.py\n",+ "import numpy as np\n",+ "\n",+ "# Define the vectors\n",+ "vector_a = np.array([8, 9])\n",+ "vector_b = np.array([5, 4])\n",+ "\n",+ "# Compute the dot product\n",+ "dot_product = np.dot(vector_a, vector_b)\n",+ "\n",+ "# Print the result\n",+ "print(\"The dot product of\", vector_a.tolist(), \"and\", vector_b.tolist(), \"is:\", dot_product)\u001b[39m\n",+ "Running code? [Y/n]:y\n",+ "The following bash code will run on your computer:\n",+ "\u001b[36m#!/bin/bash\n",+ "# get_weather.sh\n",+ "echo \"Fetching weather information for London...\"\n",+ "curl wttr.in/London\u001b[39m\n",+ "Running code? [Y/n]:y\n",+ "======stderr======\n",+ "\u001b[31m % Total % Received % Xferd Average Speed Time Time Time Current\n",+ " Dload Upload Total Spent Left Speed\n",+ "\n",+ " 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0\n",+ " 0 0 0 0 0 0 0 0 --:--:-- 0:00:01 --:--:-- 0\n",+ " 0 0 0 0 0 0 0 0 --:--:-- 0:00:02 --:--:-- 0\n",+ "100 8977 100 8977 0 0 3495 0 0:00:02 0:00:02 --:--:-- 3495\n",+ "\u001b[39m\n",+ "==================\n",+ "The following bash code will run on your computer:\n",+ "\u001b[36m# Create install_numpy.sh\n",+ "echo '#!/bin/bash' > install_numpy.sh\n",+ "echo 'echo \"Installing NumPy...\"' >> install_numpy.sh\n",+ "echo 'pip install numpy' >> install_numpy.sh\n",+ "chmod +x install_numpy.sh\n",+ "\n",+ "# Create dot_product.py\n",+ "echo 'import numpy as np' > dot_product.py\n",+ "echo 'vector_a = np.array([8, 9])' >> dot_product.py\n",+ "echo 'vector_b = np.array([5, 4])' >> dot_product.py\n",+ "echo 'dot_product = np.dot(vector_a, vector_b)' >> dot_product.py\n",+ "echo 'print(\"The dot product of\", vector_a.tolist(), \"and\", vector_b.tolist(), \"is:\", dot_product)' >> dot_product.py\n",+ "\n",+ "# Create get_weather.sh\n",+ "echo '#!/bin/bash' > get_weather.sh\n",+ "echo 'echo \"Fetching weather information for London...\"' >> get_weather.sh\n",+ "echo 'curl wttr.in/London' >> get_weather.sh\n",+ "chmod +x get_weather.sh\u001b[39m\n",+ "Running code? [Y/n]:y\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "Under the hood, the agent will perform multiple actions within its action space in the OS to fulfill the user request. It will compose code to implement the action – no worries, it will ask for your permission before execution.\n",+ "\n",+ "Ideally you should get the output similar to this, if you allow the agent to perform actions:"+ ],+ "metadata": {+ "id": "rP4Zma5ddJxh"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "print(response.msg.content)"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "qA0bpOFldKPV",+ "outputId": "421418d2-61ca-4c65-f08e-83038c50a85a"+ },+ "execution_count": 10,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "1. write a bash script to install numpy. 2. then write a python script to compute the dot product of [8, 9] and [5, 4], and print the result. 3. then write a script to search for the weather at london with wttr.in/london.\n",+ "> Embodied Actions:\n",+ "\n",+ "> Executed Results:\n",+ "Executing code block 0: {\n",+ "Installing NumPy...\n",+ "Requirement already satisfied: numpy in /usr/local/lib/python3.10/dist-packages (1.26.4)\n",+ "}\n",+ "Executing code block 1: {\n",+ "The dot product of [8, 9] and [5, 4] is: 76\n",+ "}\n",+ "Executing code block 2: {\n",+ "Fetching weather information for London...\n",+ "Weather report: London\n",+ "\n",+ " \u001b[38;5;250m .-. \u001b[0m Light rain shower\n",+ " \u001b[38;5;250m ( ). \u001b[0m \u001b[38;5;118m15\u001b[0m °C\u001b[0m \n",+ " \u001b[38;5;250m (___(__) \u001b[0m \u001b[1m↗\u001b[0m \u001b[38;5;190m12\u001b[0m km/h\u001b[0m \n",+ " \u001b[38;5;111m ‘ ‘ ‘ ‘ \u001b[0m 3 km\u001b[0m \n",+ " \u001b[38;5;111m ‘ ‘ ‘ ‘ \u001b[0m 3.4 mm\u001b[0m \n",+ " ┌─────────────┐ \n",+ "┌──────────────────────────────┬───────────────────────┤ Thu 26 Sep ├───────────────────────┬──────────────────────────────┐\n",+ "│ Morning │ Noon └──────┬──────┘ Evening │ Night │\n",+ "├──────────────────────────────┼──────────────────────────────┼──────────────────────────────┼──────────────────────────────┤\n",+ "│ \u001b[38;5;226m _`/\"\"\u001b[38;5;250m.-. \u001b[0m Patchy light d…│ \u001b[38;5;226m _`/\"\"\u001b[38;5;250m.-. \u001b[0m Patchy light d…│ \u001b[38;5;226m _`/\"\"\u001b[38;5;250m.-. \u001b[0m Light rain sho…│ \u001b[38;5;226m _`/\"\"\u001b[38;5;250m.-. \u001b[0m Patchy rain ne…│\n",+ "│ \u001b[38;5;226m ,\\_\u001b[38;5;250m( ). \u001b[0m \u001b[38;5;154m16\u001b[0m °C\u001b[0m │ \u001b[38;5;226m ,\\_\u001b[38;5;250m( ). \u001b[0m \u001b[38;5;154m17\u001b[0m °C\u001b[0m │ \u001b[38;5;226m ,\\_\u001b[38;5;250m( ). \u001b[0m \u001b[38;5;118m+14\u001b[0m(\u001b[38;5;082m12\u001b[0m) °C\u001b[0m │ \u001b[38;5;226m ,\\_\u001b[38;5;250m( ). \u001b[0m \u001b[38;5;082m+12\u001b[0m(\u001b[38;5;082m10\u001b[0m) °C\u001b[0m │\n",+ "│ \u001b[38;5;226m /\u001b[38;5;250m(___(__) \u001b[0m \u001b[1m↗\u001b[0m \u001b[38;5;220m19\u001b[0m-\u001b[38;5;208m24\u001b[0m km/h\u001b[0m │ \u001b[38;5;226m /\u001b[38;5;250m(___(__) \u001b[0m \u001b[1m↗\u001b[0m \u001b[38;5;214m20\u001b[0m-\u001b[38;5;214m23\u001b[0m km/h\u001b[0m │ \u001b[38;5;226m /\u001b[38;5;250m(___(__) \u001b[0m \u001b[1m↗\u001b[0m \u001b[38;5;214m23\u001b[0m-\u001b[38;5;196m35\u001b[0m km/h\u001b[0m │ \u001b[38;5;226m /\u001b[38;5;250m(___(__) \u001b[0m \u001b[1m↗\u001b[0m \u001b[38;5;214m20\u001b[0m-\u001b[38;5;202m29\u001b[0m km/h\u001b[0m │\n",+ "│ \u001b[38;5;111m ‘ ‘ ‘ ‘ \u001b[0m 5 km\u001b[0m │ \u001b[38;5;111m ‘ ‘ ‘ ‘ \u001b[0m 5 km\u001b[0m │ \u001b[38;5;111m ‘ ‘ ‘ ‘ \u001b[0m 10 km\u001b[0m │ \u001b[38;5;111m ‘ ‘ ‘ ‘ \u001b[0m 10 km\u001b[0m │\n",+ "│ \u001b[38;5;111m ‘ ‘ ‘ ‘ \u001b[0m 0.5 mm | 100%\u001b[0m │ \u001b[38;5;111m ‘ ‘ ‘ ‘ \u001b[0m 0.2 mm | 100%\u001b[0m │ \u001b[38;5;111m ‘ ‘ ‘ ‘ \u001b[0m 0.6 mm | 100%\u001b[0m │ \u001b[38;5;111m ‘ ‘ ‘ ‘ \u001b[0m 0.0 mm | 65%\u001b[0m │\n",+ "└──────────────────────────────┴──────────────────────────────┴──────────────────────────────┴──────────────────────────────┘\n",+ " ┌─────────────┐ \n",+ "┌──────────────────────────────┬───────────────────────┤ Fri 27 Sep ├───────────────────────┬──────────────────────────────┐\n",+ "│ Morning │ Noon └──────┬──────┘ Evening │ Night │\n",+ "├──────────────────────────────┼──────────────────────────────┼──────────────────────────────┼──────────────────────────────┤\n",+ "│ \u001b[38;5;250m .-. \u001b[0m Light rain │ \u001b[38;5;226m _`/\"\"\u001b[38;5;250m.-. \u001b[0m Patchy rain ne…│ \u001b[38;5;226m \\ / \u001b[0m Sunny │ \u001b[38;5;226m \\ / \u001b[0m Clear │\n",+ "│ \u001b[38;5;250m ( ). \u001b[0m \u001b[38;5;046m+9\u001b[0m(\u001b[38;5;047m7\u001b[0m) °C\u001b[0m │ \u001b[38;5;226m ,\\_\u001b[38;5;250m( ). \u001b[0m \u001b[38;5;082m+11\u001b[0m(\u001b[38;5;046m9\u001b[0m) °C\u001b[0m │ \u001b[38;5;226m .-. \u001b[0m \u001b[38;5;082m+11\u001b[0m(\u001b[38;5;046m8\u001b[0m) °C\u001b[0m │ \u001b[38;5;226m .-. \u001b[0m \u001b[38;5;046m+9\u001b[0m(\u001b[38;5;046m8\u001b[0m) °C\u001b[0m │\n",+ "│ \u001b[38;5;250m (___(__) \u001b[0m \u001b[1m↘\u001b[0m \u001b[38;5;220m18\u001b[0m-\u001b[38;5;208m26\u001b[0m km/h\u001b[0m │ \u001b[38;5;226m /\u001b[38;5;250m(___(__) \u001b[0m \u001b[1m↘\u001b[0m \u001b[38;5;214m23\u001b[0m-\u001b[38;5;202m31\u001b[0m km/h\u001b[0m │ \u001b[38;5;226m ― ( ) ― \u001b[0m \u001b[1m↘\u001b[0m \u001b[38;5;220m16\u001b[0m-\u001b[38;5;208m24\u001b[0m km/h\u001b[0m │ \u001b[38;5;226m ― ( ) ― \u001b[0m \u001b[1m↘\u001b[0m \u001b[38;5;190m10\u001b[0m-\u001b[38;5;220m16\u001b[0m km/h\u001b[0m │\n",+ "│ \u001b[38;5;111m ‘ ‘ ‘ ‘ \u001b[0m 9 km\u001b[0m │ \u001b[38;5;111m ‘ ‘ ‘ ‘ \u001b[0m 10 km\u001b[0m │ \u001b[38;5;226m `-’ \u001b[0m 10 km\u001b[0m │ \u001b[38;5;226m `-’ \u001b[0m 10 km\u001b[0m │\n",+ "│ \u001b[38;5;111m ‘ ‘ ‘ ‘ \u001b[0m 0.8 mm | 100%\u001b[0m │ \u001b[38;5;111m ‘ ‘ ‘ ‘ \u001b[0m 0.1 mm | 100%\u001b[0m │ \u001b[38;5;226m / \\ \u001b[0m 0.0 mm | 0%\u001b[0m │ \u001b[38;5;226m / \\ \u001b[0m 0.0 mm | 0%\u001b[0m │\n",+ "└──────────────────────────────┴──────────────────────────────┴──────────────────────────────┴──────────────────────────────┘\n",+ " ┌─────────────┐ \n",+ "┌──────────────────────────────┬───────────────────────┤ Sat 28 Sep ├───────────────────────┬──────────────────────────────┐\n",+ "│ Morning │ Noon └──────┬──────┘ Evening │ Night │\n",+ "├──────────────────────────────┼──────────────────────────────┼──────────────────────────────┼──────────────────────────────┤\n",+ "│ \u001b[38;5;226m \\ / \u001b[0m Sunny │ \u001b[38;5;226m _`/\"\"\u001b[38;5;250m.-. \u001b[0m Patchy rain ne…│ Cloudy │ \u001b[38;5;226m \\ /\u001b[0m Partly Cloudy │\n",+ "│ \u001b[38;5;226m .-. \u001b[0m \u001b[38;5;082m+11\u001b[0m(\u001b[38;5;046m9\u001b[0m) °C\u001b[0m │ \u001b[38;5;226m ,\\_\u001b[38;5;250m( ). \u001b[0m \u001b[38;5;118m+14\u001b[0m(\u001b[38;5;118m13\u001b[0m) °C\u001b[0m │ \u001b[38;5;250m .--. \u001b[0m \u001b[38;5;118m13\u001b[0m °C\u001b[0m │ \u001b[38;5;226m _ /\"\"\u001b[38;5;250m.-. \u001b[0m \u001b[38;5;082m12\u001b[0m °C\u001b[0m │\n",+ "│ \u001b[38;5;226m ― ( ) ― \u001b[0m \u001b[1m→\u001b[0m \u001b[38;5;190m11\u001b[0m-\u001b[38;5;226m14\u001b[0m km/h\u001b[0m │ \u001b[38;5;226m /\u001b[38;5;250m(___(__) \u001b[0m \u001b[1m→\u001b[0m \u001b[38;5;190m12\u001b[0m-\u001b[38;5;226m14\u001b[0m km/h\u001b[0m │ \u001b[38;5;250m .-( ). \u001b[0m \u001b[1m→\u001b[0m \u001b[38;5;118m6\u001b[0m-\u001b[38;5;190m10\u001b[0m km/h\u001b[0m │ \u001b[38;5;226m \\_\u001b[38;5;250m( ). \u001b[0m \u001b[1m↗\u001b[0m \u001b[38;5;118m5\u001b[0m-\u001b[38;5;154m8\u001b[0m km/h\u001b[0m │\n",+ "│ \u001b[38;5;226m `-’ \u001b[0m 10 km\u001b[0m │ \u001b[38;5;111m ‘ ‘ ‘ ‘ \u001b[0m 10 km\u001b[0m │ \u001b[38;5;250m (___.__)__) \u001b[0m 10 km\u001b[0m │ \u001b[38;5;226m /\u001b[38;5;250m(___(__) \u001b[0m 10 km\u001b[0m │\n",+ "│ \u001b[38;5;226m / \\ \u001b[0m 0.0 mm | 0%\u001b[0m │ \u001b[38;5;111m ‘ ‘ ‘ ‘ \u001b[0m 0.1 mm | 100%\u001b[0m │ 0.0 mm | 0%\u001b[0m │ 0.0 mm | 0%\u001b[0m │\n",+ "└──────────────────────────────┴──────────────────────────────┴──────────────────────────────┴──────────────────────────────┘\n",+ "Location: London, Greater London, England, UK [51.5073219,-0.1276474]\n",+ "\n",+ "Follow \u001b[46m\u001b[30m@igor_chubin\u001b[0m for wttr.in updates\n",+ "(stderr: % Total % Received % Xferd Average Speed Time Time Time Current\n",+ " Dload Upload Total Spent Left Speed\n",+ "\n",+ " 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0\n",+ " 0 0 0 0 0 0 0 0 --:--:-- 0:00:01 --:--:-- 0\n",+ " 0 0 0 0 0 0 0 0 --:--:-- 0:00:02 --:--:-- 0\n",+ "100 8977 100 8977 0 0 3495 0 0:00:02 0:00:02 --:--:-- 3495\n",+ ")}\n",+ "Executing code block 3: {\n",+ "}\n",+ "\n"+ ]+ }+ ]+ }+ ]+}\ No newline at end of filediff --git a/docs/cookbooks/knowledge_graph.ipynb b/docs/cookbooks/knowledge_graph.ipynbindex 146408a25..b1bf9c20f 100644--- a/docs/cookbooks/knowledge_graph.ipynb+++ b/docs/cookbooks/knowledge_graph.ipynb@@ -1,81 +1,68 @@{- "nbformat": 4,- "nbformat_minor": 0,- "metadata": {- "colab": {- "provenance": []- },- "kernelspec": {- "name": "python3",- "display_name": "Python 3"- },- "language_info": {- "name": "python"- }- },"cells": [{+ "attachments": {},"cell_type": "markdown",- "source": [- "# 🐫 Using CAMEL to Do Graph RAG with Mistral Models"- ],"metadata": {"id": "DJeeABnkOsPK"- }+ },+ "source": [+ "# Using CAMEL to Do Graph RAG with Mistral Models"+ ]},{"cell_type": "markdown",- "source": [- "You can also check this cookbook in colab [here](https://colab.research.google.com/drive/1uZKQSuu0qW6ukkuSv9TukLB9bVaS1H0U?usp=sharing)"- ],"metadata": {"id": "9fHzgxYpmz2q"- }+ },+ "source": [+ "You can also check this cookbook in colab [here](https://colab.research.google.com/drive/1uZKQSuu0qW6ukkuSv9TukLB9bVaS1H0U?usp=sharing)"+ ]},{"cell_type": "markdown",- "source": [- "This cookbook walks you through the process of performing graph-based Retrieval-Augmented Generation (RAG) using **CAMEL**, powered by the advanced **Mistral** models. Specifically, we'll utilize the **Mistral Large 2** model to extract and structure knowledge from a given content source, and store this information in a **Neo4j** graph database. Subsequently, we can leverage a hybrid approach, combining vector retrieval and knowledge graph retrieval, to query and explore the stored knowledge."- ],"metadata": {"id": "l4VANToobUzu"- }+ },+ "source": [+ "This cookbook walks you through the process of performing graph-based Retrieval-Augmented Generation (RAG) using **CAMEL**, powered by the advanced **Mistral** models. Specifically, we'll utilize the **Mistral Large 2** model to extract and structure knowledge from a given content source, and store this information in a **Neo4j** graph database. Subsequently, we can leverage a hybrid approach, combining vector retrieval and knowledge graph retrieval, to query and explore the stored knowledge."+ ]},{"cell_type": "markdown",- "source": [- ""- ],"metadata": {"id": "slaeSyWkbIzc"- }+ },+ "source": [+ ""+ ]},{"cell_type": "markdown",- "source": [- ""- ],"metadata": {"id": "X5mWln9dCDzE"- }+ },+ "source": [+ ""+ ]},{"cell_type": "markdown",- "source": [- "## 📦 Installation"- ],"metadata": {"id": "8SV7XmyKbwdc"- }+ },+ "source": [+ "## 📦 Installation"+ ]},{"cell_type": "markdown",- "source": [- "First, install the CAMEL package with all its dependencies:"- ],"metadata": {"id": "-qAA1j0Sb2Ve"- }+ },+ "source": [+ "First, install the CAMEL package with all its dependencies:"+ ]},{"cell_type": "code",@@ -85,28 +72,35 @@"id": "os7Mcfw2Svww"},"outputs": [],- "source": "%pip install \"camel-ai[all]==0.2.1\""+ "source": [+ "%pip install \"camel-ai[all]==0.2.1\""+ ]},{"cell_type": "markdown",- "source": [- "## 🔧 Setup"- ],"metadata": {"id": "X5SDX1kPb6bz"- }+ },+ "source": [+ "## 🔧 Setup"+ ]},{"cell_type": "markdown",- "source": [- "Import the required modules from CAMEL-AI:"- ],"metadata": {"id": "StvpXTi7b7pF"- }+ },+ "source": [+ "Import the required modules from CAMEL-AI:"+ ]},{"cell_type": "code",+ "execution_count": 2,+ "metadata": {+ "id": "7PcVsBYvzfSI"+ },+ "outputs": [],"source": ["from camel.models import ModelFactory\n","from camel.types import ModelPlatformType, ModelType\n",@@ -118,41 +112,29 @@"from camel.types import StorageType\n","from camel.agents import ChatAgent, KnowledgeGraphAgent\n","from camel.messages import BaseMessage"- ],- "metadata": {- "id": "7PcVsBYvzfSI"- },- "execution_count": 2,- "outputs": []+ ]},{"cell_type": "markdown",- "source": [- "## 🔑 Setting Up API Keys\n"- ],"metadata": {"id": "DahHkqSOb-T3"- }+ },+ "source": [+ "## 🔑 Setting Up API Keys\n"+ ]},{"cell_type": "markdown",- "source": [- "For secure access to Mistral AI's services, we'll prompt for the API key."- ],"metadata": {"id": "odHOpz0XcAjA"- }+ },+ "source": [+ "For secure access to Mistral AI's services, we'll prompt for the API key."+ ]},{"cell_type": "code",- "source": [- "import os\n",- "from getpass import getpass\n",- "\n",- "# Prompt for the API key securely\n",- "mistral_api_key = getpass('Enter your API key: ')\n",- "os.environ[\"MISTRAL_API_KEY\"] = mistral_api_key"- ],+ "execution_count": 3,"metadata": {"colab": {"base_uri": "https://localhost:8080/"@@ -160,7 +142,6 @@"id": "B0v7xEFFoabv","outputId": "f343482c-435d-496d-dfa2-fc65014e39c8"},- "execution_count": 3,"outputs": [{"name": "stdout",@@ -169,28 +150,41 @@"Enter your API key: ··········\n"]}+ ],+ "source": [+ "import os\n",+ "from getpass import getpass\n",+ "\n",+ "# Prompt for the API key securely\n",+ "mistral_api_key = getpass('Enter your API key: ')\n",+ "os.environ[\"MISTRAL_API_KEY\"] = mistral_api_key"]},{"cell_type": "markdown",- "source": [- "## 🗄️ Configuring Neo4j Graph Database"- ],"metadata": {"id": "bPPZx6WwcDzG"- }+ },+ "source": [+ "## 🗄️ Configuring Neo4j Graph Database"+ ]},{"cell_type": "markdown",- "source": [- "Set up your Neo4j instance by providing the URL, username, and password, [here](https://neo4j.com/docs/aura/auradb/getting-started/create-database/) is the guidance, check your credentials in the downloaded .txt file. Note that you may need to wait up to 60 seconds if the instance has just been set up."- ],"metadata": {"id": "m4pJ-V2FcG6o"- }+ },+ "source": [+ "Set up your Neo4j instance by providing the URL, username, and password, [here](https://neo4j.com/docs/aura/auradb/getting-started/create-database/) is the guidance, check your credentials in the downloaded .txt file. Note that you may need to wait up to 60 seconds if the instance has just been set up."+ ]},{"cell_type": "code",+ "execution_count": 4,+ "metadata": {+ "id": "iH7NuLvq3p2o"+ },+ "outputs": [],"source": ["# Set Neo4j instance\n","n4j = Neo4jGraph(\n",@@ -198,33 +192,33 @@" username=\"Your_Username\",\n"," password=\"Your_Password\",\n",")"- ],- "metadata": {- "id": "iH7NuLvq3p2o"- },- "execution_count": 4,- "outputs": []+ ]},{"cell_type": "markdown",- "source": [- "## 🧠 Creating the Model"- ],"metadata": {"id": "vmzruZl1cJQD"- }+ },+ "source": [+ "## 🧠 Creating the Model"+ ]},{"cell_type": "markdown",- "source": [- "Set up Mistral Large 2 model using the CAMEL ModelFactory:"- ],"metadata": {"id": "flTRxefgcOxp"- }+ },+ "source": [+ "Set up Mistral Large 2 model using the CAMEL ModelFactory:"+ ]},{"cell_type": "code",+ "execution_count": 5,+ "metadata": {+ "id": "PDhfqzA2zYmm"+ },+ "outputs": [],"source": ["# Set up model\n","mistral_large_2 = ModelFactory.create(\n",@@ -232,83 +226,83 @@" model_type=ModelType.MISTRAL_LARGE,\n"," model_config_dict=MistralConfig(temperature=0.2).as_dict(),\n",")"- ],- "metadata": {- "id": "PDhfqzA2zYmm"- },- "execution_count": 5,- "outputs": []+ ]},{"cell_type": "code",- "source": [- "# You can also set up model locally by using ollama\n",- "mistral_large_2_local = ModelFactory.create(\n",- " model_platform=ModelPlatformType.OLLAMA,\n",- " model_type=\"mistral-large\",\n",- " model_config_dict=OllamaConfig(temperature=0.2).as_dict(),\n",- ")"- ],+ "execution_count": 6,"metadata": {- "id": "PPyHfsGyraJf","colab": {"base_uri": "https://localhost:8080/"},+ "id": "PPyHfsGyraJf","outputId": "134fd954-a1c4-4642-c3f7-911c5ae8e8a5"},- "execution_count": 6,"outputs": [{- "output_type": "stream","name": "stdout",+ "output_type": "stream","text": ["Failed to start Ollama server: [Errno 2] No such file or directory: 'ollama'.\n"]}+ ],+ "source": [+ "# You can also set up model locally by using ollama\n",+ "mistral_large_2_local = ModelFactory.create(\n",+ " model_platform=ModelPlatformType.OLLAMA,\n",+ " model_type=\"mistral-large\",\n",+ " model_config_dict=OllamaConfig(temperature=0.2).as_dict(),\n",+ ")"]},{"cell_type": "markdown",- "source": [- "## 🤖 Generate a Knowledge Graph Using CAMEL's Agent"- ],"metadata": {"id": "61PwBl9XcWJ_"- }+ },+ "source": [+ "## 🤖 Generate a Knowledge Graph Using CAMEL's Agent"+ ]},{"cell_type": "markdown",- "source": [- "Set up instances for knowledge graph agent:"- ],"metadata": {"id": "nFl_Paah4OdP"- }+ },+ "source": [+ "Set up instances for knowledge graph agent:"+ ]},{"cell_type": "code",+ "execution_count": 7,+ "metadata": {+ "id": "LkUn3Ph0S1Z0"+ },+ "outputs": [],"source": ["# Set instance\n","uio = UnstructuredIO()\n","kg_agent = KnowledgeGraphAgent(model=mistral_large_2)"- ],- "metadata": {- "id": "LkUn3Ph0S1Z0"- },- "execution_count": 7,- "outputs": []+ ]},{"cell_type": "markdown",- "source": [- "Provide an example text input that the knowledge graph agent will process:"- ],"metadata": {"id": "L7EUMC-nck0d"- }+ },+ "source": [+ "Provide an example text input that the knowledge graph agent will process:"+ ]},{"cell_type": "code",+ "execution_count": 8,+ "metadata": {+ "id": "syY548PW4d2t"+ },+ "outputs": [],"source": ["# Set example text input\n","text_example = \"\"\"\n",@@ -317,55 +311,45 @@"of extracting entities and relationships from given content and create knowledge\n","graphs automaticlly.\n","\"\"\""- ],- "metadata": {- "id": "syY548PW4d2t"- },- "execution_count": 8,- "outputs": []+ ]},{"cell_type": "markdown",- "source": [- "Create an element from the text and use the knowledge graph agent to extract node and relationship information:"- ],"metadata": {"id": "bKSxhv0ucof9"- }+ },+ "source": [+ "Create an element from the text and use the knowledge graph agent to extract node and relationship information:"+ ]},{"cell_type": "code",+ "execution_count": 9,+ "metadata": {+ "id": "cDB_iDCl4h6F"+ },+ "outputs": [],"source": ["# Create an element from given text\n","element_example = uio.create_element_from_text(\n"," text=text_example, element_id=\"0\"\n",")"- ],- "metadata": {- "id": "cDB_iDCl4h6F"- },- "execution_count": 9,- "outputs": []+ ]},{"cell_type": "code",- "source": [- "# Let Knowledge Graph Agent extract node and relationship information\n",- "ans_element = kg_agent.run(element_example, parse_graph_elements=False)\n",- "print(ans_element)"- ],+ "execution_count": 10,"metadata": {- "id": "WlmeLofo4kDE","colab": {"base_uri": "https://localhost:8080/"},+ "id": "WlmeLofo4kDE","outputId": "8df4fcaa-3195-421a-afc0-298062ff7843"},- "execution_count": 10,"outputs": [{- "output_type": "stream","name": "stdout",+ "output_type": "stream","text": ["Sure, let's extract nodes and relationships from the given content. Here's the content for extraction:\n","\n",@@ -441,92 +425,102 @@"This structured output represents the nodes and relationships extracted from the given content.\n"]}+ ],+ "source": [+ "# Let Knowledge Graph Agent extract node and relationship information\n",+ "ans_element = kg_agent.run(element_example, parse_graph_elements=False)\n",+ "print(ans_element)"]},{"cell_type": "code",- "source": [- "# Check graph element\n",- "graph_elements = kg_agent.run(element_example, parse_graph_elements=True)\n",- "print(graph_elements)"- ],+ "execution_count": 11,"metadata": {- "id": "J0JzGaFN4pRh","colab": {"base_uri": "https://localhost:8080/"},+ "id": "J0JzGaFN4pRh","outputId": "6f2064f2-dce1-4b26-a4dc-50ac9481c685"},- "execution_count": 11,"outputs": [{- "output_type": "stream","name": "stdout",+ "output_type": "stream","text": ["nodes=[Node(id='CAMEL', type='Organization', properties={'source': 'agent_created'}), Node(id='knowledge graph agent', type='Software', properties={'source': 'agent_created'}), Node(id='Mistral AI', type='Organization', properties={'source': 'agent_created'}), Node(id='Mistral Large 2', type='Model', properties={'source': 'agent_created'}), Node(id='entities', type='Concept', properties={'source': 'agent_created'}), Node(id='relationships', type='Concept', properties={'source': 'agent_created'}), Node(id='content', type='Concept', properties={'source': 'agent_created'}), Node(id='knowledge graphs', type='Concept', properties={'source': 'agent_created'})] relationships=[Relationship(subj=Node(id='CAMEL', type='Organization', properties={'source': 'agent_created'}), obj=Node(id='knowledge graph agent', type='Software', properties={'source': 'agent_created'}), type='Developed', properties={'source': 'agent_created'}), Relationship(subj=Node(id='knowledge graph agent', type='Software', properties={'source': 'agent_created'}), obj=Node(id='Mistral AI', type='Organization', properties={'source': 'agent_created'}), type='CanRunWith', properties={'source': 'agent_created'}), Relationship(subj=Node(id='Mistral AI', type='Organization', properties={'source': 'agent_created'}), obj=Node(id='Mistral Large 2', type='Model', properties={'source': 'agent_created'}), type='HasModel', properties={'source': 'agent_created'}), Relationship(subj=Node(id='knowledge graph agent', type='Software', properties={'source': 'agent_created'}), obj=Node(id='entities', type='Concept', properties={'source': 'agent_created'}), type='CanExtract', properties={'source': 'agent_created'}), Relationship(subj=Node(id='knowledge graph agent', type='Software', properties={'source': 'agent_created'}), obj=Node(id='relationships', type='Concept', properties={'source': 'agent_created'}), type='CanExtract', properties={'source': 'agent_created'}), Relationship(subj=Node(id='knowledge graph agent', type='Software', properties={'source': 'agent_created'}), obj=Node(id='knowledge graphs', type='Concept', properties={'source': 'agent_created'}), type='Creates', properties={'source': 'agent_created'})] source=<unstructured.documents.elements.Text object at 0x7f5d31a5f5b0>\n"]}+ ],+ "source": [+ "# Check graph element\n",+ "graph_elements = kg_agent.run(element_example, parse_graph_elements=True)\n",+ "print(graph_elements)"]},{"cell_type": "markdown",- "source": [- "Add the extracted graph elements to the Neo4j database:"- ],"metadata": {"id": "sqEfkLI-c23g"- }+ },+ "source": [+ "Add the extracted graph elements to the Neo4j database:"+ ]},{"cell_type": "code",- "source": [- "# Add the element to neo4j database\n",- "n4j.add_graph_elements(graph_elements=[graph_elements])"- ],+ "execution_count": 12,"metadata": {"id": "89ZF99QSAaGJ"},- "execution_count": 12,- "outputs": []+ "outputs": [],+ "source": [+ "# Add the element to neo4j database\n",+ "n4j.add_graph_elements(graph_elements=[graph_elements])"+ ]},{"cell_type": "markdown",- "source": [- "### 🎉 Now you can go to [here](https://workspace-preview.neo4j.io/connection/connect) to check the knowledge graph built with CAMEL's Knowledge Graph Agent and Mistral AI's Mistral Large 2 model!"- ],"metadata": {"id": "B6C8wSo6x27Z"- }+ },+ "source": [+ "### 🎉 Now you can go to [here](https://workspace-preview.neo4j.io/connection/connect) to check the knowledge graph built with CAMEL's Knowledge Graph Agent and Mistral AI's Mistral Large 2 model!"+ ]},{"cell_type": "markdown",- "source": [- "## 🗃️ Running Graph RAG with CAMEL"- ],"metadata": {"id": "LckRFGpN6Za4"- }+ },+ "source": [+ "## 🗃️ Running Graph RAG with CAMEL"+ ]},{"cell_type": "markdown",- "source": [- "*Next we will showcase how to run RAG in a hybrid approach, combining vector retrieval and knowledge graph retrieval, to query and explore the stored knowledge.*"- ],"metadata": {"id": "vh4jrhPSyaZw"- }+ },+ "source": [+ "*Next we will showcase how to run RAG in a hybrid approach, combining vector retrieval and knowledge graph retrieval, to query and explore the stored knowledge.*"+ ]},{"cell_type": "markdown",- "source": [- "Set up a vector retriever with local storage and embedding model from Mistral AI:"- ],"metadata": {"id": "A_MiPGmOeDN3"- }+ },+ "source": [+ "Set up a vector retriever with local storage and embedding model from Mistral AI:"+ ]},{"cell_type": "code",+ "execution_count": 13,+ "metadata": {+ "id": "AwpMPpvtr6O7"+ },+ "outputs": [],"source": ["# Set retriever\n","camel_retriever = AutoRetriever(\n",@@ -534,67 +528,52 @@" storage_type=StorageType.QDRANT,\n"," embedding_model=MistralEmbedding(),\n",")"- ],- "metadata": {- "id": "AwpMPpvtr6O7"- },- "execution_count": 13,- "outputs": []+ ]},{"cell_type": "markdown",- "source": [- "Provide an example user query:"- ],"metadata": {"id": "BpAPOf7VeFjx"- }+ },+ "source": [+ "Provide an example user query:"+ ]},{"cell_type": "code",- "source": [- "# Set one user query\n",- "query=\"what's the relationship between Mistral Large 2 and Mistral AI? What kind of feature does Mistral Large 2 has?\""- ],+ "execution_count": 14,"metadata": {"id": "PTZ-8nX359bb"},- "execution_count": 14,- "outputs": []+ "outputs": [],+ "source": [+ "# Set one user query\n",+ "query=\"what's the relationship between Mistral Large 2 and Mistral AI? What kind of feature does Mistral Large 2 has?\""+ ]},{"cell_type": "markdown",- "source": [- "Retrieve related content using the vector retriever, here we take Mistral AI's news in the website as example conetent, you can also set the local file path here:"- ],"metadata": {"id": "Yq6kGaEJeI53"- }+ },+ "source": [+ "Retrieve related content using the vector retriever, here we take Mistral AI's news in the website as example conetent, you can also set the local file path here:"+ ]},{"cell_type": "code",- "source": [- "# Get related content by using vector retriever\n",- "vector_result = camel_retriever.run_vector_retriever(\n",- " query=query,\n",- " contents=\"https://mistral.ai/news/mistral-large-2407/\",\n",- ")\n",- "\n",- "# Show the result from vector search\n",- "print(vector_result)"- ],+ "execution_count": 16,"metadata": {- "id": "hLQGgp4DJAlu","colab": {"base_uri": "https://localhost:8080/"},+ "id": "hLQGgp4DJAlu","outputId": "0bfe8fe6-c5dd-42a1-ff44-450c3cb62a5a"},- "execution_count": 16,"outputs": [{- "output_type": "stream","name": "stderr",+ "output_type": "stream","text": ["[nltk_data] Downloading package punkt to /root/nltk_data...\n","[nltk_data] Unzipping tokenizers/punkt.zip.\n",@@ -604,25 +583,40 @@]},{- "output_type": "stream","name": "stdout",+ "output_type": "stream","text": ["{'Original Query': \"what's the relationship between Mistral Large 2 and Mistral AI? What kind of feature does Mistral Large 2 has?\", 'Retrieved Context': ['Mistral Large 2 is designed for single-node inference with long-context applications in mind – its size of 123 billion parameters allows it to run at large throughput on a single node.\\nWe are releasing Mistral Large 2 under the Mistral Research License, that allows usage and modification for research and non-commercial usages. For commercial usage of Mistral Large 2 requiring self-deployment, a Mistral Commercial License must be acquired by contacting us.']}\n"]}+ ],+ "source": [+ "# Get related content by using vector retriever\n",+ "vector_result = camel_retriever.run_vector_retriever(\n",+ " query=query,\n",+ " contents=\"https://mistral.ai/news/mistral-large-2407/\",\n",+ ")\n",+ "\n",+ "# Show the result from vector search\n",+ "print(vector_result)"]},{"cell_type": "markdown",- "source": [- "Parse content from the specified URL and create knowledge graph data:"- ],"metadata": {"id": "w188PLzteMkw"- }+ },+ "source": [+ "Parse content from the specified URL and create knowledge graph data:"+ ]},{"cell_type": "code",+ "execution_count": 17,+ "metadata": {+ "id": "DyuusYoo5-Vw"+ },+ "outputs": [],"source": ["# Parse conetent from mistral website and create knowledge graph data by using\n","# the Knowledge Graph Agent, store the information into graph database.\n",@@ -639,24 +633,24 @@" graph_element = kg_agent.run(chunk, parse_graph_elements=True)\n"," n4j.add_graph_elements(graph_elements=[graph_element])\n"," graph_elements.append(graph_element)"- ],- "metadata": {- "id": "DyuusYoo5-Vw"- },- "execution_count": 17,- "outputs": []+ ]},{"cell_type": "markdown",- "source": [- "Create an element from the user query:"- ],"metadata": {"id": "1UgtR5UWeSD0"- }+ },+ "source": [+ "Create an element from the user query:"+ ]},{"cell_type": "code",+ "execution_count": 18,+ "metadata": {+ "id": "ZDYCLClxeT68"+ },+ "outputs": [],"source": ["# Create an element from user query\n","query_element = uio.create_element_from_text(\n",@@ -665,24 +659,36 @@"\n","# Let Knowledge Graph Agent extract node and relationship information from the qyery\n","ans_element = kg_agent.run(query_element, parse_graph_elements=True)"- ],- "metadata": {- "id": "ZDYCLClxeT68"- },- "execution_count": 18,- "outputs": []+ ]},{"cell_type": "markdown",- "source": [- "Match entities from the query in the knowledge graph storage content:"- ],"metadata": {"id": "zD9hH7QAeVNT"- }+ },+ "source": [+ "Match entities from the query in the knowledge graph storage content:"+ ]},{"cell_type": "code",+ "execution_count": 19,+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "ttL5pnye66Wl",+ "outputId": "a64e9357-bf3d-4985-8705-90237e464a5a"+ },+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "['Node Mistral Large 2 (label: Model) has relationship HASFEATURE with Node 128k context window (label: Feature)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSLANGUAGE with Node French (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSLANGUAGE with Node German (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSLANGUAGE with Node Spanish (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSLANGUAGE with Node Italian (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSLANGUAGE with Node Portuguese (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSLANGUAGE with Node Arabic (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSLANGUAGE with Node Hindi (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSLANGUAGE with Node Russian (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSLANGUAGE with Node Chinese (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSLANGUAGE with Node Japanese (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSLANGUAGE with Node Korean (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSCODINGLANGUAGE with Node Python (label: CodingLanguage)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSCODINGLANGUAGE with Node Java (label: CodingLanguage)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSCODINGLANGUAGE with Node C (label: CodingLanguage)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSCODINGLANGUAGE with Node C++ (label: CodingLanguage)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSCODINGLANGUAGE with Node JavaScript (label: CodingLanguage)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSCODINGLANGUAGE with Node Bash (label: CodingLanguage)', 'Node Mistral Large 2 (label: Model) has relationship DESIGNEDFOR with Node single-node inference (label: Concept)', 'Node Mistral Large 2 (label: Model) has relationship DESIGNEDFOR with Node long-context applications (label: Concept)', 'Node Mistral Large 2 (label: Model) has relationship HASSIZE with Node 123 billion parameters (label: Attribute)', 'Node Mistral Large 2 (label: Model) has relationship ALLOWS with Node large throughput (label: Attribute)', 'Node Mistral Large 2 (label: Model) has relationship RELEASEDUNDER with Node Mistral Research License (label: License)', 'Node Mistral Large 2 (label: Model) has relationship REQUIRESFORCOMMERCIALUSAGE with Node Mistral Commercial License (label: License)', 'Node Mistral Large 2 (label: Model) has relationship SETSFRONTIER with Node Performance (label: Concept)', 'Node Mistral Large 2 (label: Model) has relationship SETSFRONTIER with Node Cost of Serving (label: Concept)', 'Node Mistral Large 2 (label: Model) has relationship SETSFRONTIER with Node Evaluation Metrics (label: Concept)', 'Node Mistral Large 2 (label: Model) has relationship SETSNEWPOINT with Node Performance/Cost Pareto Front (label: Concept)', 'Node Mistral Large 2 (label: Model) has relationship BENCHMARKEDTHROUGH with Node evaluation pipeline (label: Process)', 'Node Mistral Large 2 (label: Model) has relationship IMPROVED with Node instruction-following (label: Capability)', 'Node Mistral Large 2 (label: Model) has relationship IMPROVED with Node conversational capabilities (label: Capability)', 'Node Mistral Large 2 (label: Model) has relationship BETTERAT with Node precise instructions (label: Capability)', 'Node Mistral Large 2 (label: Model) has relationship BETTERAT with Node long multi-turn conversations (label: Capability)', 'Node Mistral Large 2 (label: Model) has relationship PERFORMANCEREPORTEDON with Node MT-Bench (label: Benchmark)', 'Node Mistral Large 2 (label: Model) has relationship PERFORMANCEREPORTEDON with Node Wild Bench (label: Benchmark)', 'Node Mistral Large 2 (label: Model) has relationship PERFORMANCEREPORTEDON with Node Arena Hard benchmarks (label: Benchmark)', 'Node Mistral Large 2 (label: Model) has relationship PERFORMANCEREPORTEDON with Node general alignment benchmarks (label: Benchmark)', 'Node Mistral Large 2 (label: Model) has relationship TRAINEDON with Node Multilingual Data (label: Concept)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node French (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node German (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node Spanish (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node Italian (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node Portuguese (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node Arabic (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node Hindi (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node Russian (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node Chinese (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node Japanese (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node Korean (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node English (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node Dutch (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship HASPERFORMANCERESULTSON with Node MMLU Benchmark (label: Benchmark)', 'Node Mistral Large 2 (label: Model) has relationship COMPAREDTO with Node Mistral Large (label: Model)', 'Node Mistral Large 2 (label: Model) has relationship COMPAREDTO with Node Llama (label: Model)', 'Node Mistral Large 2 (label: Model) has relationship EQUIPPEDWITH with Node Enhanced Function Calling (label: Feature)', 'Node Mistral Large 2 (label: Model) has relationship EQUIPPEDWITH with Node Retrieval Skills (label: Feature)', 'Node Mistral Large 2 (label: Model) has relationship UNDERGONE with Node Training (label: Process)', 'Node Mistral Large 2 (label: Model) has relationship CANEXECUTE with Node Parallel Function Calls (label: Feature)', 'Node Mistral Large 2 (label: Model) has relationship CANEXECUTE with Node Sequential Function Calls (label: Feature)', 'Node Mistral Large 2 (label: Model) has relationship SERVESAS with Node Power Engine (label: Role)', 'Node Mistral Large 2 (label: Product) has relationship EXPOSEDON with Node la Plateforme (label: Platform)', 'Node Mistral Large 2 (label: Product) has relationship ENRICHEDWITH with Node new features (label: Feature)', 'Node Mistral AI (label: Organization) has relationship HASMODEL with Node Mistral Large 2 (label: Model)', 'Node Mistral AI (label: Organization) has relationship PARTNERSWITH with Node Google Cloud Platform (label: Organization)', 'Node Mistral AI (label: Organization) has relationship PROVIDESMODELSON with Node Vertex AI (label: Service)', 'Node Mistral AI (label: Organization) has relationship PROVIDESMODELSON with Node Azure AI Studio (label: Service)', 'Node Mistral AI (label: Organization) has relationship PROVIDESMODELSON with Node Amazon Bedrock (label: Service)', 'Node Mistral AI (label: Organization) has relationship PROVIDESMODELSON with Node IBM watsonx.ai (label: Service)']\n"+ ]+ }+ ],"source": ["# Match the enetity got from query in the knowledge graph storage content\n","kg_result = []\n",@@ -701,96 +707,52 @@"\n","# Show the result from knowledge graph database\n","print(kg_result)"- ],- "metadata": {- "id": "ttL5pnye66Wl",- "colab": {- "base_uri": "https://localhost:8080/"- },- "outputId": "a64e9357-bf3d-4985-8705-90237e464a5a"- },- "execution_count": 19,- "outputs": [- {- "output_type": "stream",- "name": "stdout",- "text": [- "['Node Mistral Large 2 (label: Model) has relationship HASFEATURE with Node 128k context window (label: Feature)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSLANGUAGE with Node French (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSLANGUAGE with Node German (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSLANGUAGE with Node Spanish (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSLANGUAGE with Node Italian (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSLANGUAGE with Node Portuguese (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSLANGUAGE with Node Arabic (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSLANGUAGE with Node Hindi (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSLANGUAGE with Node Russian (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSLANGUAGE with Node Chinese (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSLANGUAGE with Node Japanese (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSLANGUAGE with Node Korean (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSCODINGLANGUAGE with Node Python (label: CodingLanguage)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSCODINGLANGUAGE with Node Java (label: CodingLanguage)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSCODINGLANGUAGE with Node C (label: CodingLanguage)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSCODINGLANGUAGE with Node C++ (label: CodingLanguage)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSCODINGLANGUAGE with Node JavaScript (label: CodingLanguage)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSCODINGLANGUAGE with Node Bash (label: CodingLanguage)', 'Node Mistral Large 2 (label: Model) has relationship DESIGNEDFOR with Node single-node inference (label: Concept)', 'Node Mistral Large 2 (label: Model) has relationship DESIGNEDFOR with Node long-context applications (label: Concept)', 'Node Mistral Large 2 (label: Model) has relationship HASSIZE with Node 123 billion parameters (label: Attribute)', 'Node Mistral Large 2 (label: Model) has relationship ALLOWS with Node large throughput (label: Attribute)', 'Node Mistral Large 2 (label: Model) has relationship RELEASEDUNDER with Node Mistral Research License (label: License)', 'Node Mistral Large 2 (label: Model) has relationship REQUIRESFORCOMMERCIALUSAGE with Node Mistral Commercial License (label: License)', 'Node Mistral Large 2 (label: Model) has relationship SETSFRONTIER with Node Performance (label: Concept)', 'Node Mistral Large 2 (label: Model) has relationship SETSFRONTIER with Node Cost of Serving (label: Concept)', 'Node Mistral Large 2 (label: Model) has relationship SETSFRONTIER with Node Evaluation Metrics (label: Concept)', 'Node Mistral Large 2 (label: Model) has relationship SETSNEWPOINT with Node Performance/Cost Pareto Front (label: Concept)', 'Node Mistral Large 2 (label: Model) has relationship BENCHMARKEDTHROUGH with Node evaluation pipeline (label: Process)', 'Node Mistral Large 2 (label: Model) has relationship IMPROVED with Node instruction-following (label: Capability)', 'Node Mistral Large 2 (label: Model) has relationship IMPROVED with Node conversational capabilities (label: Capability)', 'Node Mistral Large 2 (label: Model) has relationship BETTERAT with Node precise instructions (label: Capability)', 'Node Mistral Large 2 (label: Model) has relationship BETTERAT with Node long multi-turn conversations (label: Capability)', 'Node Mistral Large 2 (label: Model) has relationship PERFORMANCEREPORTEDON with Node MT-Bench (label: Benchmark)', 'Node Mistral Large 2 (label: Model) has relationship PERFORMANCEREPORTEDON with Node Wild Bench (label: Benchmark)', 'Node Mistral Large 2 (label: Model) has relationship PERFORMANCEREPORTEDON with Node Arena Hard benchmarks (label: Benchmark)', 'Node Mistral Large 2 (label: Model) has relationship PERFORMANCEREPORTEDON with Node general alignment benchmarks (label: Benchmark)', 'Node Mistral Large 2 (label: Model) has relationship TRAINEDON with Node Multilingual Data (label: Concept)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node French (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node German (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node Spanish (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node Italian (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node Portuguese (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node Arabic (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node Hindi (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node Russian (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node Chinese (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node Japanese (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node Korean (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node English (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node Dutch (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship HASPERFORMANCERESULTSON with Node MMLU Benchmark (label: Benchmark)', 'Node Mistral Large 2 (label: Model) has relationship COMPAREDTO with Node Mistral Large (label: Model)', 'Node Mistral Large 2 (label: Model) has relationship COMPAREDTO with Node Llama (label: Model)', 'Node Mistral Large 2 (label: Model) has relationship EQUIPPEDWITH with Node Enhanced Function Calling (label: Feature)', 'Node Mistral Large 2 (label: Model) has relationship EQUIPPEDWITH with Node Retrieval Skills (label: Feature)', 'Node Mistral Large 2 (label: Model) has relationship UNDERGONE with Node Training (label: Process)', 'Node Mistral Large 2 (label: Model) has relationship CANEXECUTE with Node Parallel Function Calls (label: Feature)', 'Node Mistral Large 2 (label: Model) has relationship CANEXECUTE with Node Sequential Function Calls (label: Feature)', 'Node Mistral Large 2 (label: Model) has relationship SERVESAS with Node Power Engine (label: Role)', 'Node Mistral Large 2 (label: Product) has relationship EXPOSEDON with Node la Plateforme (label: Platform)', 'Node Mistral Large 2 (label: Product) has relationship ENRICHEDWITH with Node new features (label: Feature)', 'Node Mistral AI (label: Organization) has relationship HASMODEL with Node Mistral Large 2 (label: Model)', 'Node Mistral AI (label: Organization) has relationship PARTNERSWITH with Node Google Cloud Platform (label: Organization)', 'Node Mistral AI (label: Organization) has relationship PROVIDESMODELSON with Node Vertex AI (label: Service)', 'Node Mistral AI (label: Organization) has relationship PROVIDESMODELSON with Node Azure AI Studio (label: Service)', 'Node Mistral AI (label: Organization) has relationship PROVIDESMODELSON with Node Amazon Bedrock (label: Service)', 'Node Mistral AI (label: Organization) has relationship PROVIDESMODELSON with Node IBM watsonx.ai (label: Service)']\n"- ]- }]},{"cell_type": "markdown",- "source": [- "Combine results from the vector search and knowledge graph entity search:"- ],"metadata": {"id": "sjKr29w8eZ4n"- }+ },+ "source": [+ "Combine results from the vector search and knowledge graph entity search:"+ ]},{"cell_type": "code",- "source": [- "# combine result from vector seach and knowledge graph entity search\n",- "comined_results = str(vector_result) + \"\\n\".join(kg_result)"- ],+ "execution_count": 23,"metadata": {"id": "P9ne7UoB6GY5"},- "execution_count": 23,- "outputs": []+ "outputs": [],+ "source": [+ "# combine result from vector seach and knowledge graph entity search\n",+ "comined_results = str(vector_result) + \"\\n\".join(kg_result)"+ ]},{"cell_type": "markdown",- "source": [- "Set up an assistant agent to answer questions based on the retrieved context:"- ],"metadata": {"id": "q-NaDHypebKZ"- }+ },+ "source": [+ "Set up an assistant agent to answer questions based on the retrieved context:"+ ]},{"cell_type": "code",- "source": [- "# Set agent\n",- "sys_msg = BaseMessage.make_assistant_message(\n",- " role_name=\"CAMEL Agent\",\n",- " content=\"\"\"You are a helpful assistant to answer question,\n",- " I will give you the Original Query and Retrieved Context,\n",- " answer the Original Query based on the Retrieved Context.\"\"\",\n",- ")\n",- "\n",- "camel_agent = ChatAgent(system_message=sys_msg,\n",- " model=mistral_large_2)\n",- "\n",- "# Pass the retrieved infomation to agent\n",- "user_prompt=f\"\"\"\n",- "The Original Query is {query}\n",- "The Retrieved Context is {comined_results}\n",- "\"\"\"\n",- "\n",- "user_msg = BaseMessage.make_user_message(\n",- " role_name=\"CAMEL User\", content=user_prompt\n",- ")\n",- "\n",- "# Get response\n",- "agent_response = camel_agent.step(user_msg)\n",- "\n",- "print(agent_response.msg.content)"- ],+ "execution_count": 24,"metadata": {- "id": "LxEUi36F7kq1","colab": {"base_uri": "https://localhost:8080/"},+ "id": "LxEUi36F7kq1","outputId": "9e3aeb7f-a1bd-437d-c9ab-81df4f25a960"},- "execution_count": 24,"outputs": [{- "output_type": "stream","name": "stdout",+ "output_type": "stream","text": ["### Relationship Between Mistral Large 2 and Mistral AI\n","\n",@@ -842,19 +804,49 @@"These features make Mistral Large 2 a powerful and versatile model suitable for a wide range of applications.\n"]}+ ],+ "source": [+ "# Set agent\n",+ "sys_msg = BaseMessage.make_assistant_message(\n",+ " role_name=\"CAMEL Agent\",\n",+ " content=\"\"\"You are a helpful assistant to answer question,\n",+ " I will give you the Original Query and Retrieved Context,\n",+ " answer the Original Query based on the Retrieved Context.\"\"\",\n",+ ")\n",+ "\n",+ "camel_agent = ChatAgent(system_message=sys_msg,\n",+ " model=mistral_large_2)\n",+ "\n",+ "# Pass the retrieved infomation to agent\n",+ "user_prompt=f\"\"\"\n",+ "The Original Query is {query}\n",+ "The Retrieved Context is {comined_results}\n",+ "\"\"\"\n",+ "\n",+ "user_msg = BaseMessage.make_user_message(\n",+ " role_name=\"CAMEL User\", content=user_prompt\n",+ ")\n",+ "\n",+ "# Get response\n",+ "agent_response = camel_agent.step(user_msg)\n",+ "\n",+ "print(agent_response.msg.content)"]},{"cell_type": "markdown",- "source": [- "## 🌟 Highlights"- ],"metadata": {"id": "ZMWitnLdlYCT"- }+ },+ "source": [+ "## 🌟 Highlights"+ ]},{"cell_type": "markdown",+ "metadata": {+ "id": "w2OwDpJ0lg8o"+ },"source": ["* Automated Knowledge Extraction: The Knowledge Graph Agent automates the extraction of entities and relationships, making the process efficient and effective.\n","\n",@@ -862,19 +854,30 @@"\n","\n","* Secure and Scalable: Using CAMEL-AI's robust architecture and Neo4j for graph storage ensures that the solution is both secure and scalable."- ],- "metadata": {- "id": "w2OwDpJ0lg8o"- }+ ]},{"cell_type": "markdown",- "source": [- "By following this cookbook, you can leverage the cutting-edge capabilities of **CAMEL AI** and **Mistral AI** to build sophisticated knowledge graphs, facilitating advanced data analysis and retrieval tasks."- ],"metadata": {"id": "tlTJulaQlbyW"- }+ },+ "source": [+ "By following this cookbook, you can leverage the cutting-edge capabilities of **CAMEL AI** and **Mistral AI** to build sophisticated knowledge graphs, facilitating advanced data analysis and retrieval tasks."+ ]+ }+ ],+ "metadata": {+ "colab": {+ "provenance": []+ },+ "kernelspec": {+ "display_name": "Python 3",+ "name": "python3"+ },+ "language_info": {+ "name": "python"}- ]+ },+ "nbformat": 4,+ "nbformat_minor": 0}diff --git a/docs/cookbooks/roleplaying_scraper.ipynb b/docs/cookbooks/roleplaying_scraper.ipynbindex 0777f50a8..3bbc7e1b0 100644--- a/docs/cookbooks/roleplaying_scraper.ipynb+++ b/docs/cookbooks/roleplaying_scraper.ipynb@@ -1,12 +1,13 @@{"cells": [{+ "attachments": {},"cell_type": "markdown","metadata": {"id": "ymsq1Lw0VEqT"},"source": [- "# 🐫 CAMEL Role-Playing **Scraper** for **Report** & **Knowledge Graph** Generation\n"+ "# Role-Playing **Scraper** for **Report** & **Knowledge Graph** Generation\n"]},{@@ -87,7 +88,9 @@"id": "0GXs2pruU9Vl"},"outputs": [],- "source": "%pip install \"camel-ai[all]==0.2.1\""+ "source": [+ "%pip install \"camel-ai[all]==0.2.1\""+ ]},{"cell_type": "markdown",@@ -695,7 +698,7 @@"name": "stderr","output_type": "stream","text": [- "🖇 AgentOps: \u001B[34m\u001B[34mSession Replay: https://app.agentops.ai/drilldown?session_id=ab0c011f-1928-4895-9747-ea882e9dfc38\u001B[0m\u001B[0m\n"+ "🖇 AgentOps: \u001b[34m\u001b[34mSession Replay: https://app.agentops.ai/drilldown?session_id=ab0c011f-1928-4895-9747-ea882e9dfc38\u001b[0m\u001b[0m\n"]},{@@ -941,13 +944,13 @@"name": "stdout","output_type": "stream","text": [- "\u001B[32mAI Assistant sys message:\n",+ "\u001b[32mAI Assistant sys message:\n","BaseMessage(role_name='CAMEL Assistant', role_type=<RoleType.ASSISTANT: 'assistant'>, meta_dict={'task': 'Do a comprehensive study of the Turkish shooter in 2024 paris\\nolympics, write a report for me, then create a knowledge graph for the report.\\nYou should use search tool to get related URLs first, then use retrieval tool\\nto get the retrieved content back by providing the list of URLs, finially\\nuse tool to build the knowledge graph to finish the task.\\nNo more other actions needed', 'assistant_role': 'CAMEL Assistant', 'user_role': 'CAMEL User'}, content='===== RULES OF ASSISTANT =====\\nNever forget you are a CAMEL Assistant and I am a CAMEL User. Never flip roles! Never instruct me!\\nWe share a common interest in collaborating to successfully complete a task.\\nYou must help me to complete the task.\\nHere is the task: Do a comprehensive study of the Turkish shooter in 2024 paris\\nolympics, write a report for me, then create a knowledge graph for the report.\\nYou should use search tool to get related URLs first, then use retrieval tool\\nto get the retrieved content back by providing the list of URLs, finially\\nuse tool to build the knowledge graph to finish the task.\\nNo more other actions needed. Never forget our task!\\nI must instruct you based on your expertise and my needs to complete the task.\\n\\nI must give you one instruction at a time.\\nYou must write a specific solution that appropriately solves the requested instruction and explain your solutions.\\nYou must decline my instruction honestly if you cannot perform the instruction due to physical, moral, legal reasons or your capability and explain the reasons.\\nUnless I say the task is completed, you should always start with:\\n\\nSolution: <YOUR_SOLUTION>\\n\\n<YOUR_SOLUTION> should be very specific, include detailed explanations and provide preferable detailed implementations and examples and lists for task-solving.\\nAlways end <YOUR_SOLUTION> with: Next request.', video_bytes=None, image_list=None, image_detail='auto', video_detail='low')\n","\n",- "\u001B[34mAI User sys message:\n",+ "\u001b[34mAI User sys message:\n","BaseMessage(role_name='CAMEL User', role_type=<RoleType.USER: 'user'>, meta_dict={'task': 'Do a comprehensive study of the Turkish shooter in 2024 paris\\nolympics, write a report for me, then create a knowledge graph for the report.\\nYou should use search tool to get related URLs first, then use retrieval tool\\nto get the retrieved content back by providing the list of URLs, finially\\nuse tool to build the knowledge graph to finish the task.\\nNo more other actions needed', 'assistant_role': 'CAMEL Assistant', 'user_role': 'CAMEL User'}, content='===== RULES OF USER =====\\nNever forget you are a CAMEL User and I am a CAMEL Assistant. Never flip roles! You will always instruct me.\\nWe share a common interest in collaborating to successfully complete a task.\\nI must help you to complete the task.\\nHere is the task: Do a comprehensive study of the Turkish shooter in 2024 paris\\nolympics, write a report for me, then create a knowledge graph for the report.\\nYou should use search tool to get related URLs first, then use retrieval tool\\nto get the retrieved content back by providing the list of URLs, finially\\nuse tool to build the knowledge graph to finish the task.\\nNo more other actions needed. Never forget our task!\\nYou must instruct me based on my expertise and your needs to solve the task ONLY in the following two ways:\\n\\n1. Instruct with a necessary input:\\nInstruction: <YOUR_INSTRUCTION>\\nInput: <YOUR_INPUT>\\n\\n2. Instruct without any input:\\nInstruction: <YOUR_INSTRUCTION>\\nInput: None\\n\\nThe \"Instruction\" describes a task or question. The paired \"Input\" provides further context or information for the requested \"Instruction\".\\n\\nYou must give me one instruction at a time.\\nI must write a response that appropriately solves the requested instruction.\\nI must decline your instruction honestly if I cannot perform the instruction due to physical, moral, legal reasons or my capability and explain the reasons.\\nYou should instruct me not ask me questions.\\nNow you must start to instruct me using the two ways described above.\\nDo not add anything else other than your instruction and the optional corresponding input!\\nKeep giving me instructions and necessary inputs until you think the task is completed.\\nWhen the task is completed, you must only reply with a single word <CAMEL_TASK_DONE>.\\nNever say <CAMEL_TASK_DONE> unless my responses have solved your task.', video_bytes=None, image_list=None, image_detail='auto', video_detail='low')\n","\n",- "\u001B[33mOriginal task prompt:\n",+ "\u001b[33mOriginal task prompt:\n","Do a comprehensive study of the Turkish shooter in 2024 paris\n","olympics, write a report for me, then create a knowledge graph for the report.\n","You should use search tool to get related URLs first, then use retrieval tool\n",@@ -955,10 +958,10 @@"use tool to build the knowledge graph to finish the task.\n","No more other actions needed\n","\n",- "\u001B[36mSpecified task prompt:\n",+ "\u001b[36mSpecified task prompt:\n","None\n","\n",- "\u001B[31mFinal task prompt:\n",+ "\u001b[31mFinal task prompt:\n","Do a comprehensive study of the Turkish shooter in 2024 paris\n","olympics, write a report for me, then create a knowledge graph for the report.\n","You should use search tool to get related URLs first, then use retrieval tool\n",@@ -1012,13 +1015,13 @@"name": "stdout","output_type": "stream","text": [- "\u001B[34mAI User:\n",+ "\u001b[34mAI User:\n","\n","Instruction: Use the search tool to find related URLs about the Turkish shooter in the 2024 Paris Olympics.\n","Input: None\n","\n","\n",- "\u001B[32mAI Assistant:\n",+ "\u001b[32mAI Assistant:\n","\n","Function Execution: search_duckduckgo\n","\tArgs: {'query': 'Turkish shooter in the 2024 Paris Olympics'}\n",@@ -1049,13 +1052,13 @@"Next request.\n","\n","\n",- "\u001B[34mAI User:\n",+ "\u001b[34mAI User:\n","\n","Instruction: Use the retrieval tool to get the content from the provided URLs.\n","Input: [https://olympics.com/en/news/yusuf-dikec-turkish-shooting-viral-paris-2024-olympics, https://www.nbcnews.com/news/sports/sharpshooter-yusuf-dikec-silver-olympics-minimal-gear-internet-sensati-rcna164685, https://apnews.com/article/olympics-2024-yusuf-dikec-turkish-shooter-a7890124304080a48e7ee4294004d306, https://www.nbcnews.com/video/watch-turkey-s-sharpshooter-wins-silver-without-high-tech-aids-216173637766, https://www.cnn.com/2024/08/09/sport/yusuf-dikec-olympic-celebration-craze-spt-intl/index.html]\n","\n","\n",- "\u001B[32mAI Assistant:\n",+ "\u001b[32mAI Assistant:\n","\n","Function Execution: retrieve_information_from_urls\n","\tArgs: {'query': 'Turkish shooter in the 2024 Paris Olympics', 'urls': ['https://olympics.com/en/news/yusuf-dikec-turkish-shooting-viral-paris-2024-olympics', 'https://www.nbcnews.com/news/sports/sharpshooter-yusuf-dikec-silver-olympics-minimal-gear-internet-sensati-rcna164685', 'https://apnews.com/article/olympics-2024-yusuf-dikec-turkish-shooter-a7890124304080a48e7ee4294004d306', 'https://www.nbcnews.com/video/watch-turkey-s-sharpshooter-wins-silver-without-high-tech-aids-216173637766', 'https://www.cnn.com/2024/08/09/sport/yusuf-dikec-olympic-celebration-craze-spt-intl/index.html']}\n",@@ -1098,13 +1101,13 @@"Next request.\n","\n","\n",- "\u001B[34mAI User:\n",+ "\u001b[34mAI User:\n","\n","Instruction: Summarize the key points from the retrieved content about the Turkish shooter Yusuf Dikec at the 2024 Paris Olympics.\n","Input: None\n","\n","\n",- "\u001B[32mAI Assistant:\n",+ "\u001b[32mAI Assistant:\n","\n","Solution: I have summarized the key points from the retrieved content about the Turkish shooter Yusuf Dikec at the 2024 Paris Olympics. Here are the main points:\n","\n",@@ -1121,13 +1124,13 @@"Next request.\n","\n","\n",- "\u001B[34mAI User:\n",+ "\u001b[34mAI User:\n","\n","Instruction: Use the summarized key points to write a comprehensive report about the Turkish shooter Yusuf Dikec at the 2024 Paris Olympics.\n","Input: None\n","\n","\n",- "\u001B[32mAI Assistant:\n",+ "\u001b[32mAI Assistant:\n","\n","Solution: I have written a comprehensive report about the Turkish shooter Yusuf Dikec at the 2024 Paris Olympics based on the summarized key points. Here is the report:\n","\n",@@ -1170,13 +1173,13 @@"Next request.\n","\n","\n",- "\u001B[34mAI User:\n",+ "\u001b[34mAI User:\n","\n","Instruction: Use the tool to build a knowledge graph based on the comprehensive report about the Turkish shooter Yusuf Dikec at the 2024 Paris Olympics.\n","Input: None\n","\n","\n",- "\u001B[32mAI Assistant:\n",+ "\u001b[32mAI Assistant:\n","\n","Function Execution: knowledge_graph_builder\n","\tArgs: {'text_input': \"### Comprehensive Report on Turkish Shooter Yusuf Dikec at the 2024 Paris Olympics\\n\\n#### Introduction\\n\\nYusuf Dikec, a seasoned Olympian and Turkish record breaker, made headlines at the 2024 Paris Olympics with his impressive performance and unique style. This report delves into his background, achievements, and the impact he made during the games.\\n\\n#### Background\\n\\nYusuf Dikec is an experienced shooter who has represented Turkey in multiple Olympic Games. He made his Olympic debut at the Beijing 2008 Olympics at the age of 35. Since then, he has competed in the London 2012, Rio 2016, and Tokyo 2020 Olympics, showcasing his skills and dedication to the sport.\\n\\n#### Achievements at the 2024 Paris Olympics\\n\\n##### Silver Medal Win\\n\\nAt the 2024 Paris Olympics, Yusuf Dikec won a silver medal in the air pistol team event. His performance was notable not only for his accuracy but also for his minimalistic approach. Unlike many of his competitors, Dikec did not use special lenses or big ear protectors. Instead, he competed with a regular pair of glasses and one hand casually tucked into his pocket, demonstrating a level of confidence and skill that captivated audiences.\\n\\n##### Viral Sensation\\n\\nDikec's nonchalant attitude and minimal gear during the competition went viral on the internet. Images and videos of him shooting effortlessly while maintaining a seemingly casual demeanor spread rapidly across social media platforms. His unique style and impressive performance made him an internet sensation, drawing attention from both sports enthusiasts and casual viewers alike.\\n\\n##### Partnership with Sevval Ilayda Tarhan\\n\\nDikec competed alongside Sevval Ilayda Tarhan in the mixed air pistol team event. Together, they secured Turkey’s first medal in Olympic shooting. Tarhan, like Dikec, also competed with minimal gear, keeping one hand tucked in her pocket and not wearing any blinders. Their partnership and shared approach to the sport highlighted their synergy and skill.\\n\\n#### Historic Achievement\\n\\nThe silver medal win marked a historic achievement for Turkey. It was the country’s first medal in an Olympic shooting event, underscoring the significance of Dikec and Tarhan's performance. Their success not only brought pride to their nation but also inspired a new generation of shooters in Turkey.\\n\\n#### Conclusion\\n\\nYusuf Dikec's journey at the 2024 Paris Olympics is a testament to his skill, dedication, and unique style. His silver medal win, viral fame, and historic achievement have cemented his place in the annals of Turkish sports history. As he continues to compete, Dikec serves as an inspiration for aspiring athletes, showcasing the power of perseverance and individuality in sports.\"}\n",@@ -1222,7 +1225,7 @@"Next request.\n","\n","\n",- "\u001B[34mAI User:\n",+ "\u001b[34mAI User:\n","\n","<CAMEL_TASK_DONE>\n","\n",@@ -1294,7 +1297,7 @@"output_type": "stream","text": ["🖇 AgentOps: This run's cost $0.00\n",- "🖇 AgentOps: \u001B[34m\u001B[34mSession Replay: https://app.agentops.ai/drilldown?session_id=ab0c011f-1928-4895-9747-ea882e9dfc38\u001B[0m\u001B[0m\n"+ "🖇 AgentOps: \u001b[34m\u001b[34mSession Replay: https://app.agentops.ai/drilldown?session_id=ab0c011f-1928-4895-9747-ea882e9dfc38\u001b[0m\u001b[0m\n"]}],diff --git a/docs/cookbooks/task_generation.ipynb b/docs/cookbooks/task_generation.ipynbindex 3cbd3166f..89f0442fe 100644--- a/docs/cookbooks/task_generation.ipynb+++ b/docs/cookbooks/task_generation.ipynb@@ -1,12 +1,13 @@{"cells": [{+ "attachments": {},"cell_type": "markdown","metadata": {"id": "Fvdt_pMpf7EK"},"source": [- "# 🐫 CAMEL Task Generation Cookbook"+ "# Task Generation Cookbook"]},{diff --git a/docs/cookbooks/video_analysis.ipynb b/docs/cookbooks/video_analysis.ipynbindex eac907f91..45b97ddc3 100644--- a/docs/cookbooks/video_analysis.ipynb+++ b/docs/cookbooks/video_analysis.ipynb@@ -1,32 +1,35 @@{"cells": [{+ "attachments": {},"cell_type": "markdown","metadata": {"id": "ssX_map8c6mx"},"source": [- "# 🐫 CAMEL Video Analysis"+ "# Video Analysis"]},{"cell_type": "markdown",- "source": [- "You can also check this cookbook in colab [here](https://colab.research.google.com/drive/1XfF4BOSzo_rj9J58aZYanMUk5vixn-eR?usp=sharing)"- ],"metadata": {"id": "9S0pePjZkwUz"- }+ },+ "source": [+ "You can also check this cookbook in colab [here](https://colab.research.google.com/drive/1XfF4BOSzo_rj9J58aZYanMUk5vixn-eR?usp=sharing)"+ ]},{"cell_type": "code","execution_count": null,"metadata": {- "id": "AkvGo5umOwxM",- "collapsed": true+ "collapsed": true,+ "id": "AkvGo5umOwxM"},"outputs": [],- "source": "%pip install \"camel-ai[all]==0.2.1\""+ "source": [+ "%pip install \"camel-ai[all]==0.2.1\""+ ]},{"cell_type": "code",@@ -58,6 +61,11 @@},{"cell_type": "code",+ "execution_count": 3,+ "metadata": {+ "id": "J97N3GtSexwu"+ },+ "outputs": [],"source": ["from camel.agents import ChatAgent\n","from camel.configs.openai_config import ChatGPTConfig\n",@@ -88,12 +96,7 @@" sys_msg,\n"," model=model\n",")"- ],- "metadata": {- "id": "J97N3GtSexwu"- },- "execution_count": 3,- "outputs": []+ ]},{"cell_type": "code",@@ -107,8 +110,8 @@},"outputs": [{- "output_type": "stream","name": "stdout",+ "output_type": "stream","text": ["\"Step into the fascinating world of scientific discovery with our latest video! Watch as a dedicated researcher meticulously works in a high-tech laboratory, surrounded by intricate equipment and cutting-edge technology. This behind-the-scenes footage offers a glimpse into the meticulous process of experimentation and innovation. Join us on this journey of exploration and witness the passion and precision that drive scientific breakthroughs. Don't miss out on this captivating look at the heart of scientific research!\"\n"]@@ -135,6 +138,23 @@},{"cell_type": "code",+ "execution_count": null,+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "q7NIRGNT3bWx",+ "outputId": "84941af1-45b9-42bf-cc71-8da1fc9a620d"+ },+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "\"Embark on a breathtaking journey through lush, green landscapes and rugged mountain trails. This video captures the serene beauty of nature, with winding paths leading you through picturesque scenery under a vibrant blue sky. Perfect for nature lovers and adventure seekers alike, this visual escape will transport you to a tranquil world far from the hustle and bustle of everyday life. Join us as we explore the untouched beauty of this stunning trail.\"\n"+ ]+ }+ ],"source": ["# Provide your video path\n","video_help = \"/content/help.mov\"\n",@@ -152,27 +172,27 @@"# Get response information\n","response_help = camel_agent.step(user_msg_help)\n","print(response_help.msgs[0].content)"- ],+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,"metadata": {"colab": {"base_uri": "https://localhost:8080/"},- "id": "q7NIRGNT3bWx",- "outputId": "84941af1-45b9-42bf-cc71-8da1fc9a620d"+ "id": "RdwfgT_S3uZ5",+ "outputId": "3c69323b-ad66-41c4-d700-232400535841"},- "execution_count": null,"outputs": [{- "output_type": "stream","name": "stdout",+ "output_type": "stream","text": [- "\"Embark on a breathtaking journey through lush, green landscapes and rugged mountain trails. This video captures the serene beauty of nature, with winding paths leading you through picturesque scenery under a vibrant blue sky. Perfect for nature lovers and adventure seekers alike, this visual escape will transport you to a tranquil world far from the hustle and bustle of everyday life. Join us as we explore the untouched beauty of this stunning trail.\"\n"+ "\"Join us for a candid glimpse into a moment of relaxation and reflection in the kitchen. Watch as our protagonist unwinds after a long day, savoring a drink and enjoying the simple pleasures of life. This video captures the essence of taking a break and finding comfort in familiar surroundings. Don't miss this relatable and heartwarming scene!\"\n"]}- ]- },- {- "cell_type": "code",+ ],"source": ["# Provide your video path\n","video_content_mode = \"/content/content mod.mov\"\n",@@ -190,23 +210,6 @@"# Get response information\n","response_content_mode = camel_agent.step(user_msg_content_mode)\n","print(response_content_mode.msgs[0].content)"- ],- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "RdwfgT_S3uZ5",- "outputId": "3c69323b-ad66-41c4-d700-232400535841"- },- "execution_count": null,- "outputs": [- {- "output_type": "stream",- "name": "stdout",- "text": [- "\"Join us for a candid glimpse into a moment of relaxation and reflection in the kitchen. Watch as our protagonist unwinds after a long day, savoring a drink and enjoying the simple pleasures of life. This video captures the essence of taking a break and finding comfort in familiar surroundings. Don't miss this relatable and heartwarming scene!\"\n"- ]- }]}],diff --git a/docs/index.rst b/docs/index.rstindex 1b82b410f..80ff86634 100644--- a/docs/index.rst+++ b/docs/index.rst@@ -23,10 +23,10 @@ Main Documentation:caption: Agents:name: agents- agents/single_agent.md- agents/role_playing.md- agents/embodied_agents.md- agents/critic_agents_and_tree_search.md+ cookbooks/create_your_first_agent.ipynb+ cookbooks/create_your_first_agents_society.ipynb+ cookbooks/embodied_agents.ipynb+ cookbooks/critic_agents_and_tree_search.ipynb.. toctree:::maxdepth: 1diff --git a/examples/test/bots/test_discord_bot.py b/examples/test/bots/test_discord_bot.pyindex 96737d0a1..e20172e90 100644--- a/examples/test/bots/test_discord_bot.py+++ b/examples/test/bots/test_discord_bot.py@@ -17,7 +17,7 @@ import unittestfrom unittest.mock import AsyncMock, MagicMock, patchfrom camel.agents import ChatAgent-from examples.bots.discord_bot import DiscordBot+from camel.bots.discord_bot import DiscordBotclass TestDiscordBot(unittest.TestCase):diff --git a/examples/test/bots/test_telegram_bot.py b/examples/test/bots/test_telegram_bot.pyindex 41301268f..50b2552ea 100644--- a/examples/test/bots/test_telegram_bot.py+++ b/examples/test/bots/test_telegram_bot.py@@ -15,8 +15,8 @@ import unittestfrom unittest.mock import MagicMock, patchfrom camel.agents import ChatAgent+from camel.bots.telegram_bot import TelegramBotfrom camel.messages import BaseMessage-from examples.bots.telegram_bot import TelegramBotclass TestTelegramBot(unittest.TestCase):