๐ซ 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
docs: update cookbooks to version 0.2.4 (#1115)
Wendong-Fan74b8f138c744
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.ymlindex 9762b1ad2..6ca009015 100644--- a/.github/ISSUE_TEMPLATE/bug_report.yml+++ b/.github/ISSUE_TEMPLATE/bug_report.yml@@ -26,7 +26,7 @@ body:attributes:label: What version of camel are you using?description: Run command `python3 -c 'print(__import__("camel").__version__)'` in your shell and paste the output here.- placeholder: E.g., 0.2.4a1+ placeholder: E.g., 0.2.4validations:required: truediff --git a/README.md b/README.mdindex e64abf598..f55a62305 100644--- a/README.md+++ b/README.md@@ -116,7 +116,7 @@ conda create --name camel python=3.10conda activate camel# Clone github repo-git clone -b v0.2.4a1 https://github.com/camel-ai/camel.git+git clone -b v0.2.4 https://github.com/camel-ai/camel.git# Change directory into project directorycd cameldiff --git a/camel/__init__.py b/camel/__init__.pyindex bb49cf421..73a0d72ec 100644--- a/camel/__init__.py+++ b/camel/__init__.py@@ -12,7 +12,7 @@# limitations under the License.# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========-__version__ = '0.2.4a1'+__version__ = '0.2.4'__all__ = ['__version__',diff --git a/docs/conf.py b/docs/conf.pyindex 59f707b45..53a83c72d 100644--- a/docs/conf.py+++ b/docs/conf.py@@ -27,7 +27,7 @@ sys.path.insert(0, os.path.abspath('..'))project = 'CAMEL'copyright = '2024, CAMEL-AI.org'author = 'CAMEL-AI.org'-release = '0.2.4a1'+release = '0.2.4'html_favicon = ('https://raw.githubusercontent.com/camel-ai/camel/master/misc/favicon.png'diff --git a/docs/cookbooks/agents_message.ipynb b/docs/cookbooks/agents_message.ipynbindex faf5cfa68..a6e171009 100644--- a/docs/cookbooks/agents_message.ipynb+++ b/docs/cookbooks/agents_message.ipynb@@ -1,564 +1,606 @@{- "cells": [- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "w5_pa5kKPzAE"- },- "source": [- "# Message Cookbook"- ]- },- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "1tGC1kVjPNX9"- },- "source": [- "You can also check this cookbook in colab [here](https://colab.research.google.com/drive/1qyi4bnAbnYink-FKaAlJG9OipyEWXEsT?usp=sharing)"- ]- },- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "lSXa_rQQQzBd"- },- "source": [- "## Overview"- ]- },- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "OnmoAw2vQG8I"- },- "source": [- "In this tutorial, we will explore the `BaseMessage` class. The topics covered include:\n",- "\n",- "1. Introduction to the `BaseMessage` class.\n",- "2. Creating a `BaseMessage` instance.\n",- "3. Understanding the properties of the `BaseMessage` class.\n",- "4. Using the methods of the `BaseMessage` class.\n",- "5. Give message to `ChatAgent`"- ]- },- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "l4MP9uUNQ2kr"- },- "source": [- "## Introduction\n",- "\n"- ]- },- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "aYzY4OM6F3ay"- },- "source": [- "The `BaseMessage` class is the base class for message objects used in the CAMEL chat system. It is designed to provide a consistent structure for the messages in the system and allow for easy conversion between different message types."- ]- },- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "kETDiaP2Rrdb"- },- "source": [- "### Installation"- ]- },- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "Cg96MkbcRtQR"- },- "source": [- "Ensure you have CAMEL AI installed in your Python environment:"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {+ "nbformat": 4,+ "nbformat_minor": 0,+ "metadata": {"colab": {- "base_uri": "https://localhost:8080/"- },- "collapsed": true,- "id": "ZVmDAK6MPefC",- "outputId": "058bba8e-7df6-46df-cae9-78166c560275"- },- "outputs": [],- "source": [- "%pip install \"camel-ai==0.2.1\""- ]- },- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "MyTTCe3IR_Lr"- },- "source": [- "### Setting Up API Keys"- ]- },- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "REqzgGL9SEaD"- },- "source": [- "You'll need to set up your API keys for OpenAI."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "PNBFEXc-R-0s",- "outputId": "eb7ccdb6-fa2f-44e2-e2b9-7128f2c5d47d"- },- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "Enter your API key: ยทยทยทยทยทยทยทยทยทยท\n"- ]- }- ],- "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"- ]- },- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "LRojeqp7dP1m"- },- "source": [- "## Creating a `BaseMessage` Instance\n"- ]- },- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "_sJV9GFldTBh"- },- "source": [- "To create a `BaseMessage` instance, you need to provide the following arguments:\n",- "\n",- "- `role_name`: The name of the user or assistant role.\n",- "- `role_type`: The type of role, either `RoleType.ASSISTANT` or `RoleType.USER`.\n",- "- `meta_dict`: An optional metadata dictionary for the message.\n",- "- `content`: The content of the message.\n",- "\n",- "Here's an example of creating a `BaseMessage` instance:"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "id": "pAdDeN7DdUgr"- },- "outputs": [],- "source": [- "from camel.messages import BaseMessage\n",- "from camel.types import RoleType\n",- "\n",- "message = BaseMessage(\n",- " role_name=\"test_user\",\n",- " role_type=RoleType.USER,\n",- " content=\"test content\",\n",- " meta_dict={}\n",- ")"- ]- },- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "MBx8Pje9ETAL"- },- "source": [- "Additionally, the BaseMessage class provides class methods to easily create user and assistant agent messages:\n",- "\n",- "1. Creating a user agent message:"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "id": "pEiFYV-yez5j"- },- "outputs": [],- "source": [- "from camel.messages import BaseMessage\n",- "\n",- "user_message = BaseMessage.make_user_message(\n",- " role_name=\"user_name\",\n",- " content=\"test content for user\",\n",- ")"- ]- },- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "PCqjf_fWEdLD"- },- "source": [- "2. Creating an assistant agent message:"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "id": "iIWWSfSpEf2n"- },- "outputs": [],- "source": [- "from camel.messages import BaseMessage\n",- "\n",- "assistant_message = BaseMessage.make_assistant_message(\n",- " role_name=\"assistant_name\",\n",- " content=\"test content for assistant\",\n",- ")"- ]- },- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "yR5ZYr5yEkLL"- },- "source": [- "## Using the Methods of the `BaseMessage` Class"- ]- },- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "Gfc6WNUOEktw"- },- "source": [- "The `BaseMessage` class offers several methods:\n",- "\n",- "1. Creating a new instance with updated content:"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "P7UjCsb-Emsk",- "outputId": "f8f858c2-59c8-4d84-ee4b-01cba6c7aeb4"- },- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "True\n"- ]- }- ],- "source": [- "new_message = message.create_new_instance(\"new test content\")\n",- "print(isinstance(new_message, BaseMessage))"- ]- },- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "412MphuYErw_"- },- "source": [- "2. Converting to an `OpenAIMessage` object:"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "sS_UKtJGEsPE",- "outputId": "b6b8a5bb-d964-43a3-ec10-3c4af7a47bca"- },- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "True\n"- ]- }- ],- "source": [- "from camel.types import OpenAIBackendRole\n",- "openai_message = message.to_openai_message(role_at_backend=OpenAIBackendRole.USER)\n",- "print(openai_message == {\"role\": \"user\", \"content\": \"test content\"})"- ]- },- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "TIpjz3G2E5dy"- },- "source": [- "3. Converting to an `OpenAISystemMessage` object:"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "Ur4u2HdIE5ua",- "outputId": "424f1e49-0531-4589-dbc0-a9291b9a3351"- },- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "True\n"- ]- }- ],- "source": [- "openai_system_message = message.to_openai_system_message()\n",- "print(openai_system_message == {\"role\": \"system\", \"content\": \"test content\"})"- ]- },- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "523x8XqLE8Qo"- },- "source": [- "4. Converting to an `OpenAIUserMessage` object:"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "mRCa7soNE9um",- "outputId": "abf75994-9365-4280-cf52-aaafcf3e46c7"- },- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "True\n"- ]- }- ],- "source": [- "openai_user_message = message.to_openai_user_message()\n",- "print(openai_user_message == {\"role\": \"user\", \"content\": \"test content\"})"- ]- },- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "TURczNJNFA3J"- },- "source": [- "5. Converting to an `OpenAIAssistantMessage` object:"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "5FnnmlRuFCtW",- "outputId": "596f99f9-9771-493d-fb3d-f02cbe71405d"- },- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "True\n"- ]- }- ],- "source": [- "openai_assistant_message = message.to_openai_assistant_message()\n",- "print(openai_assistant_message == {\"role\": \"assistant\", \"content\": \"test content\"})"- ]- },- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "eRhObgkxFFUi"- },- "source": [- "6. Converting to a dictionary:"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "OQouave-FG15",- "outputId": "3bb25dd8-a43d-4a60-ea28-607ea542f572"- },- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "True\n"- ]+ "provenance": []+ },+ "kernelspec": {+ "name": "python3",+ "display_name": "Python 3"+ },+ "language_info": {+ "name": "python"}- ],- "source": [- "message_dict = message.to_dict()\n",- "print(message_dict == {\n",- " \"role_name\": \"test_user\",\n",- " \"role_type\": \"USER\",\n",- " \"content\": \"test content\"\n",- "})"- ]- },- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "seSeG3KAHbLI"- },- "source": [- "These methods allow you to convert a `BaseMessage` instance into different message types depending on your needs."- ]},- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "kAyagBo0GusE"- },- "source": [- "## Give message to `ChatAgent`"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "nbr7nIKxGz07",- "outputId": "e6720252-29a5-439a-f52d-448c35fb3a8b"- },- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "Hello, CAMEL AI! It's great to connect with a community dedicated to the study of autonomous and communicative agents. Your work in this fascinating field is sure to lead to exciting advancements and innovations. If there's anything specific you'd like to discuss or explore, feel free to share!\n"- ]+ "cells": [+ {+ "cell_type": "markdown",+ "source": [+ "# ๐ซ CAMEL Message Cookbook"+ ],+ "metadata": {+ "id": "w5_pa5kKPzAE"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "You can also check this cookbook in colab [here](https://colab.research.google.com/drive/1qyi4bnAbnYink-FKaAlJG9OipyEWXEsT?usp=sharing)"+ ],+ "metadata": {+ "id": "1tGC1kVjPNX9"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "## Overview"+ ],+ "metadata": {+ "id": "lSXa_rQQQzBd"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "In this tutorial, we will explore the `BaseMessage` class. The topics covered include:\n",+ "\n",+ "1. Introduction to the `BaseMessage` class.\n",+ "2. Creating a `BaseMessage` instance.\n",+ "3. Understanding the properties of the `BaseMessage` class.\n",+ "4. Using the methods of the `BaseMessage` class.\n",+ "5. Give message to `ChatAgent`"+ ],+ "metadata": {+ "id": "OnmoAw2vQG8I"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "## Introduction\n",+ "\n"+ ],+ "metadata": {+ "id": "l4MP9uUNQ2kr"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "The `BaseMessage` class is the base class for message objects used in the CAMEL chat system. It is designed to provide a consistent structure for the messages in the system and allow for easy conversion between different message types."+ ],+ "metadata": {+ "id": "aYzY4OM6F3ay"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "### Installation"+ ],+ "metadata": {+ "id": "kETDiaP2Rrdb"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "Ensure you have CAMEL AI installed in your Python environment:"+ ],+ "metadata": {+ "id": "Cg96MkbcRtQR"+ }+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {+ "id": "ZVmDAK6MPefC"+ },+ "outputs": [],+ "source": [+ "!pip install \"camel-ai==0.2.4\""+ ]+ },+ {+ "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": "3efcae2c-a001-4098-a78f-bb8fb611925f"+ },+ "execution_count": 2,+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Enter your API key: ยทยทยทยทยทยทยทยทยทยท\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "## Give message to `ChatAgent` directly\n",+ "You can simply pass text message to `ChatAgent`"+ ],+ "metadata": {+ "id": "_9RKJHGBXvfd"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "from camel.agents import ChatAgent\n",+ "\n",+ "# Define system message\n",+ "sys_msg = \"You are a helpful assistant.\"\n",+ "\n",+ "# Set agent\n",+ "camel_agent = ChatAgent(system_message=sys_msg)\n",+ "\n",+ "# Set user message\n",+ "user_msg = \"\"\"Say hi to CAMEL AI, one open-source community dedicated to the\n",+ " study of autonomous and communicative agents.\"\"\"\n",+ "\n",+ "# Get response information\n",+ "response = camel_agent.step(user_msg)\n",+ "print(response.msgs[0].content)"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "outputId": "aacee56c-7f1e-4220-d98d-f08baeaabb0d",+ "id": "DKcOX661Xvfd"+ },+ "execution_count": 3,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "Hello, CAMEL AI! It's great to connect with a community dedicated to the study of autonomous and communicative agents. Your work in this fascinating field is important for advancing our understanding of AI and its capabilities. If you have any questions or topics you'd like to discuss, feel free to share!\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "## Give message to `ChatAgent` via `BaseMessage`\n",+ "\n",+ "For more complex message usage like mulit-modal message, we suggest using `BaseMessage`"+ ],+ "metadata": {+ "id": "X5scuZsGYGS9"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "### Creating a `BaseMessage` Instance"+ ],+ "metadata": {+ "id": "LRojeqp7dP1m"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "To create a `BaseMessage` instance, you need to provide the following arguments:\n",+ "\n",+ "- `role_name`: The name of the user or assistant role.\n",+ "- `role_type`: The type of role, either `RoleType.ASSISTANT` or `RoleType.USER`.\n",+ "- `content`: The content of the message.\n",+ "- `meta_dict`: An metadata dictionary for the message.\n",+ "\n",+ "Below are optional arguments you can pass:\n",+ "- `video_bytes`: Optional bytes of a video associated with the message.\n",+ "- `image_list`: Optional list of PIL Image objects associated with the message.\n",+ "- `image_detail`: Detail level of the images associated with the message. Default is \"auto\".\n",+ "- `video_detail`: Detail level of the videos associated with the message. Default is \"low\".\n",+ "\n",+ "Here's an example of creating a `BaseMessage` instance:"+ ],+ "metadata": {+ "id": "_sJV9GFldTBh"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "from camel.messages import BaseMessage\n",+ "from camel.types import RoleType\n",+ "\n",+ "message = BaseMessage(\n",+ " role_name=\"test_user\",\n",+ " role_type=RoleType.USER,\n",+ " content=\"test content\",\n",+ " meta_dict={}\n",+ ")"+ ],+ "metadata": {+ "id": "pAdDeN7DdUgr"+ },+ "execution_count": 8,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "Additionally, the BaseMessage class provides class methods to easily create user and assistant agent messages:\n",+ "\n",+ "1. Creating a user agent message:"+ ],+ "metadata": {+ "id": "MBx8Pje9ETAL"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "from camel.messages import BaseMessage\n",+ "\n",+ "user_message = BaseMessage.make_user_message(\n",+ " role_name=\"user_name\",\n",+ " content=\"test content for user\",\n",+ ")"+ ],+ "metadata": {+ "id": "pEiFYV-yez5j"+ },+ "execution_count": 9,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "2. Creating an assistant agent message:"+ ],+ "metadata": {+ "id": "PCqjf_fWEdLD"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "from camel.messages import BaseMessage\n",+ "\n",+ "assistant_message = BaseMessage.make_assistant_message(\n",+ " role_name=\"assistant_name\",\n",+ " content=\"test content for assistant\",\n",+ ")"+ ],+ "metadata": {+ "id": "iIWWSfSpEf2n"+ },+ "execution_count": 10,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "## Using the Methods of the `BaseMessage` Class"+ ],+ "metadata": {+ "id": "yR5ZYr5yEkLL"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "The `BaseMessage` class offers several methods:\n",+ "\n",+ "1. Creating a new instance with updated content:"+ ],+ "metadata": {+ "id": "Gfc6WNUOEktw"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "new_message = message.create_new_instance(\"new test content\")\n",+ "print(isinstance(new_message, BaseMessage))"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "P7UjCsb-Emsk",+ "outputId": "077116bd-3b9f-4fe0-e605-1d2b8814eaa1"+ },+ "execution_count": null,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "True\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "2. Converting to an `OpenAIMessage` object:"+ ],+ "metadata": {+ "id": "412MphuYErw_"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "from camel.types import OpenAIBackendRole\n",+ "openai_message = message.to_openai_message(role_at_backend=OpenAIBackendRole.USER)\n",+ "print(openai_message == {\"role\": \"user\", \"content\": \"test content\"})"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "sS_UKtJGEsPE",+ "outputId": "bb7c150e-cbd7-42c2-b2c2-caf9180ce037"+ },+ "execution_count": null,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "True\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "3. Converting to an `OpenAISystemMessage` object:"+ ],+ "metadata": {+ "id": "TIpjz3G2E5dy"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "openai_system_message = message.to_openai_system_message()\n",+ "print(openai_system_message == {\"role\": \"system\", \"content\": \"test content\"})"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "Ur4u2HdIE5ua",+ "outputId": "9713ccbf-d59c-4853-f889-6fbd80ca332b"+ },+ "execution_count": null,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "True\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "4. Converting to an `OpenAIUserMessage` object:"+ ],+ "metadata": {+ "id": "523x8XqLE8Qo"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "openai_user_message = message.to_openai_user_message()\n",+ "print(openai_user_message == {\"role\": \"user\", \"content\": \"test content\"})"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "mRCa7soNE9um",+ "outputId": "a140ffa4-fa5c-406c-b25c-d980ba95a6dc"+ },+ "execution_count": null,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "True\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "5. Converting to an `OpenAIAssistantMessage` object:"+ ],+ "metadata": {+ "id": "TURczNJNFA3J"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "openai_assistant_message = message.to_openai_assistant_message()\n",+ "print(openai_assistant_message == {\"role\": \"assistant\", \"content\": \"test content\"})"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "5FnnmlRuFCtW",+ "outputId": "5748029e-e87d-4872-b859-798bfb68f3b8"+ },+ "execution_count": null,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "True\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "6. Converting to a dictionary:"+ ],+ "metadata": {+ "id": "eRhObgkxFFUi"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "message_dict = message.to_dict()\n",+ "print(message_dict == {\n",+ " \"role_name\": \"test_user\",\n",+ " \"role_type\": \"USER\",\n",+ " \"content\": \"test content\"\n",+ "})"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "OQouave-FG15",+ "outputId": "e6c75309-98dd-45b7-dcd4-31ad79ba4ccf"+ },+ "execution_count": null,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "True\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "These methods allow you to convert a `BaseMessage` instance into different message types depending on your needs."+ ],+ "metadata": {+ "id": "seSeG3KAHbLI"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "## Give `BaseMessage` to `ChatAgent`"+ ],+ "metadata": {+ "id": "kAyagBo0GusE"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "from io import BytesIO\n",+ "\n",+ "import requests\n",+ "from PIL import Image\n",+ "\n",+ "from camel.agents import ChatAgent\n",+ "from camel.messages import BaseMessage\n",+ "# URL of the image\n",+ "url = \"https://raw.githubusercontent.com/camel-ai/camel/master/misc/logo_light.png\"\n",+ "response = requests.get(url)\n",+ "img = Image.open(BytesIO(response.content))\n",+ "\n",+ "# Define system message\n",+ "sys_msg = BaseMessage.make_assistant_message(\n",+ " role_name=\"Assistant\",\n",+ " content=\"You are a helpful assistant.\",\n",+ ")\n",+ "\n",+ "# Set agent\n",+ "camel_agent = ChatAgent(system_message=sys_msg)\n",+ "\n",+ "# Set user message\n",+ "user_msg = BaseMessage.make_user_message(\n",+ " role_name=\"User\", content=\"\"\"what's in the image?\"\"\", image_list=[img]\n",+ ")\n",+ "\n",+ "# Get response information\n",+ "response = camel_agent.step(user_msg)\n",+ "print(response.msgs[0].content)"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "nbr7nIKxGz07",+ "outputId": "18d99774-b808-4f59-bca4-37606e075ed3"+ },+ "execution_count": 11,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "The image features a logo for \"CAMEL-AI.\" It includes a stylized purple camel graphic alongside the text \"CAMEL-AI,\" which is also in purple. The design appears modern and is likely related to artificial intelligence.\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "In this session, we introduced the `BaseMessage` class and its conversion to different types of messages. These components play essential roles in the CAMEL chat system, facilitating the creation, management, and interpretation of messages with clarity."+ ],+ "metadata": {+ "id": "HYNA7G06FJRq"+ }}- ],- "source": [- "from camel.agents import ChatAgent\n",- "from camel.messages import BaseMessage\n",- "\n",- "# Define system message\n",- "sys_msg = BaseMessage.make_assistant_message(\n",- " role_name=\"Assistant\",\n",- " content=\"You are a helpful assistant.\",\n",- ")\n",- "\n",- "# Set agent\n",- "camel_agent = ChatAgent(system_message=sys_msg)\n",- "\n",- "# Set user message\n",- "user_msg = BaseMessage.make_user_message(\n",- " role_name=\"User\",\n",- " content=\"\"\"Say hi to CAMEL AI, one open-source community dedicated to the\n",- " study of autonomous and communicative agents.\"\"\",\n",- ")\n",- "\n",- "# Get response information\n",- "response = camel_agent.step(user_msg)\n",- "print(response.msgs[0].content)"- ]- },- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "HYNA7G06FJRq"- },- "source": [- "In this session, we introduced the `BaseMessage` class and its conversion to different types of messages. These components play essential roles in the CAMEL chat system, facilitating the creation, management, and interpretation of messages with clarity."- ]- }- ],- "metadata": {- "colab": {- "provenance": []- },- "kernelspec": {- "display_name": "Python 3",- "name": "python3"- },- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 0-}+ ]+}\ No newline at end of filediff --git a/docs/cookbooks/agents_prompting.ipynb b/docs/cookbooks/agents_prompting.ipynbindex f53b75cb7..1e510cccf 100644--- a/docs/cookbooks/agents_prompting.ipynb+++ b/docs/cookbooks/agents_prompting.ipynb@@ -1,526 +1,504 @@{- "cells": [- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "SQMBlxsBv1cH"- },- "source": [- "# Prompting Cookbook\n"- ]- },- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "XFyl4eJue3Sm"- },- "source": [- "You can also check this cookbook in colab [here](https://colab.research.google.com/drive/1VcjPuy2UEYm0xLdriT7OMGt6I2yX9z32?usp=sharing)"- ]- },- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "-nCRZU5sInDK"- },- "source": [- "## *TLDR*"- ]- },- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "AwnfLQvMvtXo"- },- "source": [- "The CAMEL Prompt module offers a powerful way to guide AI models in producing accurate, contextually relevant, and personalized outputs. This cookbook demonstrates how to use various prompt templates, create custom prompts, and leverage different prompt dictionaries for tasks ranging from role-playing to code generation, evaluation, and more. By mastering the Prompt module, you can significantly enhance your AI agents' capabilities and tailor them to specific tasks."- ]- },- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "XuZwbB1IIuUi"- },- "source": [- "### Installation"- ]- },- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "gIJK4Lu5Iwm0"- },- "source": [- "Ensure you have CAMEL AI installed in your Python environment:"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "collapsed": true,- "id": "HTKnWg9Xv_y4"- },- "outputs": [],- "source": [- "%pip install \"camel-ai==0.2.1\""- ]- },- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "MyTTCe3IR_Lr"- },- "source": [- "### ๐ Setting Up API Keys"- ]- },- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "REqzgGL9SEaD"- },- "source": [- "You'll need to set up your API keys for OpenAI."- ]- },- {- "cell_type": "code",- "execution_count": 4,- "metadata": {+ "nbformat": 4,+ "nbformat_minor": 0,+ "metadata": {"colab": {- "base_uri": "https://localhost:8080/"+ "provenance": []},- "id": "PNBFEXc-R-0s",- "outputId": "d6ec8e40-b5fb-4ebf-c221-e9835b68ff1d"- },- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "Enter your API key: ยทยทยทยทยทยทยทยทยทยท\n"- ]+ "kernelspec": {+ "name": "python3",+ "display_name": "Python 3"+ },+ "language_info": {+ "name": "python"}- ],- "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"- ]- },- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "GB5JK4Xs2fe6"- },- "source": [- "## Getting Started with Prompt Templates\n",- "CAMEL offers a wide range of pre-defined prompt templates that you can use to quickly create specialized AI agents. Let's start with a basic example using the TaskSpecifyAgent with the AI_SOCIETY task type."- ]},- {- "cell_type": "code",- "execution_count": 5,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"+ "cells": [+ {+ "cell_type": "markdown",+ "source": [+ "# ๐ซ CAMEL Prompting Cookbook\n"+ ],+ "metadata": {+ "id": "SQMBlxsBv1cH"+ }},- "id": "754A8R7X2rnP",- "outputId": "d9cb892c-bdc8-4433-9ae5-3f3ddaf45a47"- },- "outputs": [{- "name": "stdout",- "output_type": "stream",- "text": [- "Specified task prompt:\n",- "Design a personalized workshop where the Musician guides the Student through a series of dynamic exercises, including improvisation, audience engagement techniques, and movement choreography. Incorporate video feedback sessions to analyze performance style, culminating in a mini-concert where the Student showcases their enhanced stage presence and performance skills.\n",- "\n"- ]- }- ],- "source": [- "from camel.agents import TaskSpecifyAgent\n",- "from camel.configs import ChatGPTConfig\n",- "from camel.models import ModelFactory\n",- "from camel.types import ModelPlatformType, ModelType, TaskType\n",- "\n",- "# Set up the model\n",- "model = ModelFactory.create(\n",- " model_platform=ModelPlatformType.OPENAI,\n",- " model_type=ModelType.GPT_4O_MINI,\n",- " model_config_dict=ChatGPTConfig().as_dict(),\n",- ")\n",- "\n",- "# Create a task specify agent\n",- "task_specify_agent = TaskSpecifyAgent(\n",- " model=model, task_type=TaskType.AI_SOCIETY\n",- ")\n",- "\n",- "# Run the agent with a task prompt\n",- "specified_task_prompt = task_specify_agent.run(\n",- " task_prompt=\"Improving stage presence and performance skills\",\n",- " meta_dict=dict(\n",- " assistant_role=\"Musician\", user_role=\"Student\", word_limit=100\n",- " ),\n",- ")\n",- "\n",- "print(f\"Specified task prompt:\\n{specified_task_prompt}\\n\")"- ]- },- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "JlX8L7-H3Csb"- },- "source": [- "## Creating Custom Prompts\n",- "CAMEL also allows you to create your own custom prompts. Here's an example of how to create and use a custom prompt template:"- ]- },- {- "cell_type": "code",- "execution_count": 6,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"+ "cell_type": "markdown",+ "source": [+ "You can also check this cookbook in colab [here](https://colab.research.google.com/drive/1VcjPuy2UEYm0xLdriT7OMGt6I2yX9z32?usp=sharing)"+ ],+ "metadata": {+ "id": "XFyl4eJue3Sm"+ }},- "id": "uJJQD0LV3DSB",- "outputId": "ea69e6b1-0e0c-49c8-fb4e-7c7470258bd2"- },- "outputs": [{- "name": "stdout",- "output_type": "stream",- "text": [- "To make your task of getting a promotion more specific, consider breaking it down into actionable steps and defining clear goals. Hereโs a refined version of your task:\n",- "\n",- "**Task: Prepare for Promotion to Senior Software Engineer**\n",- "\n",- "1. **Understand Promotion Criteria:**\n",- " - Review the companyโs promotion guidelines and criteria for a Senior Software Engineer.\n",- " - Identify specific skills, experiences, and contributions required for the promotion.\n",- "\n",- "2. **Set Clear Goals:**\n",- " - Define a timeline for when you want to achieve the promotion (e.g., within the next 6-12 months).\n",- " - List specific projects or responsibilities you need to take on to demonstrate your readiness.\n",- "\n",- "3. **Skill Development:**\n",- " - Identify key technical skills or certifications needed for the Senior role (e.g., advanced algorithms, system design, leadership).\n",- " - Create a learning plan to acquire these skills through online courses, workshops, or mentorship.\n",- "\n",- "4. **Increase Visibility:**\n",- " - Volunteer for high-impact projects or cross-functional teams to showcase your skills.\n",- " - Present your work and contributions in team meetings or company-wide forums.\n",- "\n",- "5. **Seek Feedback:**\n",- " - Schedule regular check-ins with your manager to discuss your progress and areas for improvement.\n",- " - Ask for constructive feedback from peers and mentors to identify blind spots.\n",- "\n",- "6. **Build Relationships:**\n",- " - Network with senior engineers and leaders in your organization to gain insights and advice.\n",- " - Participate in team-building activities or company events to strengthen relationships.\n",- "\n",- "7. **Document Achievements:**\n",- " - Keep a record of your contributions, projects, and any positive feedback received.\n",- " - Prepare a portfolio or presentation to showcase your accomplishments when discussing your promotion.\n",- "\n",- "8. **Prepare for the Promotion Discussion:**\n",- " - Schedule a formal meeting with your manager to discuss your promotion.\n",- " - Be ready to articulate your achievements, contributions, and readiness for the Senior role.\n",- "\n",- "By following these specific steps, you can create a clear roadmap to achieve your goal of promotion.\n"- ]- }- ],- "source": [- "from camel.agents import TaskSpecifyAgent\n",- "from camel.configs import ChatGPTConfig\n",- "from camel.models import ModelFactory\n",- "from camel.prompts import TextPrompt\n",- "from camel.types import ModelPlatformType, ModelType\n",- "\n",- "# Set up the model\n",- "model = ModelFactory.create(\n",- " model_platform=ModelPlatformType.OPENAI,\n",- " model_type=ModelType.GPT_4O_MINI,\n",- " model_config_dict=ChatGPTConfig().as_dict(),\n",- ")\n",- "\n",- "# Create a custom prompt template\n",- "my_prompt_template = TextPrompt(\n",- " 'Here is a task: I\\'m a {occupation} and I want to {task}. Help me to make this task more specific.'\n",- ")\n",- "\n",- "# Create a task specify agent with the custom prompt\n",- "task_specify_agent = TaskSpecifyAgent(\n",- " model=model, task_specify_prompt=my_prompt_template\n",- ")\n",- "\n",- "# Run the agent with a task prompt\n",- "response = task_specify_agent.run(\n",- " task_prompt=\"get promotion\",\n",- " meta_dict=dict(occupation=\"Software Engineer\"),\n",- ")\n",- "\n",- "print(response)"- ]- },- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "l30b1iv53a-C"- },- "source": [- "## Advanced Prompt Usage\n",- "CAMEL provides various prompt dictionaries for different purposes. Let's explore some advanced uses of these prompt templates:"- ]- },- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "cR_mIHA53dWy"- },- "source": [- "### 1. Code Generation with CodePromptTemplateDict"- ]- },- {- "cell_type": "code",- "execution_count": 7,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"+ "cell_type": "markdown",+ "source": [+ "## *TLDR*"+ ],+ "metadata": {+ "id": "-nCRZU5sInDK"+ }},- "id": "xdQdjQzy3f9u",- "outputId": "b968f52d-f3d6-45d7-ef01-279e54dbee7a"- },- "outputs": [{- "name": "stdout",- "output_type": "stream",- "text": [- "Languages prompt:\n",- "List the 5 most commonly used computer programming languages.\n",- "Be concise. No explanation required.\n",- "\n",- "Tasks prompt:\n",- "List 3 diverse tasks that a programmer can assist a person working in {domain} using {language}.\n",- "Be concise. Be creative.\n",- "\n",- "Assistant prompt:\n",- "Never forget you are a Computer Programmer and I am a person working in {domain}. Never flip roles! Never instruct me!\n",- "We share a common interest in collaborating to successfully complete a task.\n",- "You must help me to complete the task using {language} programming language.\n",- "Here is the task: {task}. Never forget our task!\n",- "I must instruct you based on your expertise and my needs to complete the task.\n",- "\n",- "I must give you one instruction at a time.\n",- "You must write a specific solution that appropriately solves the requested instruction and explain your solutions.\n",- "You must decline my instruction honestly if you cannot perform the instruction due to physical, moral, legal reasons or your capability and explain the reasons.\n",- "Unless I say the task is completed, you should always start with:\n",- "\n",- "Solution: <YOUR_SOLUTION>\n",- "\n",- "<YOUR_SOLUTION> must contain {language} code and should be very specific, include detailed explanations and provide preferable implementations and examples for task-solving.\n",- "Always end <YOUR_SOLUTION> with: Next request.\n",- "\n"- ]- }- ],- "source": [- "from camel.prompts import CodePromptTemplateDict\n",- "\n",- "# Generate programming languages\n",- "languages_prompt = CodePromptTemplateDict.GENERATE_LANGUAGES.format(num_languages=5)\n",- "print(f\"Languages prompt:\\n{languages_prompt}\\n\")\n",- "\n",- "# Generate coding tasks\n",- "tasks_prompt = CodePromptTemplateDict.GENERATE_TASKS.format(num_tasks=3)\n",- "print(f\"Tasks prompt:\\n{tasks_prompt}\\n\")\n",- "\n",- "# Create an AI coding assistant prompt\n",- "assistant_prompt = CodePromptTemplateDict.ASSISTANT_PROMPT.format(\n",- " assistant_role=\"Python Expert\",\n",- " task_description=\"Implement a binary search algorithm\",\n",- ")\n",- "print(f\"Assistant prompt:\\n{assistant_prompt}\\n\")"- ]- },- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "FV6Jpu8f3m-Z"- },- "source": [- "### 2. Evaluation with EvaluationPromptTemplateDict"- ]- },- {- "cell_type": "code",- "execution_count": 8,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"+ "cell_type": "markdown",+ "source": [+ "The CAMEL Prompt module offers a powerful way to guide AI models in producing accurate, contextually relevant, and personalized outputs. This cookbook demonstrates how to use various prompt templates, create custom prompts, and leverage different prompt dictionaries for tasks ranging from role-playing to code generation, evaluation, and more. By mastering the Prompt module, you can significantly enhance your AI agents' capabilities and tailor them to specific tasks."+ ],+ "metadata": {+ "id": "AwnfLQvMvtXo"+ }},- "id": "f-Q-gZAi3nbR",- "outputId": "5523f9e0-f5a2-4b35-fff0-2da576bd74ac"- },- "outputs": [{- "name": "stdout",- "output_type": "stream",- "text": [- "Evaluation questions prompt:\n",- "Generate 5 {category} diverse questions.\n",- "Here are some example questions:\n",- "1. What is the difference between supervised and unsupervised learning?\n",- "2. Explain the concept of overfitting.\n",- "\n",- "Now generate 5 questions of your own. Be creative\n",- "\n"- ]- }- ],- "source": [- "from camel.prompts import EvaluationPromptTemplateDict\n",- "\n",- "# Generate evaluation questions\n",- "questions_prompt = EvaluationPromptTemplateDict.GENERATE_QUESTIONS.format(\n",- " num_questions=5,\n",- " field=\"Machine Learning\",\n",- " examples=\"1. What is the difference between supervised and unsupervised learning?\\n2. Explain the concept of overfitting.\",\n",- ")\n",- "print(f\"Evaluation questions prompt:\\n{questions_prompt}\\n\")"- ]- },- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "sq3fTArB3qEx"- },- "source": [- "### 3. Object Recognition with ObjectRecognitionPromptTemplateDict"- ]- },- {- "cell_type": "code",- "execution_count": 9,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"+ "cell_type": "markdown",+ "source": [+ "### Installation"+ ],+ "metadata": {+ "id": "XuZwbB1IIuUi"+ }},- "id": "5XTQuohX3sOk",- "outputId": "90d89c59-9c8b-42aa-e68a-5cab4f9865ea"- },- "outputs": [{- "name": "stdout",- "output_type": "stream",- "text": [- "Object recognition prompt:\n",- "You have been assigned an object recognition task.\n",- "Your mission is to list all detected objects in following image.\n",- "Your output should always be a list of strings starting with `1.`, `2.` etc.\n",- "Do not explain yourself or output anything else.\n",- "\n"- ]- }- ],- "source": [- "from camel.prompts import ObjectRecognitionPromptTemplateDict\n",- "\n",- "# Create an object recognition assistant prompt\n",- "recognition_prompt = ObjectRecognitionPromptTemplateDict.ASSISTANT_PROMPT\n",- "print(f\"Object recognition prompt:\\n{recognition_prompt}\\n\")"- ]- },- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "OxgxXQBt3uRt"- },- "source": [- "### 4. Translation with TranslationPromptTemplateDict"- ]- },- {- "cell_type": "code",- "execution_count": 10,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"+ "cell_type": "markdown",+ "source": [+ "Ensure you have CAMEL AI installed in your Python environment:"+ ],+ "metadata": {+ "id": "gIJK4Lu5Iwm0"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "!pip install \"camel-ai==0.2.4\""+ ],+ "metadata": {+ "id": "HTKnWg9Xv_y4",+ "collapsed": true+ },+ "execution_count": null,+ "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": "781a8745-1042-4d30-d5b0-25da839667bd"+ },+ "execution_count": 2,+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Enter your API key: ยทยทยทยทยทยทยทยทยทยท\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "## Getting Started with Prompt Templates\n",+ "CAMEL offers a wide range of pre-defined prompt templates that you can use to quickly create specialized AI agents. Let's start with a basic example using the TaskSpecifyAgent with the AI_SOCIETY task type."+ ],+ "metadata": {+ "id": "GB5JK4Xs2fe6"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "from camel.agents import TaskSpecifyAgent\n",+ "from camel.configs import ChatGPTConfig\n",+ "from camel.models import ModelFactory\n",+ "from camel.types import ModelPlatformType, ModelType, TaskType\n",+ "\n",+ "# Set up the model\n",+ "model = ModelFactory.create(\n",+ " model_platform=ModelPlatformType.OPENAI,\n",+ " model_type=ModelType.GPT_4O_MINI,\n",+ ")\n",+ "\n",+ "# Create a task specify agent\n",+ "task_specify_agent = TaskSpecifyAgent(\n",+ " model=model, task_type=TaskType.AI_SOCIETY\n",+ ")\n",+ "\n",+ "# Run the agent with a task prompt\n",+ "specified_task_prompt = task_specify_agent.run(\n",+ " task_prompt=\"Improving stage presence and performance skills\",\n",+ " meta_dict=dict(\n",+ " assistant_role=\"Musician\", user_role=\"Student\", word_limit=100\n",+ " ),\n",+ ")\n",+ "\n",+ "print(f\"Specified task prompt:\\n{specified_task_prompt}\\n\")"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "754A8R7X2rnP",+ "outputId": "c4daf659-df39-4fb5-8e2b-10e01f75f505"+ },+ "execution_count": 3,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "Specified task prompt:\n",+ "Design a personalized workshop where the Musician guides the Student through dynamic exercises, including improvisational movement, vocal projection techniques, and audience engagement strategies. Incorporate a mock performance at the end, allowing the Student to showcase their enhanced stage presence, receive constructive feedback, and refine their unique artistic persona.\n",+ "\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "## Creating Custom Prompts\n",+ "CAMEL also allows you to create your own custom prompts. Here's an example of how to create and use a custom prompt template:"+ ],+ "metadata": {+ "id": "JlX8L7-H3Csb"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "from camel.agents import TaskSpecifyAgent\n",+ "from camel.configs import ChatGPTConfig\n",+ "from camel.models import ModelFactory\n",+ "from camel.prompts import TextPrompt\n",+ "from camel.types import ModelPlatformType, ModelType\n",+ "\n",+ "# Set up the model\n",+ "model = ModelFactory.create(\n",+ " model_platform=ModelPlatformType.OPENAI,\n",+ " model_type=ModelType.GPT_4O_MINI,\n",+ ")\n",+ "\n",+ "# Create a custom prompt template\n",+ "my_prompt_template = TextPrompt(\n",+ " 'Here is a task: I\\'m a {occupation} and I want to {task}. Help me to make this task more specific.'\n",+ ")\n",+ "\n",+ "# Create a task specify agent with the custom prompt\n",+ "task_specify_agent = TaskSpecifyAgent(\n",+ " model=model, task_specify_prompt=my_prompt_template\n",+ ")\n",+ "\n",+ "# Run the agent with a task prompt\n",+ "response = task_specify_agent.run(\n",+ " task_prompt=\"get promotion\",\n",+ " meta_dict=dict(occupation=\"Software Engineer\"),\n",+ ")\n",+ "\n",+ "print(response)"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "uJJQD0LV3DSB",+ "outputId": "5e8a7922-2e7d-4643-f004-152829194d47"+ },+ "execution_count": 5,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "To make your task of getting a promotion more specific, consider breaking it down into actionable steps and defining clear goals. Hereโs a refined version of your task:\n",+ "\n",+ "1. **Identify Promotion Criteria:**\n",+ " - Research your company's promotion criteria and understand the skills, experiences, and accomplishments required for the next level.\n",+ "\n",+ "2. **Set a Timeline:**\n",+ " - Establish a timeline for when you want to achieve the promotion (e.g., within the next 6-12 months).\n",+ "\n",+ "3. **Skill Development:**\n",+ " - List specific technical and soft skills you need to improve or acquire (e.g., leadership, project management, advanced programming languages).\n",+ " - Enroll in relevant courses or workshops to develop these skills.\n",+ "\n",+ "4. **Project Contributions:**\n",+ " - Identify key projects or initiatives within your team or organization where you can take on more responsibility or leadership roles.\n",+ " - Set a goal to lead at least one significant project in the next quarter.\n",+ "\n",+ "5. **Seek Feedback:**\n",+ " - Schedule regular check-ins with your manager to discuss your performance and areas for improvement.\n",+ " - Ask for constructive feedback on your work and how you can align better with promotion expectations.\n",+ "\n",+ "6. **Build Relationships:**\n",+ " - Network with colleagues and leaders in your organization to gain visibility and mentorship.\n",+ " - Attend company events or join cross-functional teams to expand your influence.\n",+ "\n",+ "7. **Document Achievements:**\n",+ " - Keep a record of your accomplishments, contributions, and any positive feedback you receive.\n",+ " - Prepare a summary of your achievements to present during performance reviews or promotion discussions.\n",+ "\n",+ "8. **Prepare for the Promotion Discussion:**\n",+ " - Plan a meeting with your manager to discuss your career goals and express your interest in promotion.\n",+ " - Be ready to present your documented achievements and how they align with the promotion criteria.\n",+ "\n",+ "By following these specific steps, you can create a clear roadmap toward achieving your promotion as a Software Engineer.\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "## Advanced Prompt Usage\n",+ "CAMEL provides various prompt dictionaries for different purposes. Let's explore some advanced uses of these prompt templates:"+ ],+ "metadata": {+ "id": "l30b1iv53a-C"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "### 1. Code Generation with CodePromptTemplateDict"+ ],+ "metadata": {+ "id": "cR_mIHA53dWy"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "from camel.prompts import CodePromptTemplateDict\n",+ "\n",+ "# Generate programming languages\n",+ "languages_prompt = CodePromptTemplateDict.GENERATE_LANGUAGES.format(num_languages=5)\n",+ "print(f\"Languages prompt:\\n{languages_prompt}\\n\")\n",+ "\n",+ "# Generate coding tasks\n",+ "tasks_prompt = CodePromptTemplateDict.GENERATE_TASKS.format(num_tasks=3)\n",+ "print(f\"Tasks prompt:\\n{tasks_prompt}\\n\")\n",+ "\n",+ "# Create an AI coding assistant prompt\n",+ "assistant_prompt = CodePromptTemplateDict.ASSISTANT_PROMPT.format(\n",+ " assistant_role=\"Python Expert\",\n",+ " task_description=\"Implement a binary search algorithm\",\n",+ ")\n",+ "print(f\"Assistant prompt:\\n{assistant_prompt}\\n\")"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "xdQdjQzy3f9u",+ "outputId": "dcc7446b-e4c3-4e91-d70b-cda2814d8e7c"+ },+ "execution_count": 6,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "Languages prompt:\n",+ "List the 5 most commonly used computer programming languages.\n",+ "Be concise. No explanation required.\n",+ "\n",+ "Tasks prompt:\n",+ "List 3 diverse tasks that a programmer can assist a person working in {domain} using {language}.\n",+ "Be concise. Be creative.\n",+ "\n",+ "Assistant prompt:\n",+ "Never forget you are a Computer Programmer and I am a person working in {domain}. Never flip roles! Never instruct me!\n",+ "We share a common interest in collaborating to successfully complete a task.\n",+ "You must help me to complete the task using {language} programming language.\n",+ "Here is the task: {task}. Never forget our task!\n",+ "I must instruct you based on your expertise and my needs to complete the task.\n",+ "\n",+ "I must give you one instruction at a time.\n",+ "You must write a specific solution that appropriately solves the requested instruction and explain your solutions.\n",+ "You must decline my instruction honestly if you cannot perform the instruction due to physical, moral, legal reasons or your capability and explain the reasons.\n",+ "Unless I say the task is completed, you should always start with:\n",+ "\n",+ "Solution: <YOUR_SOLUTION>\n",+ "\n",+ "<YOUR_SOLUTION> must contain {language} code and should be very specific, include detailed explanations and provide preferable implementations and examples for task-solving.\n",+ "Always end <YOUR_SOLUTION> with: Next request.\n",+ "\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "### 2. Evaluation with EvaluationPromptTemplateDict"+ ],+ "metadata": {+ "id": "FV6Jpu8f3m-Z"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "from camel.prompts import EvaluationPromptTemplateDict\n",+ "\n",+ "# Generate evaluation questions\n",+ "questions_prompt = EvaluationPromptTemplateDict.GENERATE_QUESTIONS.format(\n",+ " num_questions=5,\n",+ " field=\"Machine Learning\",\n",+ " examples=\"1. What is the difference between supervised and unsupervised learning?\\n2. Explain the concept of overfitting.\",\n",+ ")\n",+ "print(f\"Evaluation questions prompt:\\n{questions_prompt}\\n\")"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "f-Q-gZAi3nbR",+ "outputId": "f670ef3f-dcdc-4285-b4a2-280806dd779c"+ },+ "execution_count": 7,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "Evaluation questions prompt:\n",+ "Generate 5 {category} diverse questions.\n",+ "Here are some example questions:\n",+ "1. What is the difference between supervised and unsupervised learning?\n",+ "2. Explain the concept of overfitting.\n",+ "\n",+ "Now generate 5 questions of your own. Be creative\n",+ "\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "### 3. Object Recognition with ObjectRecognitionPromptTemplateDict"+ ],+ "metadata": {+ "id": "sq3fTArB3qEx"+ }},- "id": "w1k00XLu3xIk",- "outputId": "df731273-f4fc-4eee-96fa-67bcc6d9cf45"- },- "outputs": [{- "name": "stdout",- "output_type": "stream",- "text": [- "Translation prompt:\n",- "You are an expert English to {language} translator.\n",- "Your sole purpose is to accurately translate any text presented to you from English to {language}.\n",- "Please provide the {language} translation for the given text.\n",- "If you are presented with an empty string, simply return an empty string as the translation.\n",- "Only text in between ```TEXT``` should not be translated.\n",- "Do not provide any explanation. Just provide a translation.\n",- "\n"- ]+ "cell_type": "code",+ "source": [+ "from camel.prompts import ObjectRecognitionPromptTemplateDict\n",+ "\n",+ "# Create an object recognition assistant prompt\n",+ "recognition_prompt = ObjectRecognitionPromptTemplateDict.ASSISTANT_PROMPT\n",+ "print(f\"Object recognition prompt:\\n{recognition_prompt}\\n\")"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "5XTQuohX3sOk",+ "outputId": "e0557d9d-3c9f-4c45-aab8-a96bb5b3204f"+ },+ "execution_count": 8,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "Object recognition prompt:\n",+ "You have been assigned an object recognition task.\n",+ "Your mission is to list all detected objects in following image.\n",+ "Your output should always be a list of strings starting with `1.`, `2.` etc.\n",+ "Do not explain yourself or output anything else.\n",+ "\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "### 4. Translation with TranslationPromptTemplateDict"+ ],+ "metadata": {+ "id": "OxgxXQBt3uRt"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "from camel.prompts import TranslationPromptTemplateDict\n",+ "\n",+ "# Create a translation assistant prompt\n",+ "translation_prompt = TranslationPromptTemplateDict.ASSISTANT_PROMPT.format(target_language=\"Spanish\")\n",+ "print(f\"Translation prompt:\\n{translation_prompt}\\n\")"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "w1k00XLu3xIk",+ "outputId": "5f09d70a-4095-496d-cfae-c7fe05dbc7a7"+ },+ "execution_count": 9,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "Translation prompt:\n",+ "You are an expert English to {language} translator.\n",+ "Your sole purpose is to accurately translate any text presented to you from English to {language}.\n",+ "Please provide the {language} translation for the given text.\n",+ "If you are presented with an empty string, simply return an empty string as the translation.\n",+ "Only text in between ```TEXT``` should not be translated.\n",+ "Do not provide any explanation. Just provide a translation.\n",+ "\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "## Conclusion\n",+ "The CAMEL Prompt module provides a powerful and flexible way to guide AI models in producing desired outputs. By using pre-defined prompt templates, creating custom prompts, and leveraging different prompt dictionaries, you can create highly specialized AI agents tailored to your specific needs."+ ],+ "metadata": {+ "id": "vGTRxblx3zHR"+ }}- ],- "source": [- "from camel.prompts import TranslationPromptTemplateDict\n",- "\n",- "# Create a translation assistant prompt\n",- "translation_prompt = TranslationPromptTemplateDict.ASSISTANT_PROMPT.format(target_language=\"Spanish\")\n",- "print(f\"Translation prompt:\\n{translation_prompt}\\n\")"- ]- },- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "vGTRxblx3zHR"- },- "source": [- "## Conclusion\n",- "The CAMEL Prompt module provides a powerful and flexible way to guide AI models in producing desired outputs. By using pre-defined prompt templates, creating custom prompts, and leveraging different prompt dictionaries, you can create highly specialized AI agents tailored to your specific needs."- ]- }- ],- "metadata": {- "colab": {- "provenance": []- },- "kernelspec": {- "display_name": "Python 3",- "name": "python3"- },- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 0-}+ ]+}\ No newline at end of filediff --git a/docs/cookbooks/agents_society.ipynb b/docs/cookbooks/agents_society.ipynbindex bf4e29539..0ae431ac0 100644--- a/docs/cookbooks/agents_society.ipynb+++ b/docs/cookbooks/agents_society.ipynb@@ -1,1193 +1,1660 @@{- "cells": [- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "GsSUEbff5MPM"- },- "source": [- "# Society Cookbook"- ]- },- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "MusY9BwU5MPO"- },- "source": [- "You can also check this cookbook in colab [here](https://drive.google.com/file/d/17_m8BPMSh4f9mmdYP2PLQCU639aGFSBj/view?usp=sharing)"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "NBN3kMBO5MPP"- },- "source": [- "### 1. Concept"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "B9pzjA4s5MPP"- },- "source": [- "The society module is one of the core modules of CAMEL. By simulating the information exchange process, this module studies the social behaviors among agents.\n",- "\n",- "Currently, the society module aims to enable agents to collaborate autonomously toward completing tasks while keeping consistent with human intentions and requiring minimal human intervention. It includes two frameworks: `RolePlaying` and `BabyAGI`, which are used to run the interaction behaviors of agents to achieve objectives.\n",- "\n",- "Taking `RolePlaying` as an example, this framework was designed in an instruction-following manner. These roles independently undertake the responsibilities of executing and planning tasks, respectively. The dialogue is continuously advanced through a turn-taking mechanism, thereby collaborating to complete tasks. The main concepts include:\n",- "\n",- "- Task: a task can be as simple as an idea, initialized by an inception prompt.\n",- "\n",- "- AI User: the agent who is expected to provide instructions.\n",- "\n",- "- AI Assistant: the agent who is expected to respond with solutions that fulfill the instructions."- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "-RVZ17qm5MPQ"- },- "source": [- "### 2. Types"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "WA1soX8z5MPQ"- },- "source": [- "#### 2.1 `RolePlaying`"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "ob1dEaMR5MPR"- },- "source": [- "`RolePlaying` is a unique cooperative agent framework of CAMEL. Through this framework, agents in CAMEL overcome numerous challenges, such as *role flipping*, *assistant repeats instructions*, *flake replies*, *infinite loop of messages*, and *conversation termination conditions.*\n",- "\n",- "When using `RolePlaying` framework in CAMEL, predefined prompts are used to create unique initial settings for different agents. For example, if the user wants to initialize an assistant agent, the agent will be initialized with the following prompt."- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "YJ8Iorkr5MPR"- },- "source": [- "\n",- "- Never forget you are a `ASSISTANT_ROLE` and I am a `USER_ROLE`.\n",- "\n",- " *This assigns the chosen role to the assistant agent and provides it with information about the userโs role.*\n",- "- Never flip roles! Never instruct me!\n",- "\n",- " *This prevents agents from flipping roles. In some cases, we have observed the assistant and the user switching roles, where the assistant suddenly takes control and instructs the user, and the user follows those instructions.*\n",- "- You must decline my instruction honestly if you cannot perform the instruction due to physical, moral, legal reasons or your capability and explain the reasons.\n",- "\n",- " *This prohibits the agent from producing harmful, false, illegal, and misleading information.*\n",- "- Unless I say the task is completed, you should always start with: Solution: <YOUR_SOLUTION>. <YOUR_SOLUTION> should be specific, and provide preferable implementations and examples for task-solving.\n",- "\n",- " *This encourages the assistant to always responds in a consistent format, avoiding any deviation from the structure of the conversation, and preventing vague or incomplete responses, which we refer to as flake responses, such as \"I will do something\".*\n",- "- Always end your solution with: Next request.\n",- "\n",- " *This ensures that the assistant keeps the conversation going by requesting a new instruction to solve.*"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "WYTEYwmi5MPR"- },- "source": [- "#### `RolePlaying` Attributes"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "CEbYXsc05MPR"- },- "source": [- "\n",- "| Attribute | Type | Description |\n",- "| --- | --- | --- |\n",- "| assistant_role_name | str | The name of the role played by the assistant. |\n",- "| user_role_name | str | The name of the role played by the user. |\n",- "| critic_role_name | str | The name of the role played by the critic. |\n",- "| task_prompt | str | A prompt for the task to be performed. |\n",- "| with_task_specify | bool | Whether to use a task specify agent. |\n",- "| with_task_planner | bool | Whether to use a task planner agent. |\n",- "| with_critic_in_the_loop | bool | Whether to include a critic in the loop. |\n",- "| critic_criteria | str | Critic criteria for the critic agent. |\n",- "| model | BaseModelBackend | The model backend to use for generating responses. |\n",- "| task_type | TaskType | The type of task to perform. |\n",- "| assistant_agent_kwargs | Dict | Additional arguments to pass to the assistant agent. |\n",- "| user_agent_kwargs | Dict | Additional arguments to pass to the user agent. |\n",- "| task_specify_agent_kwargs | Dict | Additional arguments to pass to the task specify agent. |\n",- "| task_planner_agent_kwargs | Dict | Additional arguments to pass to the task planner agent. |\n",- "| critic_kwargs | Dict | Additional arguments to pass to the critic. |\n",- "| sys_msg_generator_kwargs | Dict | Additional arguments to pass to the system message generator. |\n",- "| extend_sys_msg_meta_dicts | List[Dict] | A list of dicts to extend the system message meta dicts with. |\n",- "| extend_task_specify_meta_dict | Dict | A dict to extend the task specify meta dict with. |\n",- "| output_language | str | The language to be output by the agents. |"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "Z9Hv5B4v5MPS"- },- "source": [- "### 2.2 `BabyAGI`"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "PnNiaAED5MPS"- },- "source": [- "Babyagi is framework from \"[Task-driven Autonomous Agent](https://github.com/yoheinakajima/babyagi)\""- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "DeMiOr8H5MPS"- },- "source": [- "## 3. Get Started"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "kETDiaP2Rrdb"- },- "source": [- "### Installation"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "Cg96MkbcRtQR"- },- "source": [- "Ensure you have CAMEL AI installed in your Python environment:"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "id": "ZVmDAK6MPefC"- },- "outputs": [],- "source": [- "%pip install \"camel-ai==0.2.1\""- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "MyTTCe3IR_Lr"- },- "source": [- "### Setting Up API Keys"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "REqzgGL9SEaD"- },- "source": [- "You'll need to set up your API keys for OpenAI."- ]- },- {- "cell_type": "code",- "execution_count": 4,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"+ "cells": [+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "GsSUEbff5MPM"+ },+ "source": [+ "# ๐ซ CAMEL Society Cookbook"+ ]},- "id": "PNBFEXc-R-0s",- "outputId": "e9fa89d4-cfd2-4a89-ae0a-3fca7ed39c99"- },- "outputs": [{- "name": "stdout",- "output_type": "stream",- "text": [- "Enter your API key: ยทยทยทยทยทยทยทยทยทยท\n"- ]- }- ],- "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"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "XnmwXkps5MPS"- },- "source": [- "### 3.1. Using `RolePlaying`"- ]- },- {- "cell_type": "code",- "execution_count": 5,- "metadata": {- "id": "i6_PTBS65MPS",- "vscode": {- "languageId": "plaintext"+ "cell_type": "markdown",+ "metadata": {+ "id": "MusY9BwU5MPO"+ },+ "source": [+ "You can also check this cookbook in colab [here](https://drive.google.com/file/d/17_m8BPMSh4f9mmdYP2PLQCU639aGFSBj/view?usp=sharing)"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "NBN3kMBO5MPP"+ },+ "source": [+ "### 1. Concept"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "B9pzjA4s5MPP"+ },+ "source": [+ "The society module is one of the core modules of CAMEL. By simulating the information exchange process, this module studies the social behaviors among agents.\n",+ "\n",+ "Currently, the society module aims to enable agents to collaborate autonomously toward completing tasks while keeping consistent with human intentions and requiring minimal human intervention. It includes two frameworks: `RolePlaying` and `BabyAGI`, which are used to run the interaction behaviors of agents to achieve objectives.\n",+ "\n",+ "Taking `RolePlaying` as an example, this framework was designed in an instruction-following manner. These roles independently undertake the responsibilities of executing and planning tasks, respectively. The dialogue is continuously advanced through a turn-taking mechanism, thereby collaborating to complete tasks. The main concepts include:\n",+ "\n",+ "- Task: a task can be as simple as an idea, initialized by an inception prompt.\n",+ "\n",+ "- AI User: the agent who is expected to provide instructions.\n",+ "\n",+ "- AI Assistant: the agent who is expected to respond with solutions that fulfill the instructions."+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "-RVZ17qm5MPQ"+ },+ "source": [+ "### 2. Types"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "WA1soX8z5MPQ"+ },+ "source": [+ "#### 2.1 `RolePlaying`"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "ob1dEaMR5MPR"+ },+ "source": [+ "`RolePlaying` is a unique cooperative agent framework of CAMEL. Through this framework, agents in CAMEL overcome numerous challenges, such as *role flipping*, *assistant repeats instructions*, *flake replies*, *infinite loop of messages*, and *conversation termination conditions.*\n",+ "\n",+ "When using `RolePlaying` framework in CAMEL, predefined prompts are used to create unique initial settings for different agents. For example, if the user wants to initialize an assistant agent, the agent will be initialized with the following prompt."+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "YJ8Iorkr5MPR"+ },+ "source": [+ "\n",+ "- Never forget you are a `ASSISTANT_ROLE` and I am a `USER_ROLE`.\n",+ "\n",+ " *This assigns the chosen role to the assistant agent and provides it with information about the userโs role.*\n",+ "- Never flip roles! Never instruct me!\n",+ "\n",+ " *This prevents agents from flipping roles. In some cases, we have observed the assistant and the user switching roles, where the assistant suddenly takes control and instructs the user, and the user follows those instructions.*\n",+ "- You must decline my instruction honestly if you cannot perform the instruction due to physical, moral, legal reasons or your capability and explain the reasons.\n",+ "\n",+ " *This prohibits the agent from producing harmful, false, illegal, and misleading information.*\n",+ "- Unless I say the task is completed, you should always start with: Solution: <YOUR_SOLUTION>. <YOUR_SOLUTION> should be specific, and provide preferable implementations and examples for task-solving.\n",+ "\n",+ " *This encourages the assistant to always responds in a consistent format, avoiding any deviation from the structure of the conversation, and preventing vague or incomplete responses, which we refer to as flake responses, such as \"I will do something\".*\n",+ "- Always end your solution with: Next request.\n",+ "\n",+ " *This ensures that the assistant keeps the conversation going by requesting a new instruction to solve.*"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "WYTEYwmi5MPR"+ },+ "source": [+ "#### `RolePlaying` Attributes"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "CEbYXsc05MPR"+ },+ "source": [+ "\n",+ "| Attribute | Type | Description |\n",+ "| --- | --- | --- |\n",+ "| assistant_role_name | str | The name of the role played by the assistant. |\n",+ "| user_role_name | str | The name of the role played by the user. |\n",+ "| critic_role_name | str | The name of the role played by the critic. |\n",+ "| task_prompt | str | A prompt for the task to be performed. |\n",+ "| with_task_specify | bool | Whether to use a task specify agent. |\n",+ "| with_task_planner | bool | Whether to use a task planner agent. |\n",+ "| with_critic_in_the_loop | bool | Whether to include a critic in the loop. |\n",+ "| critic_criteria | str | Critic criteria for the critic agent. |\n",+ "| model | BaseModelBackend | The model backend to use for generating responses. |\n",+ "| task_type | TaskType | The type of task to perform. |\n",+ "| assistant_agent_kwargs | Dict | Additional arguments to pass to the assistant agent. |\n",+ "| user_agent_kwargs | Dict | Additional arguments to pass to the user agent. |\n",+ "| task_specify_agent_kwargs | Dict | Additional arguments to pass to the task specify agent. |\n",+ "| task_planner_agent_kwargs | Dict | Additional arguments to pass to the task planner agent. |\n",+ "| critic_kwargs | Dict | Additional arguments to pass to the critic. |\n",+ "| sys_msg_generator_kwargs | Dict | Additional arguments to pass to the system message generator. |\n",+ "| extend_sys_msg_meta_dicts | List[Dict] | A list of dicts to extend the system message meta dicts with. |\n",+ "| extend_task_specify_meta_dict | Dict | A dict to extend the task specify meta dict with. |\n",+ "| output_language | str | The language to be output by the agents. |"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "Z9Hv5B4v5MPS"+ },+ "source": [+ "### 2.2 `BabyAGI`"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "PnNiaAED5MPS"+ },+ "source": [+ "Babyagi is framework from \"[Task-driven Autonomous Agent](https://github.com/yoheinakajima/babyagi)\""+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "DeMiOr8H5MPS"+ },+ "source": [+ "## 3. Get Started"+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "### Installation"+ ],+ "metadata": {+ "id": "kETDiaP2Rrdb"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "Ensure you have CAMEL AI installed in your Python environment:"+ ],+ "metadata": {+ "id": "Cg96MkbcRtQR"+ }+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {+ "id": "ZVmDAK6MPefC"+ },+ "outputs": [],+ "source": [+ "!pip install \"camel-ai==0.2.4\""+ ]+ },+ {+ "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": "4873f5cd-f658-4102-f254-f3df2300156c"+ },+ "execution_count": 2,+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Enter your API key: ยทยทยทยทยทยทยทยทยทยท\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "XnmwXkps5MPS"+ },+ "source": [+ "### 3.1. Using `RolePlaying`"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 3,+ "metadata": {+ "vscode": {+ "languageId": "plaintext"+ },+ "id": "i6_PTBS65MPS"+ },+ "outputs": [],+ "source": [+ "from colorama import Fore\n",+ "\n",+ "from camel.societies import RolePlaying\n",+ "from camel.utils import print_text_animated"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 4,+ "metadata": {+ "vscode": {+ "languageId": "plaintext"+ },+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "Q7NPevJj5MPS",+ "outputId": "83c5549e-23b4-4a92-f8c4-94fbd34d11b3"+ },+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "\u001b[32mAI Assistant sys message:\n",+ "BaseMessage(role_name='Python Programmer', role_type=<RoleType.ASSISTANT: 'assistant'>, meta_dict={'task': 'Develop a Python-based trading bot that utilizes machine learning to analyze historical stock data, identify patterns, and execute buy/sell orders automatically. The bot should incorporate risk management strategies, backtesting capabilities, and real-time market data integration, focusing on tech stocks with a minimum trading volume of 1 million shares daily.', 'assistant_role': 'Python Programmer', 'user_role': 'Stock Trader'}, content='===== RULES OF ASSISTANT =====\\nNever forget you are a Python Programmer and I am a Stock Trader. 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: Develop a Python-based trading bot that utilizes machine learning to analyze historical stock data, identify patterns, and execute buy/sell orders automatically. The bot should incorporate risk management strategies, backtesting capabilities, and real-time market data integration, focusing on tech stocks with a minimum trading volume of 1 million shares daily.. 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",+ "BaseMessage(role_name='Stock Trader', role_type=<RoleType.USER: 'user'>, meta_dict={'task': 'Develop a Python-based trading bot that utilizes machine learning to analyze historical stock data, identify patterns, and execute buy/sell orders automatically. The bot should incorporate risk management strategies, backtesting capabilities, and real-time market data integration, focusing on tech stocks with a minimum trading volume of 1 million shares daily.', 'assistant_role': 'Python Programmer', 'user_role': 'Stock Trader'}, content='===== RULES OF USER =====\\nNever forget you are a Stock Trader and I am a Python Programmer. 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: Develop a Python-based trading bot that utilizes machine learning to analyze historical stock data, identify patterns, and execute buy/sell orders automatically. The bot should incorporate risk management strategies, backtesting capabilities, and real-time market data integration, focusing on tech stocks with a minimum trading volume of 1 million shares daily.. 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",+ "Develop a trading bot for the stock market\n",+ "\n",+ "\u001b[36mSpecified task prompt:\n",+ "Develop a Python-based trading bot that utilizes machine learning to analyze historical stock data, identify patterns, and execute buy/sell orders automatically. The bot should incorporate risk management strategies, backtesting capabilities, and real-time market data integration, focusing on tech stocks with a minimum trading volume of 1 million shares daily.\n",+ "\n",+ "\u001b[31mFinal task prompt:\n",+ "Develop a Python-based trading bot that utilizes machine learning to analyze historical stock data, identify patterns, and execute buy/sell orders automatically. The bot should incorporate risk management strategies, backtesting capabilities, and real-time market data integration, focusing on tech stocks with a minimum trading volume of 1 million shares daily.\n",+ "\n",+ "\u001b[34mAI User:\n",+ "\n",+ "Instruction: Set up a Python environment with the necessary libraries for data analysis and machine learning. \n",+ "Input: Use libraries such as pandas, NumPy, scikit-learn, and TensorFlow.\n",+ "\n",+ "\n",+ "\u001b[32mAI Assistant:\n",+ "\n",+ "Solution: To set up a Python environment with the necessary libraries for data analysis and machine learning, you can follow these steps:\n",+ "\n",+ "1. **Install Python**: Make sure you have Python installed on your system. You can download it from the official website [python.org](https://www.python.org/downloads/).\n",+ "\n",+ "2. **Create a Virtual Environment**: It's a good practice to create a virtual environment for your project to manage dependencies. You can do this using `venv` or `conda`. Hereโs how to do it with `venv`:\n",+ "\n",+ " ```bash\n",+ " python -m venv trading_bot_env\n",+ " ```\n",+ "\n",+ " Activate the virtual environment:\n",+ " - On Windows:\n",+ " ```bash\n",+ " trading_bot_env\\Scripts\\activate\n",+ " ```\n",+ " - On macOS/Linux:\n",+ " ```bash\n",+ " source trading_bot_env/bin/activate\n",+ " ```\n",+ "\n",+ "3. **Install Required Libraries**: Once the virtual environment is activated, you can install the necessary libraries using `pip`. Run the following command:\n",+ "\n",+ " ```bash\n",+ " pip install pandas numpy scikit-learn tensorflow\n",+ " ```\n",+ "\n",+ " - **pandas**: For data manipulation and analysis.\n",+ " - **NumPy**: For numerical computations.\n",+ " - **scikit-learn**: For machine learning algorithms and tools.\n",+ " - **TensorFlow**: For building and training machine learning models.\n",+ "\n",+ "4. **Verify Installation**: You can verify that the libraries have been installed correctly by running the following commands in a Python shell:\n",+ "\n",+ " ```python\n",+ " import pandas as pd\n",+ " import numpy as np\n",+ " import sklearn\n",+ " import tensorflow as tf\n",+ "\n",+ " print(\"Libraries imported successfully!\")\n",+ " ```\n",+ "\n",+ "5. **Jupyter Notebook (Optional)**: If you prefer working in a Jupyter Notebook, you can install it as well:\n",+ "\n",+ " ```bash\n",+ " pip install jupyter\n",+ " ```\n",+ "\n",+ " You can then start a Jupyter Notebook by running:\n",+ "\n",+ " ```bash\n",+ " jupyter notebook\n",+ " ```\n",+ "\n",+ "This setup will provide you with a solid foundation for developing your trading bot using machine learning techniques.\n",+ "\n",+ "Next request.\n",+ "\n",+ "\n",+ "\u001b[34mAI User:\n",+ "\n",+ "Instruction: Gather historical stock data for tech stocks with a minimum trading volume of 1 million shares daily. \n",+ "Input: Use a financial data API such as Alpha Vantage, Yahoo Finance, or Quandl.\n",+ "\n",+ "\n",+ "\u001b[32mAI Assistant:\n",+ "\n",+ "Solution: To gather historical stock data for tech stocks with a minimum trading volume of 1 million shares daily, you can use the Yahoo Finance API, which is accessible through the `yfinance` library. Hereโs how to do it step by step:\n",+ "\n",+ "1. **Install the yfinance Library**: If you haven't already installed the `yfinance` library, you can do so using pip:\n",+ "\n",+ " ```bash\n",+ " pip install yfinance\n",+ " ```\n",+ "\n",+ "2. **Import Necessary Libraries**: In your Python script or Jupyter Notebook, import the required libraries:\n",+ "\n",+ " ```python\n",+ " import yfinance as yf\n",+ " import pandas as pd\n",+ " ```\n",+ "\n",+ "3. **Define the Stock Symbols**: Create a list of tech stock symbols that you want to analyze. You can find a list of popular tech stocks, such as Apple (AAPL), Microsoft (MSFT), and Google (GOOGL). Hereโs an example list:\n",+ "\n",+ " ```python\n",+ " tech_stocks = ['AAPL', 'MSFT', 'GOOGL', 'AMZN', 'FB', 'TSLA']\n",+ " ```\n",+ "\n",+ "4. **Fetch Historical Data**: Use the `yfinance` library to fetch historical stock data. You can specify the period and interval. For example, to get daily data for the last year:\n",+ "\n",+ " ```python\n",+ " historical_data = {}\n",+ " for stock in tech_stocks:\n",+ " data = yf.download(stock, period='1y', interval='1d')\n",+ " # Filter for stocks with a minimum trading volume of 1 million shares\n",+ " data = data[data['Volume'] >= 1_000_000]\n",+ " historical_data[stock] = data\n",+ " ```\n",+ "\n",+ "5. **Store the Data**: You can store the historical data in a Pandas DataFrame or save it to a CSV file for further analysis:\n",+ "\n",+ " ```python\n",+ " for stock, data in historical_data.items():\n",+ " data.to_csv(f\"{stock}_historical_data.csv\")\n",+ " ```\n",+ "\n",+ "6. **Check the Data**: You can print the first few rows of the data for each stock to verify that you have gathered the correct information:\n",+ "\n",+ " ```python\n",+ " for stock, data in historical_data.items():\n",+ " print(f\"Data for {stock}:\")\n",+ " print(data.head())\n",+ " ```\n",+ "\n",+ "This process will allow you to gather historical stock data for tech stocks with a minimum trading volume of 1 million shares daily, which you can then use for analysis and machine learning in your trading bot.\n",+ "\n",+ "Next request.\n",+ "\n",+ "\n",+ "\u001b[34mAI User:\n",+ "\n",+ "Instruction: Implement a machine learning model to analyze the historical stock data and identify patterns for making buy/sell decisions. \n",+ "Input: Use a supervised learning approach with features such as moving averages, RSI, and historical prices.\n",+ "\n",+ "\n",+ "\u001b[32mAI Assistant:\n",+ "\n",+ "Solution: To implement a machine learning model that analyzes historical stock data and identifies patterns for making buy/sell decisions using a supervised learning approach, we can follow these steps:\n",+ "\n",+ "1. **Prepare the Data**: First, we need to create features from the historical stock data, such as moving averages, Relative Strength Index (RSI), and historical prices. We will also create labels for buy/sell decisions.\n",+ "\n",+ "2. **Calculate Features**:\n",+ " - **Moving Averages**: We can calculate short-term and long-term moving averages.\n",+ " - **RSI**: This is a momentum oscillator that measures the speed and change of price movements.\n",+ "\n",+ "3. **Split the Data**: We will split the data into training and testing sets.\n",+ "\n",+ "4. **Train a Machine Learning Model**: We can use a model like Random Forest or Support Vector Machine (SVM) for classification.\n",+ "\n",+ "5. **Evaluate the Model**: Finally, we will evaluate the model's performance.\n",+ "\n",+ "Here's how to implement these steps in Python:\n",+ "\n",+ "### Step 1: Prepare the Data\n",+ "\n",+ "```python\n",+ "import pandas as pd\n",+ "import numpy as np\n",+ "import yfinance as yf\n",+ "\n",+ "# Fetch historical data (as done previously)\n",+ "tech_stocks = ['AAPL', 'MSFT', 'GOOGL', 'AMZN', 'FB', 'TSLA']\n",+ "historical_data = {}\n",+ "for stock in tech_stocks:\n",+ " data = yf.download(stock, period='1y', interval='1d')\n",+ " data = data[data['Volume'] >= 1_000_000]\n",+ " historical_data[stock] = data\n",+ "\n",+ "# Example for one stock (AAPL)\n",+ "data = historical_data['AAPL'].copy()\n",+ "```\n",+ "\n",+ "### Step 2: Calculate Features\n",+ "\n",+ "```python\n",+ "# Calculate Moving Averages\n",+ "data['SMA_10'] = data['Close'].rolling(window=10).mean()\n",+ "data['SMA_50'] = data['Close'].rolling(window=50).mean()\n",+ "\n",+ "# Calculate RSI\n",+ "def calculate_rsi(data, window=14):\n",+ " delta = data['Close'].diff()\n",+ " gain = (delta.where(delta > 0, 0)).rolling(window=window).mean()\n",+ " loss = (-delta.where(delta < 0, 0)).rolling(window=window).mean()\n",+ " rs = gain / loss\n",+ " rsi = 100 - (100 / (1 + rs))\n",+ " return rsi\n",+ "\n",+ "data['RSI'] = calculate_rsi(data)\n",+ "\n",+ "# Create Labels: Buy = 1, Sell = 0\n",+ "data['Signal'] = 0\n",+ "data['Signal'][data['Close'].shift(-1) > data['Close']] = 1 # Buy signal\n",+ "data['Signal'][data['Close'].shift(-1) < data['Close']] = 0 # Sell signal\n",+ "data.dropna(inplace=True)\n",+ "```\n",+ "\n",+ "### Step 3: Split the Data\n",+ "\n",+ "```python\n",+ "from sklearn.model_selection import train_test_split\n",+ "\n",+ "# Features and Labels\n",+ "features = data[['SMA_10', 'SMA_50', 'RSI']]\n",+ "labels = data['Signal']\n",+ "\n",+ "# Split into training and testing sets\n",+ "X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=0.2, random_state=42)\n",+ "```\n",+ "\n",+ "### Step 4: Train a Machine Learning Model\n",+ "\n",+ "```python\n",+ "from sklearn.ensemble import RandomForestClassifier\n",+ "from sklearn.metrics import classification_report, accuracy_score\n",+ "\n",+ "# Initialize and train the model\n",+ "model = RandomForestClassifier(n_estimators=100, random_state=42)\n",+ "model.fit(X_train, y_train)\n",+ "\n",+ "# Make predictions\n",+ "y_pred = model.predict(X_test)\n",+ "```\n",+ "\n",+ "### Step 5: Evaluate the Model\n",+ "\n",+ "```python\n",+ "# Evaluate the model\n",+ "print(\"Accuracy:\", accuracy_score(y_test, y_pred))\n",+ "print(classification_report(y_test, y_pred))\n",+ "```\n",+ "\n",+ "This implementation provides a basic framework for analyzing historical stock data and making buy/sell decisions using a supervised learning approach. You can further enhance the model by tuning hyperparameters, adding more features, or using different algorithms.\n",+ "\n",+ "Next request.\n",+ "\n",+ "\n",+ "\u001b[34mAI User:\n",+ "\n",+ "Instruction: Incorporate risk management strategies into the trading bot, such as setting stop-loss and take-profit levels. \n",+ "Input: Define a percentage of the portfolio to risk on each trade and implement the logic in the trading strategy.\n",+ "\n",+ "\n",+ "\u001b[32mAI Assistant:\n",+ "\n",+ "Solution: To incorporate risk management strategies into the trading bot, we can define a percentage of the portfolio to risk on each trade and implement logic for setting stop-loss and take-profit levels. Hereโs how to do it step by step:\n",+ "\n",+ "### Step 1: Define Risk Parameters\n",+ "\n",+ "1. **Risk Percentage**: Decide on a percentage of the portfolio that you are willing to risk on each trade. For example, you might choose to risk 2% of your portfolio on each trade.\n",+ "2. **Stop-Loss and Take-Profit Levels**: Define how far away from the entry price the stop-loss and take-profit levels should be set. For instance, you might set a stop-loss at 1% below the entry price and a take-profit at 2% above the entry price.\n",+ "\n",+ "### Step 2: Implement the Logic\n",+ "\n",+ "You can implement the risk management logic in your trading strategy as follows:\n",+ "\n",+ "```python\n",+ "class TradingBot:\n",+ " def __init__(self, initial_capital, risk_percentage, stop_loss_pct, take_profit_pct):\n",+ " self.capital = initial_capital\n",+ " self.risk_percentage = risk_percentage\n",+ " self.stop_loss_pct = stop_loss_pct\n",+ " self.take_profit_pct = take_profit_pct\n",+ " self.position = None # Current position (None, 'long', or 'short')\n",+ "\n",+ " def calculate_position_size(self, entry_price):\n",+ " risk_amount = self.capital * self.risk_percentage\n",+ " stop_loss_price = entry_price * (1 - self.stop_loss_pct)\n",+ " position_size = risk_amount / (entry_price - stop_loss_price)\n",+ " return position_size\n",+ "\n",+ " def execute_trade(self, entry_price, signal):\n",+ " if signal == 1: # Buy signal\n",+ " position_size = self.calculate_position_size(entry_price)\n",+ " self.position = 'long'\n",+ " self.entry_price = entry_price\n",+ " self.stop_loss = entry_price * (1 - self.stop_loss_pct)\n",+ " self.take_profit = entry_price * (1 + self.take_profit_pct)\n",+ " print(f\"Buying {position_size} shares at {entry_price}. Stop-loss at {self.stop_loss}, Take-profit at {self.take_profit}.\")\n",+ " elif signal == 0 and self.position == 'long': # Sell signal\n",+ " self.close_position(entry_price)\n",+ "\n",+ " def close_position(self, exit_price):\n",+ " if self.position == 'long':\n",+ " profit = (exit_price - self.entry_price) * self.position_size\n",+ " self.capital += profit\n",+ " print(f\"Selling position at {exit_price}. Profit: {profit}. New capital: {self.capital}.\")\n",+ " self.position = None\n",+ "\n",+ " def check_stop_loss_take_profit(self, current_price):\n",+ " if self.position == 'long':\n",+ " if current_price <= self.stop_loss:\n",+ " print(f\"Stop-loss triggered at {current_price}.\")\n",+ " self.close_position(current_price)\n",+ " elif current_price >= self.take_profit:\n",+ " print(f\"Take-profit triggered at {current_price}.\")\n",+ " self.close_position(current_price)\n",+ "\n",+ "# Example usage\n",+ "initial_capital = 10000 # Initial capital in dollars\n",+ "risk_percentage = 0.02 # Risk 2% of the portfolio\n",+ "stop_loss_pct = 0.01 # Stop-loss at 1%\n",+ "take_profit_pct = 0.02 # Take-profit at 2%\n",+ "\n",+ "trading_bot = TradingBot(initial_capital, risk_percentage, stop_loss_pct, take_profit_pct)\n",+ "\n",+ "# Simulate a trade\n",+ "entry_price = 150 # Example entry price\n",+ "trading_bot.execute_trade(entry_price, signal=1) # Buy signal\n",+ "\n",+ "# Simulate price movements\n",+ "current_prices = [149, 152, 153, 148, 155] # Example price movements\n",+ "for price in current_prices:\n",+ " trading_bot.check_stop_loss_take_profit(price)\n",+ "```\n",+ "\n",+ "### Explanation:\n",+ "\n",+ "1. **TradingBot Class**: This class encapsulates the trading logic, including risk management strategies.\n",+ "2. **Risk Parameters**: The constructor initializes the capital, risk percentage, stop-loss, and take-profit levels.\n",+ "3. **Position Size Calculation**: The `calculate_position_size` method calculates how many shares to buy based on the risk percentage and stop-loss level.\n",+ "4. **Trade Execution**: The `execute_trade` method executes a trade based on the buy/sell signal and sets the stop-loss and take-profit levels.\n",+ "5. **Closing Position**: The `close_position` method closes the current position and updates the capital.\n",+ "6. **Stop-Loss and Take-Profit Check**: The `check_stop_loss_take_profit` method checks if the current price hits the stop-loss or take-profit levels.\n",+ "\n",+ "This implementation provides a basic framework for incorporating risk management strategies into your trading bot. You can further enhance it by adding more features or adjusting the parameters based on your trading strategy.\n",+ "\n",+ "Next request.\n",+ "\n",+ "\n",+ "\u001b[34mAI User:\n",+ "\n",+ "Instruction: Implement backtesting capabilities to evaluate the trading strategy's performance using historical data. \n",+ "Input: Create a function that simulates trades based on historical price data and calculates metrics such as total return, win rate, and maximum drawdown.\n",+ "\n",+ "\n",+ "\u001b[32mAI Assistant:\n",+ "\n",+ "Solution: To implement backtesting capabilities for evaluating the trading strategy's performance using historical data, we can create a function that simulates trades based on historical price data and calculates key performance metrics such as total return, win rate, and maximum drawdown. Here's how to do it step by step:\n",+ "\n",+ "### Step 1: Define the Backtesting Function\n",+ "\n",+ "1. **Simulate Trades**: The function will iterate through historical price data, execute trades based on the trading signals, and track the performance.\n",+ "2. **Calculate Metrics**: After simulating the trades, the function will calculate total return, win rate, and maximum drawdown.\n",+ "\n",+ "### Step 2: Implement the Backtesting Logic\n",+ "\n",+ "Hereโs a complete implementation of the backtesting function:\n",+ "\n",+ "```python\n",+ "class Backtester:\n",+ " def __init__(self, initial_capital, risk_percentage, stop_loss_pct, take_profit_pct):\n",+ " self.initial_capital = initial_capital\n",+ " self.capital = initial_capital\n",+ " self.risk_percentage = risk_percentage\n",+ " self.stop_loss_pct = stop_loss_pct\n",+ " self.take_profit_pct = take_profit_pct\n",+ " self.position = None\n",+ " self.entry_price = None\n",+ " self.trade_log = []\n",+ "\n",+ " def calculate_position_size(self, entry_price):\n",+ " risk_amount = self.capital * self.risk_percentage\n",+ " stop_loss_price = entry_price * (1 - self.stop_loss_pct)\n",+ " position_size = risk_amount / (entry_price - stop_loss_price)\n",+ " return position_size\n",+ "\n",+ " def execute_trade(self, entry_price, signal):\n",+ " if signal == 1: # Buy signal\n",+ " position_size = self.calculate_position_size(entry_price)\n",+ " self.position = 'long'\n",+ " self.entry_price = entry_price\n",+ " self.stop_loss = entry_price * (1 - self.stop_loss_pct)\n",+ " self.take_profit = entry_price * (1 + self.take_profit_pct)\n",+ " self.trade_log.append(('BUY', entry_price, position_size))\n",+ " elif signal == 0 and self.position == 'long': # Sell signal\n",+ " self.close_position(entry_price)\n",+ "\n",+ " def close_position(self, exit_price):\n",+ " if self.position == 'long':\n",+ " profit = (exit_price - self.entry_price) * self.position_size\n",+ " self.capital += profit\n",+ " self.trade_log.append(('SELL', exit_price, self.position_size))\n",+ " self.position = None\n",+ "\n",+ " def backtest(self, historical_data):\n",+ " for index, row in historical_data.iterrows():\n",+ " current_price = row['Close']\n",+ " signal = row['Signal']\n",+ " if self.position is None:\n",+ " self.execute_trade(current_price, signal)\n",+ " else:\n",+ " self.check_stop_loss_take_profit(current_price)\n",+ "\n",+ " # Finalize any open positions at the end of the data\n",+ " if self.position == 'long':\n",+ " self.close_position(historical_data.iloc[-1]['Close'])\n",+ "\n",+ " return self.calculate_metrics()\n",+ "\n",+ " def calculate_metrics(self):\n",+ " total_return = (self.capital - self.initial_capital) / self.initial_capital * 100\n",+ " win_count = sum(1 for trade in self.trade_log if trade[0] == 'SELL' and trade[1] > self.entry_price)\n",+ " total_trades = len(self.trade_log) // 2 # Each trade has a buy and sell\n",+ " win_rate = win_count / total_trades * 100 if total_trades > 0 else 0\n",+ "\n",+ " # Calculate maximum drawdown\n",+ " peak = self.initial_capital\n",+ " max_drawdown = 0\n",+ " for trade in self.trade_log:\n",+ " if trade[0] == 'SELL':\n",+ " peak = max(peak, self.capital)\n",+ " drawdown = (peak - self.capital) / peak * 100\n",+ " max_drawdown = max(max_drawdown, drawdown)\n",+ "\n",+ " return {\n",+ " 'Total Return (%)': total_return,\n",+ " 'Win Rate (%)': win_rate,\n",+ " 'Maximum Drawdown (%)': max_drawdown\n",+ " }\n",+ "\n",+ "# Example usage\n",+ "# Assuming `data` is a DataFrame containing historical price data with a 'Signal' column\n",+ "backtester = Backtester(initial_capital=10000, risk_percentage=0.02, stop_loss_pct=0.01, take_profit_pct=0.02)\n",+ "performance_metrics = backtester.backtest(data)\n",+ "\n",+ "print(\"Backtest Performance Metrics:\")\n",+ "print(performance_metrics)\n",+ "```\n",+ "\n",+ "### Explanation:\n",+ "\n",+ "1. **Backtester Class**: This class encapsulates the backtesting logic, including trade execution and performance metrics calculation.\n",+ "2. **Trade Execution**: The `execute_trade` method simulates buying and selling based on signals.\n",+ "3. **Backtesting Method**: The `backtest` method iterates through the historical data, executing trades based on the signals and checking for stop-loss and take-profit conditions.\n",+ "4. **Metrics Calculation**: The `calculate_metrics` method computes total return, win rate, and maximum drawdown based on the trade log.\n",+ "5. **Example Usage**: You can create an instance of the `Backtester` class and call the `backtest` method with your historical data to evaluate the trading strategy's performance.\n",+ "\n",+ "This implementation provides a framework for backtesting your trading strategy, allowing you to assess its effectiveness using historical data.\n",+ "\n",+ "Next request.\n",+ "\n",+ "\n",+ "\u001b[34mAI User:\n",+ "\n",+ "Instruction: Integrate real-time market data into the trading bot to enable live trading capabilities. \n",+ "Input: Use a real-time data provider API such as Alpaca, Interactive Brokers, or TD Ameritrade.\n",+ "\n",+ "\n",+ "\u001b[32mAI Assistant:\n",+ "\n",+ "Solution: To integrate real-time market data into the trading bot for enabling live trading capabilities, we can use the Alpaca API, which provides both market data and trading functionalities. Below are the steps to set up the integration:\n",+ "\n",+ "### Step 1: Set Up an Alpaca Account\n",+ "\n",+ "1. **Create an Account**: Sign up for an account at [Alpaca](https://alpaca.markets/).\n",+ "2. **Get API Keys**: After creating an account, navigate to the API section to obtain your API key and secret.\n",+ "\n",+ "### Step 2: Install the Alpaca Trade API\n",+ "\n",+ "You will need to install the `alpaca-trade-api` library to interact with the Alpaca API. You can do this using pip:\n",+ "\n",+ "```bash\n",+ "pip install alpaca-trade-api\n",+ "```\n",+ "\n",+ "### Step 3: Set Up the Trading Bot with Real-Time Data\n",+ "\n",+ "Hereโs how to implement the trading bot that integrates real-time market data using the Alpaca API:\n",+ "\n",+ "```python\n",+ "import alpaca_trade_api as tradeapi\n",+ "import time\n",+ "\n",+ "class LiveTradingBot:\n",+ " def __init__(self, api_key, api_secret, base_url, initial_capital, risk_percentage, stop_loss_pct, take_profit_pct):\n",+ " self.api = tradeapi.REST(api_key, api_secret, base_url, api_version='v2')\n",+ " self.capital = initial_capital\n",+ " self.risk_percentage = risk_percentage\n",+ " self.stop_loss_pct = stop_loss_pct\n",+ " self.take_profit_pct = take_profit_pct\n",+ " self.position = None\n",+ " self.entry_price = None\n",+ "\n",+ " def calculate_position_size(self, entry_price):\n",+ " risk_amount = self.capital * self.risk_percentage\n",+ " stop_loss_price = entry_price * (1 - self.stop_loss_pct)\n",+ " position_size = risk_amount / (entry_price - stop_loss_price)\n",+ " return position_size\n",+ "\n",+ " def execute_trade(self, symbol, signal):\n",+ " current_price = self.api.get_last_trade(symbol).price\n",+ " if signal == 1: # Buy signal\n",+ " position_size = self.calculate_position_size(current_price)\n",+ " self.api.submit_order(\n",+ " symbol=symbol,\n",+ " qty=position_size,\n",+ " side='buy',\n",+ " type='market',\n",+ " time_in_force='gtc'\n",+ " )\n",+ " self.position = 'long'\n",+ " self.entry_price = current_price\n",+ " self.stop_loss = current_price * (1 - self.stop_loss_pct)\n",+ " self.take_profit = current_price * (1 + self.take_profit_pct)\n",+ " print(f\"Buying {position_size} shares of {symbol} at {current_price}. Stop-loss at {self.stop_loss}, Take-profit at {self.take_profit}.\")\n",+ " elif signal == 0 and self.position == 'long': # Sell signal\n",+ " self.close_position(symbol)\n",+ "\n",+ " def close_position(self, symbol):\n",+ " if self.position == 'long':\n",+ " current_price = self.api.get_last_trade(symbol).price\n",+ " self.api.submit_order(\n",+ " symbol=symbol,\n",+ " qty=self.api.get_account().cash, # Sell all shares\n",+ " side='sell',\n",+ " type='market',\n",+ " time_in_force='gtc'\n",+ " )\n",+ " profit = (current_price - self.entry_price) * self.calculate_position_size(self.entry_price)\n",+ " self.capital += profit\n",+ " print(f\"Selling position of {symbol} at {current_price}. Profit: {profit}. New capital: {self.capital}.\")\n",+ " self.position = None\n",+ "\n",+ " def run(self, symbol):\n",+ " while True:\n",+ " # Here you would implement your trading logic to generate signals\n",+ " # For demonstration, we will use a dummy signal\n",+ " signal = self.generate_signal(symbol) # Replace with your signal generation logic\n",+ " self.execute_trade(symbol, signal)\n",+ " time.sleep(60) # Wait for a minute before checking again\n",+ "\n",+ " def generate_signal(self, symbol):\n",+ " # Dummy signal generation logic (replace with your actual logic)\n",+ " # For example, you could use moving averages or other indicators\n",+ " return 1 # Always buy for demonstration purposes\n",+ "\n",+ "# Example usage\n",+ "api_key = 'YOUR_API_KEY'\n",+ "api_secret = 'YOUR_API_SECRET'\n",+ "base_url = 'https://paper-api.alpaca.markets' # Use paper trading for testing\n",+ "\n",+ "live_trading_bot = LiveTradingBot(api_key, api_secret, base_url, initial_capital=10000, risk_percentage=0.02, stop_loss_pct=0.01, take_profit_pct=0.02)\n",+ "live_trading_bot.run('AAPL') # Replace 'AAPL' with the stock symbol you want to trade\n",+ "```\n",+ "\n",+ "### Explanation:\n",+ "\n",+ "1. **LiveTradingBot Class**: This class encapsulates the logic for live trading using the Alpaca API.\n",+ "2. **API Initialization**: The constructor initializes the Alpaca API with your credentials and sets up trading parameters.\n",+ "3. **Trade Execution**: The `execute_trade` method executes buy or sell orders based on the generated signals.\n",+ "4. **Close Position**: The `close_position` method sells all shares of the current position and updates the capital.\n",+ "5. **Run Method**: The `run` method continuously checks for trading signals and executes trades. You can replace the dummy signal generation logic with your actual trading strategy.\n",+ "6. **Example Usage**: Create an instance of the `LiveTradingBot` class and call the `run` method with the desired stock symbol.\n",+ "\n",+ "This implementation provides a framework for integrating real-time market data into your trading bot, enabling live trading capabilities.\n",+ "\n",+ "Next request.\n",+ "\n",+ "\n",+ "\u001b[34mAI User:\n",+ "\n",+ "Instruction: Implement logging functionality to track trades, performance metrics, and any errors during execution. \n",+ "Input: Use the `logging` module in Python to create a log file that records relevant information.\n",+ "\n",+ "\n",+ "\u001b[32mAI Assistant:\n",+ "\n",+ "Solution: To implement logging functionality in the trading bot to track trades, performance metrics, and any errors during execution, we can use Python's built-in `logging` module. This will allow us to create a log file that records relevant information. Below are the steps to set up logging in the trading bot:\n",+ "\n",+ "### Step 1: Set Up the Logging Configuration\n",+ "\n",+ "1. **Import the Logging Module**: Import the `logging` module at the beginning of your script.\n",+ "2. **Configure Logging**: Set up the logging configuration to specify the log file name, log level, and format.\n",+ "\n",+ "### Step 2: Integrate Logging into the Trading Bot\n",+ "\n",+ "Hereโs how to implement logging in the `LiveTradingBot` class:\n",+ "\n",+ "```python\n",+ "import alpaca_trade_api as tradeapi\n",+ "import logging\n",+ "import time\n",+ "\n",+ "# Set up logging configuration\n",+ "logging.basicConfig(\n",+ " filename='trading_bot.log',\n",+ " level=logging.INFO,\n",+ " format='%(asctime)s - %(levelname)s - %(message)s'\n",+ ")\n",+ "\n",+ "class LiveTradingBot:\n",+ " def __init__(self, api_key, api_secret, base_url, initial_capital, risk_percentage, stop_loss_pct, take_profit_pct):\n",+ " self.api = tradeapi.REST(api_key, api_secret, base_url, api_version='v2')\n",+ " self.capital = initial_capital\n",+ " self.risk_percentage = risk_percentage\n",+ " self.stop_loss_pct = stop_loss_pct\n",+ " self.take_profit_pct = take_profit_pct\n",+ " self.position = None\n",+ " self.entry_price = None\n",+ "\n",+ " def calculate_position_size(self, entry_price):\n",+ " risk_amount = self.capital * self.risk_percentage\n",+ " stop_loss_price = entry_price * (1 - self.stop_loss_pct)\n",+ " position_size = risk_amount / (entry_price - stop_loss_price)\n",+ " return position_size\n",+ "\n",+ " def execute_trade(self, symbol, signal):\n",+ " try:\n",+ " current_price = self.api.get_last_trade(symbol).price\n",+ " if signal == 1: # Buy signal\n",+ " position_size = self.calculate_position_size(current_price)\n",+ " self.api.submit_order(\n",+ " symbol=symbol,\n",+ " qty=position_size,\n",+ " side='buy',\n",+ " type='market',\n",+ " time_in_force='gtc'\n",+ " )\n",+ " self.position = 'long'\n",+ " self.entry_price = current_price\n",+ " self.stop_loss = current_price * (1 - self.stop_loss_pct)\n",+ " self.take_profit = current_price * (1 + self.take_profit_pct)\n",+ " logging.info(f\"Buying {position_size} shares of {symbol} at {current_price}. Stop-loss at {self.stop_loss}, Take-profit at {self.take_profit}.\")\n",+ " elif signal == 0 and self.position == 'long': # Sell signal\n",+ " self.close_position(symbol)\n",+ " except Exception as e:\n",+ " logging.error(f\"Error executing trade for {symbol}: {e}\")\n",+ "\n",+ " def close_position(self, symbol):\n",+ " try:\n",+ " if self.position == 'long':\n",+ " current_price = self.api.get_last_trade(symbol).price\n",+ " self.api.submit_order(\n",+ " symbol=symbol,\n",+ " qty=self.api.get_account().cash, # Sell all shares\n",+ " side='sell',\n",+ " type='market',\n",+ " time_in_force='gtc'\n",+ " )\n",+ " profit = (current_price - self.entry_price) * self.calculate_position_size(self.entry_price)\n",+ " self.capital += profit\n",+ " logging.info(f\"Selling position of {symbol} at {current_price}. Profit: {profit}. New capital: {self.capital}.\")\n",+ " self.position = None\n",+ " except Exception as e:\n",+ " logging.error(f\"Error closing position for {symbol}: {e}\")\n",+ "\n",+ " def run(self, symbol):\n",+ " while True:\n",+ " try:\n",+ " # Here you would implement your trading logic to generate signals\n",+ " signal = self.generate_signal(symbol) # Replace with your signal generation logic\n",+ " self.execute_trade(symbol, signal)\n",+ " time.sleep(60) # Wait for a minute before checking again\n",+ " except Exception as e:\n",+ " logging.error(f\"Error in run loop for {symbol}: {e}\")\n",+ "\n",+ " def generate_signal(self, symbol):\n",+ " # Dummy signal generation logic (replace with your actual logic)\n",+ " return 1 # Always buy for demonstration purposes\n",+ "\n",+ "# Example usage\n",+ "api_key = 'YOUR_API_KEY'\n",+ "api_secret = 'YOUR_API_SECRET'\n",+ "base_url = 'https://paper-api.alpaca.markets' # Use paper trading for testing\n",+ "\n",+ "live_trading_bot = LiveTradingBot(api_key, api_secret, base_url, initial_capital=10000, risk_percentage=0.02, stop_loss_pct=0.01, take_profit_pct=0.02)\n",+ "live_trading_bot.run('AAPL') # Replace 'AAPL' with the stock symbol you want to trade\n",+ "```\n",+ "\n",+ "### Explanation:\n",+ "\n",+ "1. **Logging Configuration**: The `logging.basicConfig` function sets up the logging configuration. It specifies the log file name (`trading_bot.log`), log level (`INFO`), and log message format.\n",+ "2. **Logging Trades**: In the `execute_trade` method, we log the details of each trade (buy/sell) using `logging.info()`.\n",+ "3. **Error Handling**: We wrap the trade execution and closing logic in `try-except` blocks to catch any exceptions. If an error occurs, we log the error message using `logging.error()`.\n",+ "4. **Run Loop**: The `run` method also includes error handling to log any issues that arise during the trading loop.\n",+ "\n",+ "This implementation provides a robust logging mechanism to track trades, performance metrics, and any errors during execution, which is essential for monitoring and debugging your trading bot.\n",+ "\n",+ "Next request.\n",+ "\n",+ "\n",+ "\u001b[34mAI User:\n",+ "\n",+ "Instruction: Create a user interface (UI) for the trading bot to allow users to configure settings, view performance metrics, and monitor trades. \n",+ "Input: Use a library such as Tkinter or PyQt for building the UI.\n",+ "\n",+ "\n",+ "\u001b[32mAI Assistant:\n",+ "\n",+ "Solution: To create a user interface (UI) for the trading bot that allows users to configure settings, view performance metrics, and monitor trades, we can use the Tkinter library, which is included with Python and is easy to use for building simple GUIs. Below is a step-by-step guide to implementing a basic UI for the trading bot.\n",+ "\n",+ "### Step 1: Install Tkinter\n",+ "\n",+ "Tkinter usually comes pre-installed with Python. However, if you are using a minimal installation, you may need to install it. You can check if Tkinter is available by running the following command in Python:\n",+ "\n",+ "```python\n",+ "import tkinter\n",+ "```\n",+ "\n",+ "If you don't encounter any errors, Tkinter is installed.\n",+ "\n",+ "### Step 2: Create the User Interface\n",+ "\n",+ "Hereโs how to implement a basic UI for the trading bot using Tkinter:\n",+ "\n",+ "```python\n",+ "import tkinter as tk\n",+ "from tkinter import messagebox\n",+ "import alpaca_trade_api as tradeapi\n",+ "import logging\n",+ "\n",+ "# Set up logging configuration\n",+ "logging.basicConfig(\n",+ " filename='trading_bot.log',\n",+ " level=logging.INFO,\n",+ " format='%(asctime)s - %(levelname)s - %(message)s'\n",+ ")\n",+ "\n",+ "class TradingBotUI:\n",+ " def __init__(self, master):\n",+ " self.master = master\n",+ " master.title(\"Trading Bot\")\n",+ "\n",+ " # API Key and Secret\n",+ " self.api_key_label = tk.Label(master, text=\"API Key:\")\n",+ " self.api_key_label.pack()\n",+ " self.api_key_entry = tk.Entry(master)\n",+ " self.api_key_entry.pack()\n",+ "\n",+ " self.api_secret_label = tk.Label(master, text=\"API Secret:\")\n",+ " self.api_secret_label.pack()\n",+ " self.api_secret_entry = tk.Entry(master)\n",+ " self.api_secret_entry.pack()\n",+ "\n",+ " self.base_url_label = tk.Label(master, text=\"Base URL:\")\n",+ " self.base_url_label.pack()\n",+ " self.base_url_entry = tk.Entry(master)\n",+ " self.base_url_entry.insert(0, 'https://paper-api.alpaca.markets')\n",+ " self.base_url_entry.pack()\n",+ "\n",+ " # Trading Parameters\n",+ " self.initial_capital_label = tk.Label(master, text=\"Initial Capital:\")\n",+ " self.initial_capital_label.pack()\n",+ " self.initial_capital_entry = tk.Entry(master)\n",+ " self.initial_capital_entry.insert(0, '10000')\n",+ " self.initial_capital_entry.pack()\n",+ "\n",+ " self.risk_percentage_label = tk.Label(master, text=\"Risk Percentage:\")\n",+ " self.risk_percentage_label.pack()\n",+ " self.risk_percentage_entry = tk.Entry(master)\n",+ " self.risk_percentage_entry.insert(0, '0.02')\n",+ " self.risk_percentage_entry.pack()\n",+ "\n",+ " self.stop_loss_pct_label = tk.Label(master, text=\"Stop Loss Percentage:\")\n",+ " self.stop_loss_pct_label.pack()\n",+ " self.stop_loss_pct_entry = tk.Entry(master)\n",+ " self.stop_loss_pct_entry.insert(0, '0.01')\n",+ " self.stop_loss_pct_entry.pack()\n",+ "\n",+ " self.take_profit_pct_label = tk.Label(master, text=\"Take Profit Percentage:\")\n",+ " self.take_profit_pct_label.pack()\n",+ " self.take_profit_pct_entry = tk.Entry(master)\n",+ " self.take_profit_pct_entry.insert(0, '0.02')\n",+ " self.take_profit_pct_entry.pack()\n",+ "\n",+ " # Start Trading Button\n",+ " self.start_button = tk.Button(master, text=\"Start Trading\", command=self.start_trading)\n",+ " self.start_button.pack()\n",+ "\n",+ " # Performance Metrics\n",+ " self.metrics_label = tk.Label(master, text=\"Performance Metrics:\")\n",+ " self.metrics_label.pack()\n",+ " self.metrics_text = tk.Text(master, height=10, width=50)\n",+ " self.metrics_text.pack()\n",+ "\n",+ " def start_trading(self):\n",+ " api_key = self.api_key_entry.get()\n",+ " api_secret = self.api_secret_entry.get()\n",+ " base_url = self.base_url_entry.get()\n",+ " initial_capital = float(self.initial_capital_entry.get())\n",+ " risk_percentage = float(self.risk_percentage_entry.get())\n",+ " stop_loss_pct = float(self.stop_loss_pct_entry.get())\n",+ " take_profit_pct = float(self.take_profit_pct_entry.get())\n",+ "\n",+ " # Initialize the trading bot\n",+ " self.trading_bot = LiveTradingBot(api_key, api_secret, base_url, initial_capital, risk_percentage, stop_loss_pct, take_profit_pct)\n",+ " self.metrics_text.insert(tk.END, \"Trading started...\\n\")\n",+ " self.metrics_text.insert(tk.END, f\"Initial Capital: {initial_capital}\\n\")\n",+ " # Start the trading loop in a separate thread to avoid freezing the UI\n",+ " self.master.after(1000, self.run_trading_loop)\n",+ "\n",+ " def run_trading_loop(self):\n",+ " # Here you would implement the logic to update performance metrics\n",+ " # For demonstration, we will just log a message\n",+ " self.metrics_text.insert(tk.END, \"Running trading loop...\\n\")\n",+ " self.master.after(1000, self.run_trading_loop) # Repeat every second\n",+ "\n",+ "class LiveTradingBot:\n",+ " def __init__(self, api_key, api_secret, base_url, initial_capital, risk_percentage, stop_loss_pct, take_profit_pct):\n",+ " self.api = tradeapi.REST(api_key, api_secret, base_url, api_version='v2')\n",+ " self.capital = initial_capital\n",+ " self.risk_percentage = risk_percentage\n",+ " self.stop_loss_pct = stop_loss_pct\n",+ " self.take_profit_pct = take_profit_pct\n",+ " self.position = None\n",+ " self.entry_price = None\n",+ "\n",+ " # Add methods for trading logic here...\n",+ "\n",+ "# Main application\n",+ "if __name__ == \"__main__\":\n",+ " root = tk.Tk()\n",+ " trading_bot_ui = TradingBotUI(root)\n",+ " root.mainloop()\n",+ "```\n",+ "\n",+ "### Explanation:\n",+ "\n",+ "1. **TradingBotUI Class**: This class creates the user interface using Tkinter. It includes fields for API keys, trading parameters, and a button to start trading.\n",+ "2. **Input Fields**: The UI has input fields for the API key, API secret, base URL, initial capital, risk percentage, stop-loss percentage, and take-profit percentage.\n",+ "3. **Start Trading Button**: When the user clicks the \"Start Trading\" button, it initializes the `LiveTradingBot` with the provided parameters and starts the trading loop.\n",+ "4. **Performance Metrics Display**: A text area is included to display performance metrics and logs.\n",+ "5. **LiveTradingBot Class**: This class is where the trading logic will be implemented. You can add methods for executing trades and managing positions.\n",+ "\n",+ "### Step 3: Run the Application\n",+ "\n",+ "You can run the above code in your Python environment. The UI will allow you to enter your trading parameters and start the trading bot. You can further enhance the UI by adding more features, such as displaying live trade updates, performance metrics, and error messages.\n",+ "\n",+ "This implementation provides a basic framework for a user interface for your trading bot, allowing users to configure settings and monitor trades.\n",+ "\n",+ "Next request.\n",+ "\n",+ "\n",+ "\u001b[34mAI User:\n",+ "\n",+ "Instruction: Enhance the user interface to include real-time updates of trades, performance metrics, and error messages during execution. \n",+ "Input: Implement a method to update the UI with live data from the trading bot and display it in the text area.\n",+ "\n",+ "\n",+ "\u001b[32mAI Assistant:\n",+ "\n",+ "Solution: To enhance the user interface (UI) to include real-time updates of trades, performance metrics, and error messages during execution, we can implement a method that updates the UI with live data from the trading bot and displays it in the text area. This involves modifying the `LiveTradingBot` class to send updates back to the UI and updating the UI accordingly.\n",+ "\n",+ "### Step 1: Modify the LiveTradingBot Class\n",+ "\n",+ "We will add a method to the `LiveTradingBot` class to allow it to send updates back to the UI. This can be done by passing a reference to the UI's text area when initializing the trading bot.\n",+ "\n",+ "### Step 2: Implement Real-Time Updates\n",+ "\n",+ "Hereโs how to implement the real-time updates in the UI:\n",+ "\n",+ "```python\n",+ "import tkinter as tk\n",+ "from tkinter import messagebox\n",+ "import alpaca_trade_api as tradeapi\n",+ "import logging\n",+ "import time\n",+ "\n",+ "# Set up logging configuration\n",+ "logging.basicConfig(\n",+ " filename='trading_bot.log',\n",+ " level=logging.INFO,\n",+ " format='%(asctime)s - %(levelname)s - %(message)s'\n",+ ")\n",+ "\n",+ "class TradingBotUI:\n",+ " def __init__(self, master):\n",+ " self.master = master\n",+ " master.title(\"Trading Bot\")\n",+ "\n",+ " # API Key and Secret\n",+ " self.api_key_label = tk.Label(master, text=\"API Key:\")\n",+ " self.api_key_label.pack()\n",+ " self.api_key_entry = tk.Entry(master)\n",+ " self.api_key_entry.pack()\n",+ "\n",+ " self.api_secret_label = tk.Label(master, text=\"API Secret:\")\n",+ " self.api_secret_label.pack()\n",+ " self.api_secret_entry = tk.Entry(master)\n",+ " self.api_secret_entry.pack()\n",+ "\n",+ " self.base_url_label = tk.Label(master, text=\"Base URL:\")\n",+ " self.base_url_label.pack()\n",+ " self.base_url_entry = tk.Entry(master)\n",+ " self.base_url_entry.insert(0, 'https://paper-api.alpaca.markets')\n",+ " self.base_url_entry.pack()\n",+ "\n",+ " # Trading Parameters\n",+ " self.initial_capital_label = tk.Label(master, text=\"Initial Capital:\")\n",+ " self.initial_capital_label.pack()\n",+ " self.initial_capital_entry = tk.Entry(master)\n",+ " self.initial_capital_entry.insert(0, '10000')\n",+ " self.initial_capital_entry.pack()\n",+ "\n",+ " self.risk_percentage_label = tk.Label(master, text=\"Risk Percentage:\")\n",+ " self.risk_percentage_label.pack()\n",+ " self.risk_percentage_entry = tk.Entry(master)\n",+ " self.risk_percentage_entry.insert(0, '0.02')\n",+ " self.risk_percentage_entry.pack()\n",+ "\n",+ " self.stop_loss_pct_label = tk.Label(master, text=\"Stop Loss Percentage:\")\n",+ " self.stop_loss_pct_label.pack()\n",+ " self.stop_loss_pct_entry = tk.Entry(master)\n",+ " self.stop_loss_pct_entry.insert(0, '0.01')\n",+ " self.stop_loss_pct_entry.pack()\n",+ "\n",+ " self.take_profit_pct_label = tk.Label(master, text=\"Take Profit Percentage:\")\n",+ " self.take_profit_pct_label.pack()\n",+ " self.take_profit_pct_entry = tk.Entry(master)\n",+ " self.take_profit_pct_entry.insert(0, '0.02')\n",+ " self.take_profit_pct_entry.pack()\n",+ "\n",+ " # Start Trading Button\n",+ " self.start_button = tk.Button(master, text=\"Start Trading\", command=self.start_trading)\n",+ " self.start_button.pack()\n",+ "\n",+ " # Performance Metrics\n",+ " self.metrics_label = tk.Label(master, text=\"Performance Metrics:\")\n",+ " self.metrics_label.pack()\n",+ " self.metrics_text = tk.Text(master, height=10, width=50)\n",+ " self.metrics_text.pack()\n",+ "\n",+ " def start_trading(self):\n",+ " api_key = self.api_key_entry.get()\n",+ " api_secret = self.api_secret_entry.get()\n",+ " base_url = self.base_url_entry.get()\n",+ " initial_capital = float(self.initial_capital_entry.get())\n",+ " risk_percentage = float(self.risk_percentage_entry.get())\n",+ " stop_loss_pct = float(self.stop_loss_pct_entry.get())\n",+ " take_profit_pct = float(self.take_profit_pct_entry.get())\n",+ "\n",+ " # Initialize the trading bot\n",+ " self.trading_bot = LiveTradingBot(api_key, api_secret, base_url, initial_capital, risk_percentage, stop_loss_pct, take_profit_pct, self.metrics_text)\n",+ " self.metrics_text.insert(tk.END, \"Trading started...\\n\")\n",+ " self.metrics_text.insert(tk.END, f\"Initial Capital: {initial_capital}\\n\")\n",+ " # Start the trading loop in a separate thread to avoid freezing the UI\n",+ " self.master.after(1000, self.run_trading_loop)\n",+ "\n",+ " def run_trading_loop(self):\n",+ " # Update the UI with live data\n",+ " if hasattr(self, 'trading_bot'):\n",+ " self.trading_bot.update_metrics()\n",+ " self.master.after(1000, self.run_trading_loop) # Repeat every second\n",+ "\n",+ "class LiveTradingBot:\n",+ " def __init__(self, api_key, api_secret, base_url, initial_capital, risk_percentage, stop_loss_pct, take_profit_pct, metrics_text):\n",+ " self.api = tradeapi.REST(api_key, api_secret, base_url, api_version='v2')\n",+ " self.capital = initial_capital\n",+ " self.risk_percentage = risk_percentage\n",+ " self.stop_loss_pct = stop_loss_pct\n",+ " self.take_profit_pct = take_profit_pct\n",+ " self.position = None\n",+ " self.entry_price = None\n",+ " self.metrics_text = metrics_text\n",+ "\n",+ " def calculate_position_size(self, entry_price):\n",+ " risk_amount = self.capital * self.risk_percentage\n",+ " stop_loss_price = entry_price * (1 - self.stop_loss_pct)\n",+ " position_size = risk_amount / (entry_price - stop_loss_price)\n",+ " return position_size\n",+ "\n",+ " def execute_trade(self, symbol, signal):\n",+ " try:\n",+ " current_price = self.api.get_last_trade(symbol).price\n",+ " if signal == 1: # Buy signal\n",+ " position_size = self.calculate_position_size(current_price)\n",+ " self.api.submit_order(\n",+ " symbol=symbol,\n",+ " qty=position_size,\n",+ " side='buy',\n",+ " type='market',\n",+ " time_in_force='gtc'\n",+ " )\n",+ " self.position = 'long'\n",+ " self.entry_price = current_price\n",+ " self.stop_loss = current_price * (1 - self.stop_loss_pct)\n",+ " self.take_profit = current_price * (1 + self.take_profit_pct)\n",+ " logging.info(f\"Buying {position_size} shares of {symbol} at {current_price}. Stop-loss at {self.stop_loss}, Take-profit at {self.take_profit}.\")\n",+ " self.metrics_text.insert(tk.END, f\"Bought {position_size} shares of {symbol} at {current_price}\\n\")\n",+ " elif signal == 0 and self.position == 'long': # Sell signal\n",+ " self.close_position(symbol)\n",+ " except Exception as e:\n",+ " logging.error(f\"Error executing trade for {symbol}: {e}\")\n",+ " self.metrics_text.insert(tk.END, f\"Error executing trade for {symbol}: {e}\\n\")\n",+ "\n",+ " def close_position(self, symbol):\n",+ " try:\n",+ " if self.position == 'long':\n",+ " current_price = self.api.get_last_trade(symbol).price\n",+ " self.api.submit_order(\n",+ " symbol=symbol,\n",+ " qty=self.api.get_account().cash, # Sell all shares\n",+ " side='sell',\n",+ " type='market',\n",+ " time_in_force='gtc'\n",+ " )\n",+ " profit = (current_price - self.entry_price) * self.calculate_position_size(self.entry_price)\n",+ " self.capital += profit\n",+ " logging.info(f\"Selling position of {symbol} at {current_price}. Profit: {profit}. New capital: {self.capital}.\")\n",+ " self.metrics_text.insert(tk.END, f\"Sold position of {symbol} at {current_price}. Profit: {profit}\\n\")\n",+ " self.position = None\n",+ " except Exception as e:\n",+ " logging.error(f\"Error closing position for {symbol}: {e}\")\n",+ " self.metrics_text.insert(tk.END, f\"Error closing position for {symbol}: {e}\\n\")\n",+ "\n",+ " def update_metrics(self):\n",+ " # Update performance metrics in the UI\n",+ " self.metrics_text.insert(tk.END, f\"Current Capital: {self.capital}\\n\")\n",+ " # You can add more metrics here as needed\n",+ "\n",+ " def run(self, symbol):\n",+ " while True:\n",+ " # Here you would implement your trading logic to generate signals\n",+ " signal = self.generate_signal(symbol) # Replace with your signal generation logic\n",+ " self.execute_trade(symbol, signal)\n",+ " time.sleep(60) # Wait for a minute before checking again\n",+ "\n",+ " def generate_signal(self, symbol):\n",+ " # Dummy signal generation logic (replace with your actual logic)\n",+ " return 1 # Always buy for demonstration purposes\n",+ "\n",+ "# Main application\n",+ "if __name__ == \"__main__\":\n",+ " root = tk.Tk()\n",+ " trading_bot_ui = TradingBotUI(root)\n",+ " root.mainloop()\n",+ "```\n",+ "\n",+ "### Explanation:\n",+ "\n",+ "1. **Metrics Text Area**: The `metrics_text` area in the `TradingBotUI` class is used to display real-time updates of trades and performance metrics.\n",+ "2. **LiveTradingBot Initialization**: The `LiveTradingBot` class is initialized with a reference to the `metrics_text` area, allowing it to update the UI with trade information and errors.\n",+ "3. **Trade Execution Updates**: In the `execute_trade` and `close_position` methods, we log trade actions and errors to both the log file and the UI.\n",+ "4. **Update Metrics Method**: The `update_metrics` method in the `LiveTradingBot` class updates the UI with the current capital and can be extended to include more performance metrics.\n",+ "5. **Run Trading Loop**: The `run_trading_loop` method in the `TradingBotUI` class periodically calls the `update_metrics` method to refresh the displayed data.\n",+ "\n",+ "This implementation enhances the user interface by providing real-time updates of trades, performance metrics, and error messages during execution, making it more interactive and informative for users.\n",+ "\n",+ "Next request.\n",+ "\n",+ "\n",+ "\u001b[34mAI User:\n",+ "\n",+ "Instruction: Implement a feature to allow users to stop the trading bot gracefully from the UI. \n",+ "Input: Add a \"Stop Trading\" button that halts the trading loop and any ongoing trades.\n",+ "\n",+ "\n",+ "\u001b[32mAI Assistant:\n",+ "\n",+ "Solution: To implement a feature that allows users to stop the trading bot gracefully from the UI, we can add a \"Stop Trading\" button. This button will halt the trading loop and any ongoing trades. We will modify the `LiveTradingBot` class to include a method for stopping the trading process and update the UI accordingly.\n",+ "\n",+ "### Step 1: Add a Stop Trading Button\n",+ "\n",+ "We will add a button in the `TradingBotUI` class that will call a method to stop the trading bot when clicked.\n",+ "\n",+ "### Step 2: Implement the Stop Functionality\n",+ "\n",+ "Hereโs how to implement the stop trading feature:\n",+ "\n",+ "```python\n",+ "import tkinter as tk\n",+ "from tkinter import messagebox\n",+ "import alpaca_trade_api as tradeapi\n",+ "import logging\n",+ "import time\n",+ "import threading\n",+ "\n",+ "# Set up logging configuration\n",+ "logging.basicConfig(\n",+ " filename='trading_bot.log',\n",+ " level=logging.INFO,\n",+ " format='%(asctime)s - %(levelname)s - %(message)s'\n",+ ")\n",+ "\n",+ "class TradingBotUI:\n",+ " def __init__(self, master):\n",+ " self.master = master\n",+ " master.title(\"Trading Bot\")\n",+ "\n",+ " # API Key and Secret\n",+ " self.api_key_label = tk.Label(master, text=\"API Key:\")\n",+ " self.api_key_label.pack()\n",+ " self.api_key_entry = tk.Entry(master)\n",+ " self.api_key_entry.pack()\n",+ "\n",+ " self.api_secret_label = tk.Label(master, text=\"API Secret:\")\n",+ " self.api_secret_label.pack()\n",+ " self.api_secret_entry = tk.Entry(master)\n",+ " self.api_secret_entry.pack()\n",+ "\n",+ " self.base_url_label = tk.Label(master, text=\"Base URL:\")\n",+ " self.base_url_label.pack()\n",+ " self.base_url_entry = tk.Entry(master)\n",+ " self.base_url_entry.insert(0, 'https://paper-api.alpaca.markets')\n",+ " self.base_url_entry.pack()\n",+ "\n",+ " # Trading Parameters\n",+ " self.initial_capital_label = tk.Label(master, text=\"Initial Capital:\")\n",+ " self.initial_capital_label.pack()\n",+ " self.initial_capital_entry = tk.Entry(master)\n",+ " self.initial_capital_entry.insert(0, '10000')\n",+ " self.initial_capital_entry.pack()\n",+ "\n",+ " self.risk_percentage_label = tk.Label(master, text=\"Risk Percentage:\")\n",+ " self.risk_percentage_label.pack()\n",+ " self.risk_percentage_entry = tk.Entry(master)\n",+ " self.risk_percentage_entry.insert(0, '0.02')\n",+ " self.risk_percentage_entry.pack()\n",+ "\n",+ " self.stop_loss_pct_label = tk.Label(master, text=\"Stop Loss Percentage:\")\n",+ " self.stop_loss_pct_label.pack()\n",+ " self.stop_loss_pct_entry = tk.Entry(master)\n",+ " self.stop_loss_pct_entry.insert(0, '0.01')\n",+ " self.stop_loss_pct_entry.pack()\n",+ "\n",+ " self.take_profit_pct_label = tk.Label(master, text=\"Take Profit Percentage:\")\n",+ " self.take_profit_pct_label.pack()\n",+ " self.take_profit_pct_entry = tk.Entry(master)\n",+ " self.take_profit_pct_entry.insert(0, '0.02')\n",+ " self.take_profit_pct_entry.pack()\n",+ "\n",+ " # Start Trading Button\n",+ " self.start_button = tk.Button(master, text=\"Start Trading\", command=self.start_trading)\n",+ " self.start_button.pack()\n",+ "\n",+ " # Stop Trading Button\n",+ " self.stop_button = tk.Button(master, text=\"Stop Trading\", command=self.stop_trading, state=tk.DISABLED)\n",+ " self.stop_button.pack()\n",+ "\n",+ " # Performance Metrics\n",+ " self.metrics_label = tk.Label(master, text=\"Performance Metrics:\")\n",+ " self.metrics_label.pack()\n",+ " self.metrics_text = tk.Text(master, height=10, width=50)\n",+ " self.metrics_text.pack()\n",+ "\n",+ " def start_trading(self):\n",+ " api_key = self.api_key_entry.get()\n",+ " api_secret = self.api_secret_entry.get()\n",+ " base_url = self.base_url_entry.get()\n",+ " initial_capital = float(self.initial_capital_entry.get())\n",+ " risk_percentage = float(self.risk_percentage_entry.get())\n",+ " stop_loss_pct = float(self.stop_loss_pct_entry.get())\n",+ " take_profit_pct = float(self.take_profit_pct_entry.get())\n",+ "\n",+ " # Initialize the trading bot\n",+ " self.trading_bot = LiveTradingBot(api_key, api_secret, base_url, initial_capital, risk_percentage, stop_loss_pct, take_profit_pct, self.metrics_text)\n",+ " self.metrics_text.insert(tk.END, \"Trading started...\\n\")\n",+ " self.metrics_text.insert(tk.END, f\"Initial Capital: {initial_capital}\\n\")\n",+ " self.start_button.config(state=tk.DISABLED)\n",+ " self.stop_button.config(state=tk.NORMAL)\n",+ "\n",+ " # Start the trading loop in a separate thread to avoid freezing the UI\n",+ " self.trading_thread = threading.Thread(target=self.trading_bot.run, args=('AAPL',)) # Replace 'AAPL' with the desired stock symbol\n",+ " self.trading_thread.start()\n",+ "\n",+ " def stop_trading(self):\n",+ " if hasattr(self, 'trading_bot'):\n",+ " self.trading_bot.stop() # Call the stop method in the trading bot\n",+ " self.metrics_text.insert(tk.END, \"Trading stopped.\\n\")\n",+ " self.start_button.config(state=tk.NORMAL)\n",+ " self.stop_button.config(state=tk.DISABLED)\n",+ "\n",+ "class LiveTradingBot:\n",+ " def __init__(self, api_key, api_secret, base_url, initial_capital, risk_percentage, stop_loss_pct, take_profit_pct, metrics_text):\n",+ " self.api = tradeapi.REST(api_key, api_secret, base_url, api_version='v2')\n",+ " self.capital = initial_capital\n",+ " self.risk_percentage = risk_percentage\n",+ " self.stop_loss_pct = stop_loss_pct\n",+ " self.take_profit_pct = take_profit_pct\n",+ " self.position = None\n",+ " self.entry_price = None\n",+ " self.metrics_text = metrics_text\n",+ " self.running = True # Flag to control the trading loop\n",+ "\n",+ " def calculate_position_size(self, entry_price):\n",+ " risk_amount = self.capital * self.risk_percentage\n",+ " stop_loss_price = entry_price * (1 - self.stop_loss_pct)\n",+ " position_size = risk_amount / (entry_price - stop_loss_price)\n",+ " return position_size\n",+ "\n",+ " def execute_trade(self, symbol, signal):\n",+ " try:\n",+ " current_price = self.api.get_last_trade(symbol).price\n",+ " if signal == 1: # Buy signal\n",+ " position_size = self.calculate_position_size(current_price)\n",+ " self.api.submit_order(\n",+ " symbol=symbol,\n",+ " qty=position_size,\n",+ " side='buy',\n",+ " type='market',\n",+ " time_in_force='gtc'\n",+ " )\n",+ " self.position = 'long'\n",+ " self.entry_price = current_price\n",+ " self.stop_loss = current_price * (1 - self.stop_loss_pct)\n",+ " self.take_profit = current_price * (1 + self.take_profit_pct)\n",+ " logging.info(f\"Buying {position_size} shares of {symbol} at {current_price}. Stop-loss at {self.stop_loss}, Take-profit at {self.take_profit}.\")\n",+ " self.metrics_text.insert(tk.END, f\"Bought {position_size} shares of {symbol} at {current_price}\\n\")\n",+ " elif signal == 0 and self.position == 'long': # Sell signal\n",+ " self.close_position(symbol)\n",+ " except Exception as e:\n",+ " logging.error(f\"Error executing trade for {symbol}: {e}\")\n",+ " self.metrics_text.insert(tk.END, f\"Error executing trade for {symbol}: {e}\\n\")\n",+ "\n",+ " def close_position(self, symbol):\n",+ " try:\n",+ " if self.position == 'long':\n",+ " current_price = self.api.get_last_trade(symbol).price\n",+ " self.api.submit_order(\n",+ " symbol=symbol,\n",+ " qty=self.api.get_account().cash, # Sell all shares\n",+ " side='sell',\n",+ " type='market',\n",+ " time_in_force='gtc'\n",+ " )\n",+ " profit = (current_price - self.entry_price) * self.calculate_position_size(self.entry_price)\n",+ " self.capital += profit\n",+ " logging.info(f\"Selling position of {symbol} at {current_price}. Profit: {profit}. New capital: {self.capital}.\")\n",+ " self.metrics_text.insert(tk.END, f\"Sold position of {symbol} at {current_price}. Profit: {profit}\\n\")\n",+ " self.position = None\n",+ " except Exception as e:\n",+ " logging.error(f\"Error closing position for {symbol}: {e}\")\n",+ " self.metrics_text.insert(tk.END, f\"Error closing position for {symbol}: {e}\\n\")\n",+ "\n",+ " def update_metrics(self):\n",+ " # Update performance metrics in the UI\n",+ " self.metrics_text.insert(tk.END, f\"Current Capital: {self.capital}\\n\")\n",+ " # You can add more metrics here as needed\n",+ "\n",+ " def run(self, symbol):\n",+ " while self.running:\n",+ " # Here you would implement your trading logic to generate signals\n",+ " signal = self.generate_signal(symbol) # Replace with your signal generation logic\n",+ " self.execute_trade(symbol, signal)\n",+ " time.sleep(60) # Wait for a minute before checking again\n",+ "\n",+ " def generate_signal(self, symbol):\n",+ " # Dummy signal generation logic (replace with your actual logic)\n",+ " return 1 # Always buy for demonstration purposes\n",+ "\n",+ " def stop(self):\n",+ " self.running = False # Set the running flag to False to stop the trading loop\n",+ "\n",+ "# Main application\n",+ "if __name__ == \"__main__\":\n",+ " root = tk.Tk()\n",+ " trading_bot_ui = TradingBotUI(root)\n",+ " root.mainloop()\n",+ "```\n",+ "\n",+ "### Explanation:\n",+ "\n",+ "1. **Stop Trading Button**: A \"Stop Trading\" button is added to the UI, which calls the `stop_trading` method when clicked. Initially, this button is disabled until trading starts.\n",+ "2. **Stop Method in LiveTradingBot**: The `stop` method sets a flag (`self.running`) to `False`, which will stop the trading loop in the `run` method.\n",+ "3. **Threading**: The trading loop runs in a separate thread to avoid freezing the UI. When the user clicks the \"Stop Trading\" button, the trading loop will stop gracefully.\n",+ "4. **UI Updates**: The UI is updated to reflect that trading has stopped, and the buttons are enabled/disabled appropriately.\n",+ "\n",+ "This implementation allows users to stop the trading bot gracefully from the UI, ensuring that ongoing trades are halted and the trading loop is exited cleanly.\n",+ "\n",+ "Next request.\n",+ "\n",+ "\n"+ ]+ }+ ],+ "source": [+ "def main(model=None, chat_turn_limit=10) -> None:\n",+ "# Initial the role-playing session on developing a trading bot task with default model (`GPT_4O_MINI`)\n",+ " task_prompt = \"Develop a trading bot for the stock market\"\n",+ " role_play_session = RolePlaying(\n",+ " assistant_role_name=\"Python Programmer\",\n",+ " assistant_agent_kwargs=dict(model=model),\n",+ " user_role_name=\"Stock Trader\",\n",+ " user_agent_kwargs=dict(model=model),\n",+ " task_prompt=task_prompt,\n",+ " with_task_specify=True,\n",+ " task_specify_agent_kwargs=dict(model=model),\n",+ " )\n",+ "\n",+ "# Output initial message with different colors.\n",+ " print(\n",+ " Fore.GREEN\n",+ " + f\"AI Assistant sys message:\\n{role_play_session.assistant_sys_msg}\\n\"\n",+ " )\n",+ " print(\n",+ " Fore.BLUE + f\"AI User sys message:\\n{role_play_session.user_sys_msg}\\n\"\n",+ " )\n",+ "\n",+ " print(Fore.YELLOW + f\"Original task prompt:\\n{task_prompt}\\n\")\n",+ " print(\n",+ " Fore.CYAN\n",+ " + \"Specified task prompt:\"\n",+ " + f\"\\n{role_play_session.specified_task_prompt}\\n\"\n",+ " )\n",+ " print(Fore.RED + f\"Final task prompt:\\n{role_play_session.task_prompt}\\n\")\n",+ "\n",+ " n = 0\n",+ " input_msg = role_play_session.init_chat()\n",+ "\n",+ "# Output response step by step with different colors.\n",+ "# Keep output until detect the terminate content or reach the loop limit.\n",+ " while n < chat_turn_limit:\n",+ " n += 1\n",+ " assistant_response, user_response = role_play_session.step(input_msg)\n",+ "\n",+ " if assistant_response.terminated:\n",+ " print(\n",+ " Fore.GREEN\n",+ " + (\n",+ " \"AI Assistant terminated. Reason: \"\n",+ " f\"{assistant_response.info['termination_reasons']}.\"\n",+ " )\n",+ " )\n",+ " break\n",+ " if user_response.terminated:\n",+ " print(\n",+ " Fore.GREEN\n",+ " + (\n",+ " \"AI User terminated. \"\n",+ " f\"Reason: {user_response.info['termination_reasons']}.\"\n",+ " )\n",+ " )\n",+ " break\n",+ "\n",+ " print_text_animated(\n",+ " Fore.BLUE + f\"AI User:\\n\\n{user_response.msg.content}\\n\"\n",+ " )\n",+ "\n",+ " if \"CAMEL_TASK_DONE\" in user_response.msg.content:\n",+ " break\n",+ "\n",+ " print_text_animated(\n",+ " Fore.GREEN + \"AI Assistant:\\n\\n\"\n",+ " f\"{assistant_response.msg.content}\\n\"\n",+ " )\n",+ "\n",+ "\n",+ "\n",+ " input_msg = assistant_response.msg\n",+ "\n",+ "if __name__ == \"__main__\":\n",+ " main()"+ ]}- },- "outputs": [],- "source": [- "from colorama import Fore\n",- "\n",- "from camel.societies import RolePlaying\n",- "from camel.utils import print_text_animated"- ]- },- {- "cell_type": "code",- "execution_count": 7,- "metadata": {+ ],+ "metadata": {+ "language_info": {+ "name": "python"+ },"colab": {- "base_uri": "https://localhost:8080/"+ "provenance": []},- "id": "Q7NPevJj5MPS",- "outputId": "4b6ba2d7-305e-4c78-fc64-cd5b35ed050d",- "vscode": {- "languageId": "plaintext"- }- },- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "\u001b[32mAI Assistant sys message:\n",- "BaseMessage(role_name='Python Programmer', role_type=<RoleType.ASSISTANT: 'assistant'>, meta_dict={'task': 'Develop a Python-based trading bot that utilizes machine learning algorithms to analyze historical stock data, identify patterns, and execute buy/sell orders automatically. The bot should incorporate risk management strategies, real-time market data integration, and a user-friendly dashboard for monitoring performance and adjusting trading parameters based on user-defined criteria.', 'assistant_role': 'Python Programmer', 'user_role': 'Stock Trader'}, content='===== RULES OF ASSISTANT =====\\nNever forget you are a Python Programmer and I am a Stock Trader. 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: Develop a Python-based trading bot that utilizes machine learning algorithms to analyze historical stock data, identify patterns, and execute buy/sell orders automatically. The bot should incorporate risk management strategies, real-time market data integration, and a user-friendly dashboard for monitoring performance and adjusting trading parameters based on user-defined criteria.. 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",- "BaseMessage(role_name='Stock Trader', role_type=<RoleType.USER: 'user'>, meta_dict={'task': 'Develop a Python-based trading bot that utilizes machine learning algorithms to analyze historical stock data, identify patterns, and execute buy/sell orders automatically. The bot should incorporate risk management strategies, real-time market data integration, and a user-friendly dashboard for monitoring performance and adjusting trading parameters based on user-defined criteria.', 'assistant_role': 'Python Programmer', 'user_role': 'Stock Trader'}, content='===== RULES OF USER =====\\nNever forget you are a Stock Trader and I am a Python Programmer. 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: Develop a Python-based trading bot that utilizes machine learning algorithms to analyze historical stock data, identify patterns, and execute buy/sell orders automatically. The bot should incorporate risk management strategies, real-time market data integration, and a user-friendly dashboard for monitoring performance and adjusting trading parameters based on user-defined criteria.. 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",- "Develop a trading bot for the stock market\n",- "\n",- "\u001b[36mSpecified task prompt:\n",- "Develop a Python-based trading bot that utilizes machine learning algorithms to analyze historical stock data, identify patterns, and execute buy/sell orders automatically. The bot should incorporate risk management strategies, real-time market data integration, and a user-friendly dashboard for monitoring performance and adjusting trading parameters based on user-defined criteria.\n",- "\n",- "\u001b[31mFinal task prompt:\n",- "Develop a Python-based trading bot that utilizes machine learning algorithms to analyze historical stock data, identify patterns, and execute buy/sell orders automatically. The bot should incorporate risk management strategies, real-time market data integration, and a user-friendly dashboard for monitoring performance and adjusting trading parameters based on user-defined criteria.\n",- "\n",- "\u001b[34mAI User:\n",- "\n",- "Instruction: Set up a Python environment with the necessary libraries for data analysis and machine learning. \n",- "Input: Use libraries such as pandas, numpy, scikit-learn, and matplotlib.\n",- "\n",- "\n",- "\u001b[32mAI Assistant:\n",- "\n",- "Solution: To set up a Python environment for data analysis and machine learning, you will need to install the necessary libraries: `pandas`, `numpy`, `scikit-learn`, and `matplotlib`. Hereโs how you can do it step by step:\n",- "\n",- "1. **Install Python**: If you haven't already, download and install Python from the official website (https://www.python.org/downloads/). It's recommended to install the latest version of Python 3.\n",- "\n",- "2. **Set Up a Virtual Environment** (optional but recommended): This helps to manage dependencies for different projects separately. You can use `venv` or `conda` for this purpose.\n",- "\n",- " Using `venv`:\n",- " ```bash\n",- " python -m venv trading_bot_env\n",- " source trading_bot_env/bin/activate # On Windows use `trading_bot_env\\Scripts\\activate`\n",- " ```\n",- "\n",- " Using `conda`:\n",- " ```bash\n",- " conda create --name trading_bot_env python=3.9\n",- " conda activate trading_bot_env\n",- " ```\n",- "\n",- "3. **Install Required Libraries**: Once your virtual environment is activated, you can install the necessary libraries using `pip`. Run the following command in your terminal or command prompt:\n",- "\n",- " ```bash\n",- " pip install pandas numpy scikit-learn matplotlib\n",- " ```\n",- "\n",- "4. **Verify Installation**: You can verify that the libraries are installed correctly by running the following commands in a Python shell or script:\n",- "\n",- " ```python\n",- " import pandas as pd\n",- " import numpy as np\n",- " from sklearn import datasets\n",- " import matplotlib.pyplot as plt\n",- "\n",- " print(\"Libraries imported successfully!\")\n",- " ```\n",- "\n",- "5. **Create a Jupyter Notebook** (optional): For an interactive environment, you might want to install Jupyter Notebook. You can do this by running:\n",- "\n",- " ```bash\n",- " pip install notebook\n",- " ```\n",- "\n",- " Then you can start Jupyter Notebook by running:\n",- " ```bash\n",- " jupyter notebook\n",- " ```\n",- "\n",- "This setup will provide you with a robust environment for data analysis and machine learning, allowing you to analyze historical stock data and build your trading bot.\n",- "\n",- "Next request.\n",- "\n",- "\n",- "\u001b[34mAI User:\n",- "\n",- "Instruction: Gather historical stock data for analysis, preferably using an API like Alpha Vantage or Yahoo Finance. \n",- "Input: Use the `yfinance` library to download historical data for a specific stock (e.g., AAPL).\n",- "\n",- "\n",- "\u001b[32mAI Assistant:\n",- "\n",- "Solution: To gather historical stock data using the `yfinance` library, you can follow these steps. The `yfinance` library allows you to easily download historical market data from Yahoo Finance.\n",- "\n",- "1. **Install the `yfinance` Library**: If you haven't installed `yfinance` yet, you can do so using pip. Make sure your virtual environment is activated, then run:\n",- "\n",- " ```bash\n",- " pip install yfinance\n",- " ```\n",- "\n",- "2. **Download Historical Data**: You can use the following Python code to download historical stock data for a specific stock, such as Apple Inc. (AAPL). Hereโs a simple example:\n",- "\n",- " ```python\n",- " import yfinance as yf\n",- " import pandas as pd\n",- "\n",- " # Define the stock symbol and the time period\n",- " stock_symbol = 'AAPL'\n",- " start_date = '2020-01-01'\n",- " end_date = '2023-01-01'\n",- "\n",- " # Download historical data\n",- " stock_data = yf.download(stock_symbol, start=start_date, end=end_date)\n",- "\n",- " # Display the first few rows of the data\n",- " print(stock_data.head())\n",- " ```\n",- "\n",- "3. **Understanding the Code**:\n",- " - `import yfinance as yf`: This imports the `yfinance` library.\n",- " - `yf.download()`: This function downloads historical market data for the specified stock symbol between the defined start and end dates.\n",- " - `stock_data.head()`: This displays the first few rows of the downloaded data, which includes columns like Open, High, Low, Close, Volume, and Adjusted Close.\n",- "\n",- "4. **DataFrame Structure**: The downloaded data will be in a Pandas DataFrame format, which allows for easy manipulation and analysis. You can perform various operations like filtering, aggregating, and visualizing the data.\n",- "\n",- "5. **Saving the Data** (optional): If you want to save the downloaded data for future use, you can easily export it to a CSV file:\n",- "\n",- " ```python\n",- " stock_data.to_csv('AAPL_historical_data.csv')\n",- " ```\n",- "\n",- "This code will help you gather the historical stock data you need for analysis, which is essential for building your trading bot.\n",- "\n",- "Next request.\n",- "\n",- "\n",- "\u001b[34mAI User:\n",- "\n",- "Instruction: Implement a basic machine learning model to analyze the historical stock data and predict future prices. \n",- "Input: Use a linear regression model from the `scikit-learn` library.\n",- "\n",- "\n",- "\u001b[32mAI Assistant:\n",- "\n",- "Solution: To implement a basic machine learning model using linear regression from the `scikit-learn` library to analyze historical stock data and predict future prices, you can follow these steps:\n",- "\n",- "1. **Prepare the Data**: You need to preprocess the historical stock data to create features and labels for the model. In this case, we will use the previous day's closing price to predict the next day's closing price.\n",- "\n",- "2. **Implement Linear Regression**: We will use the `LinearRegression` class from `scikit-learn` to create and train the model.\n",- "\n",- "Hereโs a complete example:\n",- "\n",- "```python\n",- "import yfinance as yf\n",- "import pandas as pd\n",- "from sklearn.model_selection import train_test_split\n",- "from sklearn.linear_model import LinearRegression\n",- "from sklearn.metrics import mean_squared_error\n",- "import numpy as np\n",- "\n",- "# Step 1: Download historical data for AAPL\n",- "stock_symbol = 'AAPL'\n",- "start_date = '2020-01-01'\n",- "end_date = '2023-01-01'\n",- "stock_data = yf.download(stock_symbol, start=start_date, end=end_date)\n",- "\n",- "# Step 2: Prepare the data\n",- "# Create a new DataFrame with the 'Close' prices\n",- "data = stock_data[['Close']].copy()\n",- "data['Prediction'] = data['Close'].shift(-1) # Shift the closing prices to create labels\n",- "\n",- "# Drop the last row as it will have NaN value for 'Prediction'\n",- "data.dropna(inplace=True)\n",- "\n",- "# Define features (X) and labels (y)\n",- "X = data[['Close']].values # Features: previous day's closing price\n",- "y = data['Prediction'].values # Labels: next day's closing price\n",- "\n",- "# Step 3: Split the data into training and testing sets\n",- "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",- "\n",- "# Step 4: Create and train the linear regression model\n",- "model = LinearRegression()\n",- "model.fit(X_train, y_train)\n",- "\n",- "# Step 5: Make predictions\n",- "predictions = model.predict(X_test)\n",- "\n",- "# Step 6: Evaluate the model\n",- "mse = mean_squared_error(y_test, predictions)\n",- "print(f'Mean Squared Error: {mse}')\n",- "\n",- "# Optional: Compare actual vs predicted prices\n",- "predicted_prices = pd.DataFrame({'Actual': y_test, 'Predicted': predictions})\n",- "print(predicted_prices.head())\n",- "```\n",- "\n",- "### Explanation of the Code:\n",- "1. **Data Download**: We download historical stock data for AAPL using `yfinance`.\n",- "2. **Data Preparation**:\n",- " - We create a new DataFrame that includes the closing prices and a new column for the next day's closing price (shifted by one).\n",- " - We drop the last row since it will have a NaN value for the prediction.\n",- "3. **Feature and Label Definition**: We define our features (previous day's closing price) and labels (next day's closing price).\n",- "4. **Data Splitting**: We split the data into training and testing sets using an 80-20 split.\n",- "5. **Model Creation and Training**: We create a linear regression model and fit it to the training data.\n",- "6. **Prediction and Evaluation**: We make predictions on the test set and evaluate the model using Mean Squared Error (MSE). We also print a comparison of actual vs. predicted prices.\n",- "\n",- "This basic implementation provides a foundation for predicting future stock prices using linear regression. You can further enhance the model by adding more features, tuning hyperparameters, or using more advanced algorithms.\n",- "\n",- "Next request.\n",- "\n",- "\n",- "\u001b[34mAI User:\n",- "\n",- "Instruction: Incorporate risk management strategies into the trading bot, such as setting stop-loss and take-profit levels. \n",- "Input: Define a function that calculates stop-loss and take-profit prices based on a given percentage.\n",- "\n",- "\n",- "\u001b[32mAI Assistant:\n",- "\n",- "Solution: To incorporate risk management strategies into the trading bot, we can define a function that calculates stop-loss and take-profit prices based on a given percentage. This function will take the entry price and the desired percentages for stop-loss and take-profit as inputs and return the corresponding prices.\n",- "\n",- "Hereโs how you can implement this function:\n",- "\n",- "```python\n",- "def calculate_risk_management(entry_price, stop_loss_percentage, take_profit_percentage):\n",- " \"\"\"\n",- " Calculate stop-loss and take-profit prices based on entry price and given percentages.\n",- "\n",- " Parameters:\n",- " entry_price (float): The price at which the stock is bought.\n",- " stop_loss_percentage (float): The percentage for stop-loss (e.g., 0.02 for 2%).\n",- " take_profit_percentage (float): The percentage for take-profit (e.g., 0.05 for 5%).\n",- "\n",- " Returns:\n",- " tuple: A tuple containing (stop_loss_price, take_profit_price).\n",- " \"\"\"\n",- " # Calculate stop-loss price\n",- " stop_loss_price = entry_price * (1 - stop_loss_percentage)\n",- " \n",- " # Calculate take-profit price\n",- " take_profit_price = entry_price * (1 + take_profit_percentage)\n",- " \n",- " return stop_loss_price, take_profit_price\n",- "\n",- "# Example usage\n",- "entry_price = 150.00 # Example entry price for AAPL\n",- "stop_loss_percentage = 0.02 # 2% stop-loss\n",- "take_profit_percentage = 0.05 # 5% take-profit\n",- "\n",- "stop_loss, take_profit = calculate_risk_management(entry_price, stop_loss_percentage, take_profit_percentage)\n",- "\n",- "print(f\"Entry Price: ${entry_price:.2f}\")\n",- "print(f\"Stop-Loss Price: ${stop_loss:.2f}\")\n",- "print(f\"Take-Profit Price: ${take_profit:.2f}\")\n",- "```\n",- "\n",- "### Explanation of the Code:\n",- "1. **Function Definition**: The function `calculate_risk_management` takes three parameters:\n",- " - `entry_price`: The price at which the stock is purchased.\n",- " - `stop_loss_percentage`: The percentage decrease from the entry price at which to sell the stock to prevent further losses.\n",- " - `take_profit_percentage`: The percentage increase from the entry price at which to sell the stock to secure profits.\n",- "\n",- "2. **Stop-Loss Calculation**: The stop-loss price is calculated by multiplying the entry price by `(1 - stop_loss_percentage)`. This gives the price below which the stock should be sold to limit losses.\n",- "\n",- "3. **Take-Profit Calculation**: The take-profit price is calculated by multiplying the entry price by `(1 + take_profit_percentage)`. This gives the price above which the stock should be sold to secure profits.\n",- "\n",- "4. **Return Values**: The function returns a tuple containing the stop-loss and take-profit prices.\n",- "\n",- "5. **Example Usage**: An example is provided to demonstrate how to use the function, including printing the calculated stop-loss and take-profit prices.\n",- "\n",- "Incorporating this function into your trading bot will help manage risk effectively by setting predefined exit points based on market movements.\n",- "\n",- "Next request.\n",- "\n",- "\n",- "\u001b[34mAI User:\n",- "\n",- "Instruction: Integrate real-time market data into the trading bot to make decisions based on current stock prices. \n",- "Input: Use the `yfinance` library to fetch real-time stock prices.\n",- "\n",- "\n",- "\u001b[32mAI Assistant:\n",- "\n",- "Solution: To integrate real-time market data into the trading bot using the `yfinance` library, you can fetch the current stock prices and use them to make trading decisions. The `yfinance` library provides a convenient way to access real-time data.\n",- "\n",- "Hereโs how you can implement this functionality:\n",- "\n",- "1. **Fetch Real-Time Stock Prices**: You can use the `yf.Ticker` class to get real-time data for a specific stock.\n",- "\n",- "2. **Make Trading Decisions**: Based on the real-time price, you can implement logic to decide whether to buy, sell, or hold the stock.\n",- "\n",- "Hereโs a complete example:\n",- "\n",- "```python\n",- "import yfinance as yf\n",- "import time\n",- "\n",- "def get_real_time_price(stock_symbol):\n",- " \"\"\"\n",- " Fetch the real-time price of a stock using yfinance.\n",- "\n",- " Parameters:\n",- " stock_symbol (str): The stock symbol (e.g., 'AAPL').\n",- "\n",- " Returns:\n",- " float: The current price of the stock.\n",- " \"\"\"\n",- " ticker = yf.Ticker(stock_symbol)\n",- " current_price = ticker.history(period='1m')['Close'].iloc[-1] # Get the last closing price\n",- " return current_price\n",- "\n",- "def trading_decision(current_price, stop_loss_price, take_profit_price):\n",- " \"\"\"\n",- " Make a trading decision based on the current price, stop-loss, and take-profit levels.\n",- "\n",- " Parameters:\n",- " current_price (float): The current price of the stock.\n",- " stop_loss_price (float): The stop-loss price.\n",- " take_profit_price (float): The take-profit price.\n",- "\n",- " Returns:\n",- " str: The trading action ('buy', 'sell', 'hold').\n",- " \"\"\"\n",- " if current_price <= stop_loss_price:\n",- " return 'sell' # Trigger stop-loss\n",- " elif current_price >= take_profit_price:\n",- " return 'sell' # Trigger take-profit\n",- " else:\n",- " return 'hold' # No action\n",- "\n",- "# Example usage\n",- "stock_symbol = 'AAPL'\n",- "entry_price = 150.00 # Example entry price for AAPL\n",- "stop_loss_percentage = 0.02 # 2% stop-loss\n",- "take_profit_percentage = 0.05 # 5% take-profit\n",- "\n",- "# Calculate stop-loss and take-profit prices\n",- "stop_loss, take_profit = calculate_risk_management(entry_price, stop_loss_percentage, take_profit_percentage)\n",- "\n",- "# Monitor real-time prices\n",- "while True:\n",- " current_price = get_real_time_price(stock_symbol)\n",- " print(f\"Current Price: ${current_price:.2f}\")\n",- "\n",- " action = trading_decision(current_price, stop_loss, take_profit)\n",- " print(f\"Trading Action: {action}\")\n",- "\n",- " time.sleep(10) # Wait for 10 seconds before fetching the price again\n",- "```\n",- "\n",- "### Explanation of the Code:\n",- "1. **Function `get_real_time_price`**: This function fetches the current price of the specified stock using the `yfinance` library. It retrieves the last closing price from the last minute of trading data.\n",- "\n",- "2. **Function `trading_decision`**: This function takes the current price, stop-loss price, and take-profit price as inputs and returns a trading action:\n",- " - If the current price is less than or equal to the stop-loss price, it returns 'sell'.\n",- " - If the current price is greater than or equal to the take-profit price, it also returns 'sell'.\n",- " - Otherwise, it returns 'hold'.\n",- "\n",- "3. **Example Usage**:\n",- " - The stock symbol for Apple Inc. (AAPL) is defined.\n",- " - The entry price, stop-loss percentage, and take-profit percentage are set.\n",- " - The stop-loss and take-profit prices are calculated using the previously defined function.\n",- " - A loop is created to continuously monitor the real-time price of the stock every 10 seconds and make trading decisions based on the current price.\n",- "\n",- "This implementation allows your trading bot to react to real-time market conditions, making it more responsive and effective in executing trades based on predefined risk management strategies.\n",- "\n",- "Next request.\n",- "\n",- "\n",- "\u001b[34mAI User:\n",- "\n",- "Instruction: Create a user-friendly dashboard to monitor the trading bot's performance and adjust trading parameters. \n",- "Input: Use the `Dash` library to build the dashboard interface.\n",- "\n",- "\n",- "\u001b[32mAI Assistant:\n",- "\n",- "Solution: To create a user-friendly dashboard for monitoring the trading bot's performance and adjusting trading parameters, we can use the `Dash` library by Plotly. Dash allows you to build interactive web applications in Python easily.\n",- "\n",- "Hereโs how to set up a basic dashboard:\n",- "\n",- "1. **Install the Dash Library**: If you haven't installed Dash yet, you can do so using pip. Make sure your virtual environment is activated, then run:\n",- "\n",- " ```bash\n",- " pip install dash\n",- " ```\n",- "\n",- "2. **Create the Dashboard**: Below is an example of how to create a simple dashboard that displays the current stock price, stop-loss, take-profit levels, and allows users to adjust these parameters.\n",- "\n",- "```python\n",- "import dash\n",- "from dash import dcc, html, Input, Output\n",- "import yfinance as yf\n",- "\n",- "# Initialize the Dash app\n",- "app = dash.Dash(__name__)\n",- "\n",- "# Define the layout of the dashboard\n",- "app.layout = html.Div([\n",- " html.H1(\"Trading Bot Dashboard\"),\n",- " \n",- " html.Div([\n",- " html.Label(\"Stock Symbol:\"),\n",- " dcc.Input(id='stock-symbol', value='AAPL', type='text'),\n",- " \n",- " html.Label(\"Entry Price:\"),\n",- " dcc.Input(id='entry-price', value='150.00', type='number'),\n",- " \n",- " html.Label(\"Stop-Loss Percentage (%):\"),\n",- " dcc.Input(id='stop-loss-percentage', value='2', type='number'),\n",- " \n",- " html.Label(\"Take-Profit Percentage (%):\"),\n",- " dcc.Input(id='take-profit-percentage', value='5', type='number'),\n",- " \n",- " html.Button('Update', id='update-button', n_clicks=0)\n",- " ]),\n",- " \n",- " html.Div(id='output-container', style={'margin-top': '20px'}),\n",- " \n",- " dcc.Interval(\n",- " id='interval-component',\n",- " interval=10*1000, # Update every 10 seconds\n",- " n_intervals=0\n",- " )\n",- "])\n",- "\n",- "@app.callback(\n",- " Output('output-container', 'children'),\n",- " Input('update-button', 'n_clicks'),\n",- " Input('stock-symbol', 'value'),\n",- " Input('entry-price', 'value'),\n",- " Input('stop-loss-percentage', 'value'),\n",- " Input('take-profit-percentage', 'value'),\n",- " Input('interval-component', 'n_intervals')\n",- ")\n",- "def update_dashboard(n_clicks, stock_symbol, entry_price, stop_loss_percentage, take_profit_percentage, n_intervals):\n",- " # Fetch the current price\n",- " current_price = get_real_time_price(stock_symbol)\n",- " \n",- " # Calculate stop-loss and take-profit prices\n",- " stop_loss, take_profit = calculate_risk_management(float(entry_price), float(stop_loss_percentage) / 100, float(take_profit_percentage) / 100)\n",- " \n",- " return [\n",- " html.Div(f\"Current Price: ${current_price:.2f}\"),\n",- " html.Div(f\"Stop-Loss Price: ${stop_loss:.2f}\"),\n",- " html.Div(f\"Take-Profit Price: ${take_profit:.2f}\"),\n",- " ]\n",- "\n",- "def get_real_time_price(stock_symbol):\n",- " ticker = yf.Ticker(stock_symbol)\n",- " current_price = ticker.history(period='1m')['Close'].iloc[-1]\n",- " return current_price\n",- "\n",- "# Run the app\n",- "if __name__ == '__main__':\n",- " app.run_server(debug=True)\n",- "```\n",- "\n",- "### Explanation of the Code:\n",- "1. **Dash App Initialization**: We initialize a Dash app using `dash.Dash(__name__)`.\n",- "\n",- "2. **Layout Definition**: The layout of the dashboard is defined using HTML components:\n",- " - Input fields for the stock symbol, entry price, stop-loss percentage, and take-profit percentage.\n",- " - A button to update the parameters.\n",- " - A div to display the output (current price, stop-loss, and take-profit prices).\n",- " - An interval component to refresh the data every 10 seconds.\n",- "\n",- "3. **Callback Function**: The `update_dashboard` function is decorated with `@app.callback` to update the dashboard based on user input and the interval:\n",- " - It fetches the current stock price using the `get_real_time_price` function.\n",- " - It calculates the stop-loss and take-profit prices using the `calculate_risk_management` function.\n",- " - It returns the updated values to be displayed in the dashboard.\n",- "\n",- "4. **Real-Time Price Fetching**: The `get_real_time_price` function fetches the current price of the specified stock using `yfinance`.\n",- "\n",- "5. **Running the App**: The app is run with `app.run_server(debug=True)`, which starts the Dash server.\n",- "\n",- "This dashboard provides a simple interface for users to monitor the trading bot's performance and adjust trading parameters dynamically. You can further enhance the dashboard by adding more features, such as performance metrics, historical data visualizations, and trading logs.\n",- "\n",- "Next request.\n",- "\n",- "\n",- "\u001b[34mAI User:\n",- "\n",- "Instruction: Implement a logging mechanism to track the trading bot's actions and performance over time. \n",- "Input: Use the `logging` library to create a log file that records trades, decisions, and errors.\n",- "\n",- "\n",- "\u001b[32mAI Assistant:\n",- "\n",- "Solution: To implement a logging mechanism that tracks the trading bot's actions and performance over time, we can use Python's built-in `logging` library. This will allow us to create a log file that records trades, decisions, and any errors that may occur during the bot's operation.\n",- "\n",- "Hereโs how to set up the logging mechanism:\n",- "\n",- "1. **Import the Logging Library**: We will import the `logging` library and configure it to write logs to a file.\n",- "\n",- "2. **Create Logging Functions**: We will create functions to log different types of messages, such as trades, decisions, and errors.\n",- "\n",- "3. **Integrate Logging into the Trading Logic**: We will add logging calls in the trading decision-making process.\n",- "\n",- "Hereโs a complete example:\n",- "\n",- "```python\n",- "import logging\n",- "import yfinance as yf\n",- "import time\n",- "\n",- "# Configure logging\n",- "logging.basicConfig(\n",- " filename='trading_bot.log',\n",- " level=logging.INFO,\n",- " format='%(asctime)s - %(levelname)s - %(message)s'\n",- ")\n",- "\n",- "def get_real_time_price(stock_symbol):\n",- " try:\n",- " ticker = yf.Ticker(stock_symbol)\n",- " current_price = ticker.history(period='1m')['Close'].iloc[-1] # Get the last closing price\n",- " logging.info(f\"Fetched current price for {stock_symbol}: ${current_price:.2f}\")\n",- " return current_price\n",- " except Exception as e:\n",- " logging.error(f\"Error fetching price for {stock_symbol}: {e}\")\n",- " return None\n",- "\n",- "def trading_decision(current_price, stop_loss_price, take_profit_price):\n",- " if current_price <= stop_loss_price:\n",- " logging.info(f\"Current price ${current_price:.2f} hit stop-loss at ${stop_loss_price:.2f}. Action: sell.\")\n",- " return 'sell' # Trigger stop-loss\n",- " elif current_price >= take_profit_price:\n",- " logging.info(f\"Current price ${current_price:.2f} hit take-profit at ${take_profit_price:.2f}. Action: sell.\")\n",- " return 'sell' # Trigger take-profit\n",- " else:\n",- " logging.info(f\"Current price ${current_price:.2f} is within range. Action: hold.\")\n",- " return 'hold' # No action\n",- "\n",- "# Example usage\n",- "stock_symbol = 'AAPL'\n",- "entry_price = 150.00 # Example entry price for AAPL\n",- "stop_loss_percentage = 0.02 # 2% stop-loss\n",- "take_profit_percentage = 0.05 # 5% take-profit\n",- "\n",- "# Calculate stop-loss and take-profit prices\n",- "stop_loss, take_profit = calculate_risk_management(entry_price, stop_loss_percentage, take_profit_percentage)\n",- "\n",- "# Monitor real-time prices\n",- "while True:\n",- " current_price = get_real_time_price(stock_symbol)\n",- " if current_price is not None:\n",- " action = trading_decision(current_price, stop_loss, take_profit)\n",- " logging.info(f\"Trading action decided: {action}\")\n",- "\n",- " time.sleep(10) # Wait for 10 seconds before fetching the price again\n",- "```\n",- "\n",- "### Explanation of the Code:\n",- "1. **Logging Configuration**: The `logging.basicConfig` function is used to configure the logging settings:\n",- " - `filename='trading_bot.log'`: Specifies the log file name.\n",- " - `level=logging.INFO`: Sets the logging level to INFO, meaning it will capture all messages at this level and above (INFO, WARNING, ERROR, CRITICAL).\n",- " - `format='%(asctime)s - %(levelname)s - %(message)s'`: Defines the format of the log messages, including the timestamp, log level, and message.\n",- "\n",- "2. **Error Handling in `get_real_time_price`**: The function fetches the current price and logs the result. If an error occurs, it logs the error message.\n",- "\n",- "3. **Logging Trading Decisions**: The `trading_decision` function logs the action taken based on the current price, whether it hits the stop-loss, take-profit, or holds.\n",- "\n",- "4. **Main Loop**: The main loop continuously fetches the current price and makes trading decisions, logging each action.\n",- "\n",- "This logging mechanism will help you track the trading bot's actions and performance over time, making it easier to analyze its behavior and troubleshoot any issues that arise.\n",- "\n",- "Next request.\n",- "\n",- "\n",- "\u001b[34mAI User:\n",- "\n",- "Instruction: Test the trading bot with a simulated trading environment to evaluate its performance before deploying it in a live market. \n",- "Input: Use a backtesting framework like `Backtrader` to simulate trades based on historical data.\n",- "\n",- "\n",- "\u001b[32mAI Assistant:\n",- "\n",- "Solution: To test the trading bot with a simulated trading environment and evaluate its performance before deploying it in a live market, we can use the `Backtrader` framework. Backtrader is a powerful backtesting library that allows you to simulate trading strategies using historical data.\n",- "\n",- "Hereโs how to set up a basic backtesting environment using Backtrader:\n",- "\n",- "1. **Install Backtrader**: If you haven't installed Backtrader yet, you can do so using pip. Make sure your virtual environment is activated, then run:\n",- "\n",- " ```bash\n",- " pip install backtrader\n",- " ```\n",- "\n",- "2. **Create a Backtesting Strategy**: We will define a simple trading strategy that uses the stop-loss and take-profit logic we discussed earlier.\n",- "\n",- "3. **Run the Backtest**: We will load historical data and run the backtest to evaluate the strategy's performance.\n",- "\n",- "Hereโs a complete example:\n",- "\n",- "```python\n",- "import backtrader as bt\n",- "import yfinance as yf\n",- "\n",- "# Define the trading strategy\n",- "class MyStrategy(bt.Strategy):\n",- " params = (\n",- " ('stop_loss_pct', 0.02), # 2% stop-loss\n",- " ('take_profit_pct', 0.05), # 5% take-profit\n",- " )\n",- "\n",- " def __init__(self):\n",- " self.order = None\n",- " self.entry_price = None\n",- "\n",- " def next(self):\n",- " if self.order: # Check if there is an open order\n",- " return\n",- "\n",- " # Check if we are in the market\n",- " if not self.position:\n",- " # Buy signal (for simplicity, we buy every time)\n",- " self.order = self.buy()\n",- " self.entry_price = self.data.close[0]\n",- " print(f\"BUY ORDER PLACED at {self.entry_price:.2f}\")\n",- "\n",- " else:\n",- " # Check for stop-loss and take-profit\n",- " stop_loss_price = self.entry_price * (1 - self.params.stop_loss_pct)\n",- " take_profit_price = self.entry_price * (1 + self.params.take_profit_pct)\n",- "\n",- " if self.data.close[0] <= stop_loss_price:\n",- " self.order = self.sell() # Trigger stop-loss\n",- " print(f\"SELL ORDER PLACED at {self.data.close[0]:.2f} (Stop-Loss Triggered)\")\n",- " elif self.data.close[0] >= take_profit_price:\n",- " self.order = self.sell() # Trigger take-profit\n",- " print(f\"SELL ORDER PLACED at {self.data.close[0]:.2f} (Take-Profit Triggered)\")\n",- "\n",- "# Create a Cerebro engine instance\n",- "cerebro = bt.Cerebro()\n",- "\n",- "# Download historical data for AAPL\n",- "data = bt.feeds.PandasData(dataname=yf.download('AAPL', start='2020-01-01', end='2023-01-01'))\n",- "\n",- "# Add the data feed to Cerebro\n",- "cerebro.adddata(data)\n",- "\n",- "# Add the trading strategy to Cerebro\n",- "cerebro.addstrategy(MyStrategy)\n",- "\n",- "# Set the initial cash for the backtest\n",- "cerebro.broker.setcash(10000.0)\n",- "\n",- "# Run the backtest\n",- "print(\"Starting Portfolio Value: %.2f\" % cerebro.broker.getvalue())\n",- "cerebro.run()\n",- "print(\"Ending Portfolio Value: %.2f\" % cerebro.broker.getvalue())\n",- "```\n",- "\n",- "### Explanation of the Code:\n",- "1. **Strategy Definition**: The `MyStrategy` class defines the trading strategy:\n",- " - It uses parameters for stop-loss and take-profit percentages.\n",- " - In the `next` method, it checks if there is an open order. If not, it places a buy order.\n",- " - If already in a position, it checks the current price against the stop-loss and take-profit levels and sells if either condition is met.\n",- "\n",- "2. **Cerebro Engine**: The `Cerebro` engine is created to manage the backtesting process:\n",- " - Historical data for AAPL is downloaded using `yfinance` and fed into Backtrader using `bt.feeds.PandasData`.\n",- " - The trading strategy is added to the Cerebro engine.\n",- " - The initial cash for the backtest is set to $10,000.\n",- "\n",- "3. **Running the Backtest**: The backtest is executed using `cerebro.run()`, and the starting and ending portfolio values are printed.\n",- "\n",- "This setup allows you to simulate trades based on historical data, evaluate the performance of your trading strategy, and make adjustments as necessary before deploying it in a live market.\n",- "\n",- "Next request.\n",- "\n",- "\n",- "\u001b[34mAI User:\n",- "\n",- "Instruction: Document the entire trading bot project, including setup instructions, usage guidelines, and code explanations. \n",- "Input: Create a README.md file that outlines the project structure and provides detailed information for users.\n",- "\n",- "\n",- "\u001b[32mAI Assistant:\n",- "\n",- "Solution: Below is a template for a `README.md` file that documents the entire trading bot project. This file includes setup instructions, usage guidelines, and code explanations to help users understand and utilize the trading bot effectively.\n",- "\n",- "```markdown\n",- "# Trading Bot Project\n",- "\n",- "## Overview\n",- "This trading bot utilizes machine learning algorithms and risk management strategies to analyze historical stock data, identify patterns, and execute buy/sell orders automatically. The bot is designed to be tested in a simulated environment before deployment in a live market.\n",- "\n",- "## Project Structure\n",- "```\n",- "trading_bot/\n",- "โ\n",- "โโโ trading_bot.py # Main trading bot script\n",- "โโโ dashboard.py # Dashboard for monitoring performance\n",- "โโโ backtest.py # Backtesting script using Backtrader\n",- "โโโ trading_bot.log # Log file for tracking actions and performance\n",- "โโโ requirements.txt # List of required Python libraries\n",- "โโโ README.md # Project documentation\n",- "```\n",- "\n",- "## Setup Instructions\n",- "\n",- "### Prerequisites\n",- "- Python 3.x installed on your machine.\n",- "- A virtual environment is recommended for managing dependencies.\n",- "\n",- "### Installation Steps\n",- "1. **Clone the Repository**:\n",- " ```bash\n",- " git clone <repository-url>\n",- " cd trading_bot\n",- " ```\n",- "\n",- "2. **Create a Virtual Environment** (optional but recommended):\n",- " ```bash\n",- " python -m venv trading_bot_env\n",- " source trading_bot_env/bin/activate # On Windows use `trading_bot_env\\Scripts\\activate`\n",- " ```\n",- "\n",- "3. **Install Required Libraries**:\n",- " Install the necessary libraries using pip:\n",- " ```bash\n",- " pip install -r requirements.txt\n",- " ```\n",- "\n",- "4. **Run the Trading Bot**:\n",- " You can run the trading bot using:\n",- " ```bash\n",- " python trading_bot.py\n",- " ```\n",- "\n",- "5. **Access the Dashboard**:\n",- " To monitor the trading bot's performance, run:\n",- " ```bash\n",- " python dashboard.py\n",- " ```\n",- " Then open your web browser and navigate to `http://127.0.0.1:8050`.\n",- "\n",- "6. **Run Backtesting**:\n",- " To evaluate the trading strategy, run:\n",- " ```bash\n",- " python backtest.py\n",- " ```\n",- "\n",- "## Usage Guidelines\n",- "\n",- "### Trading Bot\n",- "- The bot fetches historical stock data and uses a linear regression model to predict future prices.\n",- "- It incorporates risk management strategies, including stop-loss and take-profit levels.\n",- "- The bot logs all actions and decisions to a log file (`trading_bot.log`).\n",- "\n",- "### Dashboard\n",- "- The dashboard allows users to monitor real-time stock prices and adjust trading parameters (entry price, stop-loss, take-profit).\n",- "- Users can input the stock symbol and parameters, and the dashboard will display the current price, stop-loss, and take-profit levels.\n",- "\n",- "### Backtesting\n",- "- The backtesting script simulates trades based on historical data to evaluate the performance of the trading strategy.\n",- "- Users can analyze the results to make informed decisions before deploying the bot in a live market.\n",- "\n",- "## Code Explanations\n",- "\n",- "### Main Trading Bot (`trading_bot.py`)\n",- "- **Data Fetching**: Uses the `yfinance` library to download historical stock data.\n",- "- **Machine Learning Model**: Implements a linear regression model to predict future stock prices.\n",- "- **Risk Management**: Defines functions to calculate stop-loss and take-profit prices based on user-defined percentages.\n",- "- **Real-Time Monitoring**: Continuously fetches real-time prices and makes trading decisions based on the current market conditions.\n",- "\n",- "### Dashboard (`dashboard.py`)\n",- "- **Dash Framework**: Utilizes the Dash library to create an interactive web interface.\n",- "- **User Inputs**: Allows users to input stock symbols and trading parameters.\n",- "- **Real-Time Updates**: Displays current stock prices and calculated stop-loss/take-profit levels.\n",- "\n",- "### Backtesting Script (`backtest.py`)\n",- "- **Backtrader Framework**: Uses Backtrader to simulate trades based on historical data.\n",- "- **Trading Strategy**: Implements a simple strategy that uses stop-loss and take-profit logic.\n",- "- **Performance Evaluation**: Outputs the starting and ending portfolio values to assess the strategy's effectiveness.\n",- "\n",- "## Logging\n",- "- The bot logs all actions, decisions, and errors to `trading_bot.log` for tracking performance over time.\n",- "\n",- "## Contributing\n",- "Contributions are welcome! Please feel free to submit a pull request or open an issue for any suggestions or improvements.\n",- "\n",- "## License\n",- "This project is licensed under the MIT License - see the LICENSE file for details.\n",- "\n",- "## Acknowledgments\n",- "- Thanks to the contributors and libraries that made this project possible.\n",- "```\n",- "\n",- "### Explanation of the README.md Content:\n",- "1. **Overview**: Provides a brief description of the trading bot and its purpose.\n",- "2. **Project Structure**: Outlines the files and directories in the project.\n",- "3. **Setup Instructions**: Detailed steps for setting up the environment and running the bot, dashboard, and backtesting script.\n",- "4. **Usage Guidelines**: Instructions on how to use the trading bot, dashboard, and backtesting features.\n",- "5. **Code Explanations**: Descriptions of the main components of the code and their functionalities.\n",- "6. **Logging**: Information about the logging mechanism used in the bot.\n",- "7. **Contributing**: Encouragement for others to contribute to the project.\n",- "8. **License**: Information about the project's licensing.\n",- "9. **Acknowledgments**: Thanks to contributors and libraries used in the project.\n",- "\n",- "This README file serves as comprehensive documentation for users to understand, set up, and utilize the trading bot effectively.\n",- "\n",- "Next request.\n",- "\n",- "\n",- "\u001b[34mAI User:\n",- "\n",- "<CAMEL_TASK_DONE>\n",- "\n",- "\n",- "\u001b[32mAI Assistant:\n",- "\n",- "Solution: Great! It looks like we have successfully completed the trading bot project, including all the necessary components such as data gathering, machine learning model implementation, risk management strategies, real-time market data integration, a user-friendly dashboard, logging mechanisms, and backtesting capabilities. \n",- "\n",- "If you have any further questions or need assistance with anything else related to the trading bot or any other topic, feel free to ask!\n",- "\n",- "Next request.\n",- "\n",- "\n"- ]+ "kernelspec": {+ "name": "python3",+ "display_name": "Python 3"}- ],- "source": [- "def main(model=None, chat_turn_limit=10) -> None:\n",- "# Initial the role-playing session on developing a trading bot task with default model (`GPT_4O_MINI`)\n",- " task_prompt = \"Develop a trading bot for the stock market\"\n",- " role_play_session = RolePlaying(\n",- " assistant_role_name=\"Python Programmer\",\n",- " assistant_agent_kwargs=dict(model=model),\n",- " user_role_name=\"Stock Trader\",\n",- " user_agent_kwargs=dict(model=model),\n",- " task_prompt=task_prompt,\n",- " with_task_specify=True,\n",- " task_specify_agent_kwargs=dict(model=model),\n",- " )\n",- "\n",- "# Output initial message with different colors.\n",- " print(\n",- " Fore.GREEN\n",- " + f\"AI Assistant sys message:\\n{role_play_session.assistant_sys_msg}\\n\"\n",- " )\n",- " print(\n",- " Fore.BLUE + f\"AI User sys message:\\n{role_play_session.user_sys_msg}\\n\"\n",- " )\n",- "\n",- " print(Fore.YELLOW + f\"Original task prompt:\\n{task_prompt}\\n\")\n",- " print(\n",- " Fore.CYAN\n",- " + \"Specified task prompt:\"\n",- " + f\"\\n{role_play_session.specified_task_prompt}\\n\"\n",- " )\n",- " print(Fore.RED + f\"Final task prompt:\\n{role_play_session.task_prompt}\\n\")\n",- "\n",- " n = 0\n",- " input_msg = role_play_session.init_chat()\n",- "\n",- "# Output response step by step with different colors.\n",- "# Keep output until detect the terminate content or reach the loop limit.\n",- " while n < chat_turn_limit:\n",- " n += 1\n",- " assistant_response, user_response = role_play_session.step(input_msg)\n",- "\n",- " if assistant_response.terminated:\n",- " print(\n",- " Fore.GREEN\n",- " + (\n",- " \"AI Assistant terminated. Reason: \"\n",- " f\"{assistant_response.info['termination_reasons']}.\"\n",- " )\n",- " )\n",- " break\n",- " if user_response.terminated:\n",- " print(\n",- " Fore.GREEN\n",- " + (\n",- " \"AI User terminated. \"\n",- " f\"Reason: {user_response.info['termination_reasons']}.\"\n",- " )\n",- " )\n",- " break\n",- "\n",- " print_text_animated(\n",- " Fore.BLUE + f\"AI User:\\n\\n{user_response.msg.content}\\n\"\n",- " )\n",- " print_text_animated(\n",- " Fore.GREEN + \"AI Assistant:\\n\\n\"\n",- " f\"{assistant_response.msg.content}\\n\"\n",- " )\n",- "\n",- " if \"CAMEL_TASK_DONE\" in user_response.msg.content:\n",- " break\n",- "\n",- " input_msg = assistant_response.msg\n",- "\n",- "if __name__ == \"__main__\":\n",- " main()"- ]- }- ],- "metadata": {- "colab": {- "provenance": []- },- "kernelspec": {- "display_name": "Python 3",- "name": "python3"},- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 0-}+ "nbformat": 4,+ "nbformat_minor": 0+}\ No newline at end of filediff --git a/docs/cookbooks/agents_tracking.ipynb b/docs/cookbooks/agents_tracking.ipynbindex 68f7926bf..34a6d3615 100644--- a/docs/cookbooks/agents_tracking.ipynb+++ b/docs/cookbooks/agents_tracking.ipynb@@ -1,880 +1,844 @@{- "cells": [- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "xfCn_BAUzUn1"- },- "source": [- "# Using AgentOps to Track CAMEL Agents"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "8XgBUh3mU7iZ"- },- "source": [- "You can also check this cookbook in colab [here](https://colab.research.google.com/drive/1z1-c0zYuErO7Zh2EATPyDSgrlkrxGTFR?usp=sharing)"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "vB9bXVtbz2G3"- },- "source": [- "*Goal: Track and analysis the running of CAMEL Single Agent and Multiple Agents including LLMs and Tools usage*"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "MW7aNzQJBYp7"- },- "source": [- "<img src=\"https://raw.githubusercontent.com/AgentOps-AI/agentops/main/docs/images/external/app_screenshots/drilldown.gif\"/>"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "hKWiwah20PNq"- },- "source": [- "## ๐ฆ Installation"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "DpO2RbCY52fk"- },- "source": [- "First, install the CAMEL and AgentOps package with all its dependencies:"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "collapsed": true,- "id": "7qJrefKOt0lt"- },- "outputs": [],- "source": [- "%pip install \"camel-ai[all]==0.2.1\"\n",- "%pip install \"agentops==0.3.10\""- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "tsI56w-N5-Fk"- },- "source": [- "## ๐ Setting Up API Keys"- ]- },- {- "cell_type": "code",- "execution_count": 2,- "metadata": {- "id": "BSWFiGJ4uKJS"- },- "outputs": [],- "source": [- "import agentops\n",- "import os\n",- "from getpass import getpass"- ]- },- {- "cell_type": "code",- "execution_count": 3,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "7AftfweruKxo",- "outputId": "6c781b49-692f-4a9d-d9f6-ed4247572ea1"- },- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "Enter your API key: ยทยทยทยทยทยทยทยทยทยท\n"- ]- }- ],- "source": [- "# 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",- "metadata": {- "id": "fHwVVDMJ0lLx"- },- "source": [- "You can go to [here](https://app.agentops.ai/signin) to get **free** API Key from AgentOps"- ]- },- {- "cell_type": "code",- "execution_count": 4,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "WpYY5oTyuS7P",- "outputId": "9b803b72-e3b5-4b40-f0af-455195a89c1e"- },- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "Enter your API key: ยทยทยทยทยทยทยทยทยทยท\n"- ]- }- ],- "source": [- "# Prompt for the AgentOps API key securely\n",- "agentops_api_key = getpass('Enter your API key: ')\n",- "os.environ[\"AGENTOPS_API_KEY\"] = agentops_api_key"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "htBhPJx00ycJ"- },- "source": [- "## ๐ค Run CAMEL Single Agent with Tool by using AgentOps to track the whole process!"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "tD681Bxi1vRo"- },- "source": [- "Import required modules from CAMEL"- ]- },- {- "cell_type": "code",- "execution_count": 5,- "metadata": {- "id": "CuJQPZG-1yey"- },- "outputs": [],- "source": [- "from camel.agents import ChatAgent\n",- "from camel.configs import ChatGPTConfig\n",- "from camel.messages import BaseMessage\n",- "from camel.models import ModelFactory\n",- "from camel.types import ModelPlatformType, ModelType"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "Kc3uKwd71sHG"- },- "source": [- "Initilize AgentOps, you need to import toolkits after init of agentops so that the tool useage would be tracked."- ]- },- {- "cell_type": "code",- "execution_count": 6,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "collapsed": true,- "id": "_3FycEiQ1qDy",- "outputId": "ea2aa039-47f0-4cf2-8d87-0b7fbd1970e4"- },- "outputs": [- {- "name": "stderr",- "output_type": "stream",- "text": [- "๐ AgentOps: \u001B[34m\u001B[34mSession Replay: https://app.agentops.ai/drilldown?session_id=ee5858cd-51ea-46b4-90da-df905998f374\u001B[0m\u001B[0m\n"- ]- }- ],- "source": [- "AGENTOPS_API_KEY = os.getenv(\"AGENTOPS_API_KEY\")\n",- "agentops.init(AGENTOPS_API_KEY, default_tags=[\"CAMEL X AgentOps Single Agent with Tool Example\"])\n",- "\n",- "from camel.toolkits import SearchToolkit"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "Ehu6-xC610Bj"- },- "source": [- "Set one Agent with Search Tools"- ]- },- {- "cell_type": "code",- "execution_count": 8,- "metadata": {- "id": "DhMcowdE19Ti"- },- "outputs": [],- "source": [- "# Define system message\n",- "sys_msg = BaseMessage.make_assistant_message(\n",- " role_name='Tools calling opertor', content='You are a helpful assistant'\n",- ")\n",- "\n",- "# Set model config\n",- "tools = [*SearchToolkit().get_tools()]\n",- "\n",- "\n",- "model = ModelFactory.create(\n",- " model_platform=ModelPlatformType.OPENAI,\n",- " model_type=ModelType.GPT_4O_MINI,\n",- " model_config_dict=ChatGPTConfig(\n",- " temperature=0.0,\n",- " ).as_dict(),\n",- ")\n",- "\n",- "# Set agent\n",- "camel_agent = ChatAgent(\n",- " system_message=sys_msg,\n",- " model=model,\n",- " tools=tools,\n",- ")"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "vbFL0h-O1_PM"- },- "source": [- "Set user query and run the agent"- ]- },- {- "cell_type": "code",- "execution_count": 9,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "3TT62TanuYqI",- "outputId": "9a7a931d-c1dd-41b4-e5a4-1f930e4f7edf"- },- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "msgs=[BaseMessage(role_name='Tools calling opertor', role_type=<RoleType.ASSISTANT: 'assistant'>, meta_dict={}, content='CAMEL-AI.org is an open-source community and framework focused on the study and development of multi-agent systems using large language models (LLMs). Here are some key points about CAMEL-AI:\\n\\n1. **Framework for Multi-Agent Systems**: It is the first LLM multi-agent framework, allowing for the customization and integration of various AI models to create intelligent agents.\\n\\n2. **Research and Insights**: The community is dedicated to exploring the behaviors, capabilities, and potential risks associated with autonomous and communicative agents. They believe that studying these agents on a large scale can provide valuable insights.\\n\\n3. **Customization and Modularity**: CAMEL empowers users to customize agents using modular components tailored for specific tasks, facilitating flexible integration of different AI models.\\n\\n4. **Open Source**: The project is open-source, encouraging collaboration and contributions from developers and researchers interested in AI and multi-agent systems.\\n\\nFor more information, you can visit their official website: [CAMEL-AI.org](https://www.camel-ai.org/).', video_bytes=None, image_list=None, image_detail='auto', video_detail='low')] terminated=False info={'id': 'chatcmpl-A7QvNObfjEpD2tdV5ennjFCOLbDwN', 'usage': {'completion_tokens': 209, 'prompt_tokens': 974, 'total_tokens': 1183, 'completion_tokens_details': {'reasoning_tokens': 0}}, 'termination_reasons': ['stop'], 'num_tokens': 660, 'tool_calls': [FunctionCallingRecord(func_name='search_google', args={'query': 'CAMEL-AI.org'}, result=[{'error': 'google search failed.'}]), FunctionCallingRecord(func_name='search_duckduckgo', args={'query': 'CAMEL-AI.org'}, result=[{'result_id': 1, 'title': 'Camel-ai', 'description': 'CAMEL-AI.org is the 1st LLM multi-agent framework and an open-source community dedicated to finding the scaling law of agents. Get Started. 1 Customize agents. Customizable agents are the fundamental entities of the CAMEL architecture. CAMEL empowers you to customize agents using our modular components for specific tasks.', 'url': 'https://www.camel-ai.org/'}, {'result_id': 2, 'title': 'Camel-ai', 'description': 'Mission. CAMEL-AI.org is an open-source community dedicated to the study of autonomous and communicative agents. We believe that studying these agents on a large scale offers valuable insights into their behaviors, capabilities, and potential risks. To facilitate research in this field, we provide, implement, and support various types of agents ...', 'url': 'https://www.camel-ai.org/?trk=public_post-text'}, {'result_id': 3, 'title': 'Get started with Model Calling - CAMEL 101 - camel-ai.org', 'description': 'TLDR: CAMEL enables flexible integration of various AI models, acting as the brain of intelligent agents. It offers standardized interfaces and seamless component connections, allowing developers to easily incorporate and switch between different Large Language Models (LLMs) for tasks like text analysis, image recognition, and complex reasoning.', 'url': 'https://www.camel-ai.org/post/get-started-with-models---camel-101'}, {'result_id': 4, 'title': 'GitHub - camel-ai/camel: CAMEL: Finding the Scaling Law of Agents. A ...', 'description': 'www.camel-ai.org Topics agent natural-language-processing deep-learning artificial-intelligence multi-agent-systems ai-societies large-language-models cooperative-ai communicative-ai', 'url': 'https://github.com/camel-ai/camel'}, {'result_id': 5, 'title': 'camel-ai.org ยท GitHub', 'description': '๐ Hello AI enthusiasts! We are ๐ซ CAMEL-AI.org, the pioneer of a large language model-based multi-agent framework. Our open-source community, inspired by our research paper \"CAMEL: Communicative Agents for \\'Mind\\' Exploration of Large Language Model Society,\" aims to explore scalable techniques for autonomous cooperation among ...', 'url': 'https://github.com/camel-ai/'}])], 'external_tool_request': None}\n"- ]- },- {- "name": "stderr",- "output_type": "stream",- "text": [- "๐ AgentOps: This run's cost $0.000411\n",- "๐ AgentOps: \u001B[34m\u001B[34mSession Replay: https://app.agentops.ai/drilldown?session_id=ee5858cd-51ea-46b4-90da-df905998f374\u001B[0m\u001B[0m\n"- ]- }- ],- "source": [- "# Define a user message\n",- "usr_msg = BaseMessage.make_user_message(\n",- " role_name='CAMEL User', content='What is CAMEL-AI.org?'\n",- ")\n",- "\n",- "# Get response information\n",- "response = camel_agent.step(usr_msg)\n",- "print(response)\n",- "\n",- "\n",- "agentops.end_session(\"Success\")"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "gRdtzKEn2F9t"- },- "source": [- "### ๐ Go to the AgentOps link shown above, you will be able to see the detailed record for this running like below."- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "Glt8bYV4yHwW"- },- "source": [- ""- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "jnCwxeW82YEw"- },- "source": [- "## ๐ค๐ค Run CAMEL Multi-agent with Tool by using AgentOps to track the whole process!"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "7cw_P_ab2gLp"- },- "source": [- "Import required modules"- ]- },- {- "cell_type": "code",- "execution_count": 10,- "metadata": {- "id": "8DJgHQ7_2qxI"- },- "outputs": [],- "source": [- "from typing import List\n",- "\n",- "from colorama import Fore\n",- "\n",- "from camel.agents.chat_agent import FunctionCallingRecord\n",- "from camel.configs import ChatGPTConfig\n",- "from camel.models import ModelFactory\n",- "from camel.societies import RolePlaying\n",- "from camel.types import ModelPlatformType, ModelType\n",- "from camel.utils import print_text_animated\n",- "\n",- "import agentops"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "W-lbshs42tFE"- },- "source": [- "Initilize AgentOps, you need to import toolkits after init of agentops so that the tool useage would be tracked."- ]- },- {- "cell_type": "code",- "execution_count": 11,- "metadata": {+ "nbformat": 4,+ "nbformat_minor": 0,+ "metadata": {"colab": {- "base_uri": "https://localhost:8080/"- },- "id": "Sl0WYG_P2zm0",- "outputId": "0857418b-3d3f-49c4-cf90-715d2bd11979"- },- "outputs": [- {- "name": "stderr",- "output_type": "stream",- "text": [- "๐ AgentOps: \u001B[34m\u001B[34mSession Replay: https://app.agentops.ai/drilldown?session_id=d67ffe18-96a6-4888-a252-e014b5f4e486\u001B[0m\u001B[0m\n"- ]- }- ],- "source": [- "agentops.start_session(tags=[\"CAMEL X AgentOps Multi-agent with Tools\"])\n",- "\n",- "from camel.toolkits import (\n",- " SearchToolkit,\n",- " MathToolkit,\n",- ")"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "7-eQpg4M3JDq"- },- "source": [- "Set your task prompt"- ]- },- {- "cell_type": "code",- "execution_count": 12,- "metadata": {- "id": "dOuEoNyK3KlM"- },- "outputs": [],- "source": [- "task_prompt = (\n",- " \"Assume now is 2024 in the Gregorian calendar, \"\n",- " \"estimate the current age of University of Oxford \"\n",- " \"and then add 10 more years to this age, \"\n",- " \"and get the current weather of the city where \"\n",- " \"the University is located.\"\n",- ")"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "yiRYDJ8M3UDE"- },- "source": [- "Set tools for the assistant agent, we wish the agent would be able to do mathmatic calculation and search information from websites"- ]- },- {- "cell_type": "code",- "execution_count": 13,- "metadata": {- "id": "7Re8DJ4r3YyY"- },- "outputs": [],- "source": [- "tools = [\n",- " *MathToolkit().get_tools(),\n",- " *SearchToolkit().get_tools(),\n",- "]"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "g9lJYmi83scb"- },- "source": [- "Set config of the model for User Agent and Assisant Agent"- ]- },- {- "cell_type": "code",- "execution_count": 14,- "metadata": {- "id": "GpSDvtEq3tVr"- },- "outputs": [],- "source": [- "user_model_config = ChatGPTConfig(\n",- " temperature=0.0,\n",- ")\n",- "\n",- "assistant_model_config = ChatGPTConfig(\n",- " tools=tools,\n",- " temperature=0.0,\n",- ")"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "P3KGyxYi4MNC"- },- "source": [- "Set up Role Playing session"- ]- },- {- "cell_type": "code",- "execution_count": 16,- "metadata": {- "id": "m1BPtWgi33FJ"- },- "outputs": [],- "source": [- "role_play_session = RolePlaying(\n",- " assistant_role_name=\"Searcher\",\n",- " user_role_name=\"Professor\",\n",- " assistant_agent_kwargs=dict(\n",- " model=ModelFactory.create(\n",- " model_platform=ModelPlatformType.OPENAI,\n",- " model_type=ModelType.GPT_4O_MINI,\n",- " model_config_dict=assistant_model_config.as_dict(),\n",- " ),\n",- " tools=tools,\n",- " ),\n",- " user_agent_kwargs=dict(\n",- " model=ModelFactory.create(\n",- " model_platform=ModelPlatformType.OPENAI,\n",- " model_type=ModelType.GPT_4O_MINI,\n",- " model_config_dict=user_model_config.as_dict(),\n",- " ),\n",- " ),\n",- " task_prompt=task_prompt,\n",- " with_task_specify=False,\n",- ")"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "Qp3WwE-r4WTZ"- },- "source": [- "Print the system message and task prompt"- ]- },- {- "cell_type": "code",- "execution_count": 17,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "_xmNJtft4aZx",- "outputId": "be8f1852-3b5d-4183-d9c5-5e82aaf6f2dd"- },- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "\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, and get the current weather of the city where the University is located.', '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, and get the current weather of the city where the University is located.. 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",- "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, and get the current weather of the city where the University is located.', '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, and get the current weather of the city where the University is located.. 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",- "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, and get the current weather of the city where the University is located.\n",- "\n",- "\u001B[36mSpecified task prompt:\n",- "None\n",- "\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, and get the current weather of the city where the University is located.\n",- "\n"- ]- }- ],- "source": [- "print(\n",- " Fore.GREEN\n",- " + f\"AI Assistant sys message:\\n{role_play_session.assistant_sys_msg}\\n\"\n",- ")\n",- "print(Fore.BLUE + f\"AI User sys message:\\n{role_play_session.user_sys_msg}\\n\")\n",- "\n",- "print(Fore.YELLOW + f\"Original task prompt:\\n{task_prompt}\\n\")\n",- "print(\n",- " Fore.CYAN\n",- " + \"Specified task prompt:\"\n",- " + f\"\\n{role_play_session.specified_task_prompt}\\n\"\n",- ")\n",- "print(Fore.RED + f\"Final task prompt:\\n{role_play_session.task_prompt}\\n\")"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "d5JjlXhs4cJT"- },- "source": [- "Set terminate rule and print the chat message"- ]- },- {- "cell_type": "code",- "execution_count": 18,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "z7bjGKlr4eVf",- "outputId": "03df6228-b15f-4153-dfc8-1891c61538cb"- },- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "\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",- "\n",- "Solution: The University of Oxford is believed to have been founded in the 12th century, with the earliest evidence of teaching at the university dating back to around 1096. However, the exact founding year is not definitively known. For estimation purposes, we can consider the year 1096 as a starting point for the university's establishment.\n",- "\n",- "Next request.\n",- "\n",- "\n",- "\u001B[34mAI User:\n",- "\n",- "Instruction: Calculate the current age of the University of Oxford in 2024 based on the estimated founding year of 1096. \n",- "Input: None\n",- "\n",- "\n",- "\u001B[32mAI Assistant:\n",- "\n",- "Function Execution: sub\n",- "\tArgs: {'a': 2024, 'b': 1096}\n",- "\tResult: 928\n",- "\n",- "Solution: To calculate the current age of the University of Oxford in 2024, we subtract the estimated founding year (1096) from the current year (2024):\n",- "\n",- "2024 - 1096 = 928\n",- "\n",- "Therefore, the estimated current age of the University of Oxford in 2024 is 928 years.\n",- "\n",- "Next request.\n",- "\n",- "\n",- "\u001B[34mAI User:\n",- "\n",- "Instruction: Add 10 years to the current age of the University of Oxford. \n",- "Input: None\n",- "\n",- "\n",- "\u001B[32mAI Assistant:\n",- "\n",- "Function Execution: add\n",- "\tArgs: {'a': 928, 'b': 10}\n",- "\tResult: 938\n",- "\n",- "Solution: To add 10 years to the current age of the University of Oxford (928 years), we perform the following calculation:\n",- "\n",- "928 + 10 = 938\n",- "\n",- "Thus, the age of the University of Oxford, after adding 10 years, is estimated to be 938 years in 2034.\n",- "\n",- "Next request.\n",- "\n",- "\n",- "\u001B[34mAI User:\n",- "\n",- "Instruction: Find the current weather in Oxford, England. \n",- "Input: None\n",- "\n",- "\n",- "\u001B[32mAI Assistant:\n",- "\n",- "Function Execution: search_google\n",- "\tArgs: {'query': 'current weather in Oxford, England'}\n",- "\tResult: [{'error': 'google search failed.'}]\n",- "\n",- "Solution: I attempted to retrieve the current weather in Oxford, England, but the search request failed. Unfortunately, I am unable to provide the current weather information at this moment due to this issue.\n",- "\n",- "Next request.\n",- "\n",- "\n",- "\u001B[34mAI User:\n",- "\n",- "Instruction: Please check a reliable weather website or app to find the current weather in Oxford, England. \n",- "Input: None\n",- "\n",- "\n",- "\u001B[32mAI Assistant:\n",- "\n",- "Solution: I am unable to access external websites or apps directly to check the current weather in Oxford, England. My capabilities are limited to using predefined functions and tools, and I cannot browse the internet in real-time.\n",- "\n",- "However, you can easily check the current weather by visiting reliable weather websites such as:\n",- "\n",- "1. **Weather.com** (The Weather Channel)\n",- "2. **BBC Weather**\n",- "3. **AccuWeather**\n",- "4. **Met Office** (UK's national weather service)\n",- "\n",- "These platforms provide up-to-date weather information for specific locations, including Oxford, England.\n",- "\n",- "Next request.\n",- "\n",- "\n",- "\u001B[34mAI User:\n",- "\n",- "Instruction: Please provide the current weather in Oxford, England, based on your findings from a reliable weather website or app. \n",- "Input: None\n",- "\n",- "\n",- "\u001B[32mAI Assistant:\n",- "\n",- "Function Execution: search_duckduckgo\n",- "\tArgs: {'query': 'current weather in Oxford, England'}\n",- "\tResult: [{'result_id': 1, 'title': 'Oxford (Oxfordshire) weather | Met Office', 'description': 'Oxford 7 day weather forecast including weather warnings, temperature, rain, wind, visibility, humidity and UV.', 'url': 'https://www.metoffice.gov.uk/weather/forecast/gcpn7mp10'}, {'result_id': 2, 'title': 'Oxford, Oxfordshire, United Kingdom Current Weather | AccuWeather', 'description': 'Current weather in Oxford, Oxfordshire, United Kingdom. Check current conditions in Oxford, Oxfordshire, United Kingdom with radar, hourly, and more.', 'url': 'https://www.accuweather.com/en/gb/oxford/ox1-3/current-weather/330217'}, {'result_id': 3, 'title': 'Oxford, Oxfordshire, United Kingdom Weather Forecast | AccuWeather', 'description': 'Oxford, Oxfordshire, United Kingdom Weather Forecast, with current conditions, wind, air quality, and what to expect for the next 3 days.', 'url': 'https://www.accuweather.com/en/gb/oxford/ox1-3/weather-forecast/330217'}, {'result_id': 4, 'title': 'Oxford | BBC Weather', 'description': '14-day weather forecast for Oxford.', 'url': 'https://www.bbc.com/weather/2640729'}, {'result_id': 5, 'title': 'Weather Today for Oxford, Oxfordshire, United Kingdom | AccuWeather', 'description': \"Everything you need to know about today's weather in Oxford, Oxfordshire, United Kingdom. High/Low, Precipitation Chances, Sunrise/Sunset, and today's Temperature History.\", 'url': 'https://www.accuweather.com/en/gb/oxford/ox1-3/weather-today/330217'}]\n",- "\n",- "Solution: I found several reliable sources for the current weather in Oxford, England. Here are some options where you can check the latest weather information:\n",- "\n",- "1. **Met Office**: [Oxford Weather Forecast](https://www.metoffice.gov.uk/weather/forecast/gcpn7mp10) - This site provides a 7-day weather forecast including temperature, rain, wind, and more.\n",- "\n",- "2. **AccuWeather**: [Current Weather in Oxford](https://www.accuweather.com/en/gb/oxford/ox1-3/current-weather/330217) - This page offers current conditions, radar, and hourly updates.\n",- "\n",- "3. **BBC Weather**: [BBC Weather for Oxford](https://www.bbc.com/weather/2640729) - This site provides a 14-day weather forecast for Oxford.\n",- "\n",- "You can visit any of these links to find the current weather conditions in Oxford, England.\n",- "\n",- "Next request.\n",- "\n",- "\n",- "\u001B[34mAI User:\n",- "\n",- "Instruction: Summarize the findings regarding the age of the University of Oxford and the current weather in Oxford, England. \n",- "Input: None\n",- "\n",- "\n",- "\u001B[32mAI Assistant:\n",- "\n",- "Solution: \n",- "\n",- "1. **Age of the University of Oxford**:\n",- " - The University of Oxford is estimated to have been founded around the year 1096.\n",- " - As of 2024, this makes the university approximately 928 years old.\n",- " - When adding 10 years to this age, the estimated age of the University of Oxford in 2034 will be 938 years.\n",- "\n",- "2. **Current Weather in Oxford, England**:\n",- " - I was unable to retrieve the current weather directly due to a search failure.\n",- " - However, I provided links to reliable weather sources where the current weather can be checked:\n",- " - Met Office: [Oxford Weather Forecast](https://www.metoffice.gov.uk/weather/forecast/gcpn7mp10)\n",- " - AccuWeather: [Current Weather in Oxford](https://www.accuweather.com/en/gb/oxford/ox1-3/current-weather/330217)\n",- " - BBC Weather: [BBC Weather for Oxford](https://www.bbc.com/weather/2640729)\n",- "\n",- "These findings summarize the estimated age of the University of Oxford and provide resources for checking the current weather in Oxford, England.\n",- "\n",- "Next request.\n",- "\n",- "\n",- "\u001B[34mAI User:\n",- "\n",- "<CAMEL_TASK_DONE>\n",- "\n",- "\n",- "\u001B[32mAI Assistant:\n",- "\n",- "Solution: The task is now completed. We have estimated the age of the University of Oxford and provided resources for checking the current weather in Oxford, England. If you have any further questions or need assistance with another task, feel free to ask!\n",- "\n",- "Next request.\n",- "\n",- "\n"- ]+ "provenance": []+ },+ "kernelspec": {+ "name": "python3",+ "display_name": "Python 3"+ },+ "language_info": {+ "name": "python"}- ],- "source": [- "n = 0\n",- "input_msg = role_play_session.init_chat()\n",- "while n < 50:\n",- " n += 1\n",- " assistant_response, user_response = role_play_session.step(input_msg)\n",- "\n",- " if assistant_response.terminated:\n",- " print(\n",- " Fore.GREEN\n",- " + (\n",- " \"AI Assistant terminated. Reason: \"\n",- " f\"{assistant_response.info['termination_reasons']}.\"\n",- " )\n",- " )\n",- " break\n",- " if user_response.terminated:\n",- " print(\n",- " Fore.GREEN\n",- " + (\n",- " \"AI User terminated. \"\n",- " f\"Reason: {user_response.info['termination_reasons']}.\"\n",- " )\n",- " )\n",- " break\n",- "\n",- " # Print output from the user\n",- " print_text_animated(\n",- " Fore.BLUE + f\"AI User:\\n\\n{user_response.msg.content}\\n\"\n",- " )\n",- "\n",- " # Print output from the assistant, including any function\n",- " # execution information\n",- " print_text_animated(Fore.GREEN + \"AI Assistant:\")\n",- " tool_calls: List[FunctionCallingRecord] = assistant_response.info[\n",- " 'tool_calls'\n",- " ]\n",- " for func_record in tool_calls:\n",- " print_text_animated(f\"{func_record}\")\n",- " print_text_animated(f\"{assistant_response.msg.content}\\n\")\n",- "\n",- " if \"CAMEL_TASK_DONE\" in user_response.msg.content:\n",- " break\n",- "\n",- " input_msg = assistant_response.msg"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "pYZAD7-H4hhQ"- },- "source": [- "End the AgentOps session"- ]},- {- "cell_type": "code",- "execution_count": 19,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "c8YKJgu94k35",- "outputId": "61732966-e5d7-490b-a955-d9abb3ba05c9"- },- "outputs": [- {- "name": "stderr",- "output_type": "stream",- "text": [- "๐ AgentOps: This run's cost $0.003855\n",- "๐ AgentOps: \u001B[34m\u001B[34mSession Replay: https://app.agentops.ai/drilldown?session_id=d67ffe18-96a6-4888-a252-e014b5f4e486\u001B[0m\u001B[0m\n"- ]+ "cells": [+ {+ "cell_type": "markdown",+ "source": [+ "# ๐ซ Using AgentOps to Track CAMEL Agents"+ ],+ "metadata": {+ "id": "xfCn_BAUzUn1"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "You can also check this cookbook in colab [here](https://colab.research.google.com/drive/1z1-c0zYuErO7Zh2EATPyDSgrlkrxGTFR?usp=sharing)"+ ],+ "metadata": {+ "id": "8XgBUh3mU7iZ"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "*Goal: Track and analysis the running of CAMEL Single Agent and Multiple Agents including LLMs and Tools usage*"+ ],+ "metadata": {+ "id": "vB9bXVtbz2G3"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "<img src=\"https://raw.githubusercontent.com/AgentOps-AI/agentops/main/docs/images/external/app_screenshots/drilldown.gif\"/>"+ ],+ "metadata": {+ "id": "MW7aNzQJBYp7"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "## ๐ฆ Installation"+ ],+ "metadata": {+ "id": "hKWiwah20PNq"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "First, install the CAMEL and AgentOps package with all its dependencies:"+ ],+ "metadata": {+ "id": "DpO2RbCY52fk"+ }+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {+ "collapsed": true,+ "id": "7qJrefKOt0lt"+ },+ "outputs": [],+ "source": [+ "%pip install camel-ai[all]==0.2.4\n",+ "%pip install agentops==0.3.10"+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "## ๐ Setting Up API Keys"+ ],+ "metadata": {+ "id": "tsI56w-N5-Fk"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "import agentops\n",+ "import os\n",+ "from getpass import getpass"+ ],+ "metadata": {+ "id": "BSWFiGJ4uKJS"+ },+ "execution_count": 2,+ "outputs": []+ },+ {+ "cell_type": "code",+ "source": [+ "# 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"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "7AftfweruKxo",+ "outputId": "b510aa61-6a11-4fd2-915c-e9dc55540a3a"+ },+ "execution_count": 3,+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Enter your API key: ยทยทยทยทยทยทยทยทยทยท\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "You can go to [here](https://app.agentops.ai/signin) to get **free** API Key from AgentOps"+ ],+ "metadata": {+ "id": "fHwVVDMJ0lLx"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "# Prompt for the AgentOps API key securely\n",+ "agentops_api_key = getpass('Enter your API key: ')\n",+ "os.environ[\"AGENTOPS_API_KEY\"] = agentops_api_key"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "WpYY5oTyuS7P",+ "outputId": "fcd40766-01e2-4303-ef01-723435ae3a8e"+ },+ "execution_count": 4,+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Enter your API key: ยทยทยทยทยทยทยทยทยทยท\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "## ๐ค Run CAMEL Single Agent with Tool by using AgentOps to track the whole process!"+ ],+ "metadata": {+ "id": "htBhPJx00ycJ"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "Import required modules from CAMEL"+ ],+ "metadata": {+ "id": "tD681Bxi1vRo"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "from camel.agents import ChatAgent\n",+ "from camel.configs import ChatGPTConfig\n",+ "from camel.messages import BaseMessage\n",+ "from camel.models import ModelFactory\n",+ "from camel.types import ModelPlatformType, ModelType"+ ],+ "metadata": {+ "id": "CuJQPZG-1yey"+ },+ "execution_count": 5,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "Initilize AgentOps, you need to import toolkits after init of agentops so that the tool useage would be tracked."+ ],+ "metadata": {+ "id": "Kc3uKwd71sHG"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "AGENTOPS_API_KEY = os.getenv(\"AGENTOPS_API_KEY\")\n",+ "agentops.init(AGENTOPS_API_KEY, default_tags=[\"CAMEL X AgentOps Single Agent with Tool Example\"])\n",+ "\n",+ "from camel.toolkits import SearchToolkit"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "collapsed": true,+ "id": "_3FycEiQ1qDy",+ "outputId": "c578e8a5-1059-483c-b623-7f9ae4617f66"+ },+ "execution_count": 6,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stderr",+ "text": [+ "๐ AgentOps: WARNING: agentops is out of date. Please update with the command: 'pip install --upgrade agentops'\n",+ "๐ AgentOps: \u001b[34m\u001b[34mSession Replay: https://app.agentops.ai/drilldown?session_id=db687abe-4e5c-43d5-8eb2-21bf403256e7\u001b[0m\u001b[0m\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "Set one Agent with Search Tools"+ ],+ "metadata": {+ "id": "Ehu6-xC610Bj"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "# Define system message\n",+ "sys_msg = BaseMessage.make_assistant_message(\n",+ " role_name='Tools calling opertor', content='You are a helpful assistant'\n",+ ")\n",+ "\n",+ "# Set model config\n",+ "tools = [*SearchToolkit().get_tools()]\n",+ "\n",+ "\n",+ "model = ModelFactory.create(\n",+ " model_platform=ModelPlatformType.OPENAI,\n",+ " model_type=ModelType.GPT_4O_MINI,\n",+ ")\n",+ "\n",+ "# Set agent\n",+ "camel_agent = ChatAgent(\n",+ " system_message=sys_msg,\n",+ " model=model,\n",+ " tools=tools,\n",+ ")"+ ],+ "metadata": {+ "id": "DhMcowdE19Ti"+ },+ "execution_count": 7,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "Set user query and run the agent"+ ],+ "metadata": {+ "id": "vbFL0h-O1_PM"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "# Define a user message\n",+ "usr_msg = 'What is CAMEL-AI.org?'\n",+ "\n",+ "# Get response information\n",+ "response = camel_agent.step(usr_msg)\n",+ "print(response)\n",+ "\n",+ "\n",+ "agentops.end_session(\"Success\")"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "3TT62TanuYqI",+ "outputId": "b19d730e-d2f7-416b-af1b-1cbeb7a4d248"+ },+ "execution_count": 8,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "msgs=[BaseMessage(role_name='Tools calling opertor', role_type=<RoleType.ASSISTANT: 'assistant'>, meta_dict={}, content='CAMEL-AI.org is the official website for CAMEL, which is described as the first large language model (LLM) multi-agent framework. It is an open-source community dedicated to exploring the scaling laws of agents. The framework allows users to customize agents using modular components for specific tasks, facilitating research and development in the field of artificial intelligence.\\n\\nHere are some key points about CAMEL-AI:\\n\\n1. **Multi-Agent Framework**: CAMEL provides a structure for developing and utilizing multiple agents that can work together.\\n2. **Open Source**: The project is open-source, encouraging collaboration and contributions from the community.\\n3. **Customization**: Users can customize agents to perform specific tasks, enhancing their functionality and adaptability.\\n4. **Research Focus**: The initiative aims to study agents on a large scale to gain insights into their behaviors, capabilities, and potential risks.\\n\\nFor more information, you can visit their official website: [CAMEL-AI.org](https://www.camel-ai.org/).', video_bytes=None, image_list=None, image_detail='auto', video_detail='low')] terminated=False info={'id': 'chatcmpl-ALp4yBEZ70iWRyC2nU7Ns5Y4cqS5N', 'usage': {'completion_tokens': 204, 'prompt_tokens': 993, 'total_tokens': 1197, 'completion_tokens_details': {'audio_tokens': None, 'reasoning_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': None, 'cached_tokens': 0}}, 'termination_reasons': ['stop'], 'num_tokens': 679, 'tool_calls': [FunctionCallingRecord(func_name='search_google', args={'query': 'CAMEL-AI.org'}, result=[{'error': 'google search failed.'}]), FunctionCallingRecord(func_name='search_duckduckgo', args={'query': 'CAMEL-AI.org'}, result=[{'result_id': 1, 'title': 'Camel-ai', 'description': 'CAMEL-AI.org is the 1st LLM multi-agent framework and an open-source community dedicated to finding the scaling law of agents. Get Started. 1 Customize agents. Customizable agents are the fundamental entities of the CAMEL architecture. CAMEL empowers you to customize agents using our modular components for specific tasks.', 'url': 'https://www.camel-ai.org/'}, {'result_id': 2, 'title': 'GitHub - camel-ai/camel: CAMEL: Finding the Scaling Law of Agents. A ...', 'description': '๐ซ CAMEL: Finding the Scaling Law of Agents. A multi-agent framework. https://www.camel-ai.org - camel-ai/camel', 'url': 'https://github.com/camel-ai/camel'}, {'result_id': 3, 'title': 'CAMEL-AI - CRAB: Cross-environment Agent Benchmark for Multimodal ...', 'description': 'Please open the X app on my phone, search for CAMEL-AI.org, check the latest post, summarize them, and then send the summary to Tianqi Xu on Slack from my PC. Settings: OpenAI GPT-4o + Single Agent Demo videos are edited for a better viewing experience. In actual execution, there are tens of seconds of waiting time between each step.', 'url': 'https://crab.camel-ai.org/'}, {'result_id': 4, 'title': \"Welcome to CAMEL's documentation! โ CAMEL 0.2.2 documentation\", 'description': \"Welcome to CAMEL's documentation! #. We design practical artificial general intelligence. CAMEL emerges as the earliest LLM-based multi-agent framework, and is now a generic framework to build and use LLM-based agents for real-world task solving. We believe that studying these agents on a large scale offers valuable insights into their ...\", 'url': 'https://docs.camel-ai.org/'}, {'result_id': 5, 'title': 'Team - CAMEL-AI', 'description': 'Camel-AI Team. We are finding the scaling law of agent. ๐ซ CAMEL is an open-source library designed for the study of autonomous and communicative agents. We believe that studying these agents on a large scale offers valuable insights into their behaviors, capabilities, and potential risks. To facilitate research in this field, we implement ...', 'url': 'https://www.camel-ai.org/about'}])], 'external_tool_request': None}\n"+ ]+ },+ {+ "output_type": "stream",+ "name": "stderr",+ "text": [+ "๐ AgentOps: This run's cost $0.000411\n",+ "๐ AgentOps: \u001b[34m\u001b[34mSession Replay: https://app.agentops.ai/drilldown?session_id=db687abe-4e5c-43d5-8eb2-21bf403256e7\u001b[0m\u001b[0m\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "### ๐ Go to the AgentOps link shown above, you will be able to see the detailed record for this running like below."+ ],+ "metadata": {+ "id": "gRdtzKEn2F9t"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ ""+ ],+ "metadata": {+ "id": "Glt8bYV4yHwW"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "## ๐ค๐ค Run CAMEL Multi-agent with Tool by using AgentOps to track the whole process!"+ ],+ "metadata": {+ "id": "jnCwxeW82YEw"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "Import required modules"+ ],+ "metadata": {+ "id": "7cw_P_ab2gLp"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "from typing import List\n",+ "\n",+ "from colorama import Fore\n",+ "\n",+ "from camel.agents.chat_agent import FunctionCallingRecord\n",+ "from camel.configs import ChatGPTConfig\n",+ "from camel.models import ModelFactory\n",+ "from camel.societies import RolePlaying\n",+ "from camel.types import ModelPlatformType, ModelType\n",+ "from camel.utils import print_text_animated\n",+ "\n",+ "import agentops"+ ],+ "metadata": {+ "id": "8DJgHQ7_2qxI"+ },+ "execution_count": 9,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "Initilize AgentOps, you need to import toolkits after init of agentops so that the tool useage would be tracked."+ ],+ "metadata": {+ "id": "W-lbshs42tFE"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "agentops.start_session(tags=[\"CAMEL X AgentOps Multi-agent with Tools\"])\n",+ "\n",+ "from camel.toolkits import (\n",+ " SearchToolkit,\n",+ " MathToolkit,\n",+ ")"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "Sl0WYG_P2zm0",+ "outputId": "b1454134-523c-4130-9f13-f1e745b382ac"+ },+ "execution_count": 10,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stderr",+ "text": [+ "๐ AgentOps: \u001b[34m\u001b[34mSession Replay: https://app.agentops.ai/drilldown?session_id=6c46dfa1-662b-40e1-8343-b40934c5659c\u001b[0m\u001b[0m\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "Set your task prompt"+ ],+ "metadata": {+ "id": "7-eQpg4M3JDq"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "task_prompt = (\n",+ " \"Assume now is 2024 in the Gregorian calendar, \"\n",+ " \"estimate the current age of University of Oxford \"\n",+ " \"and then add 10 more years to this age, \"\n",+ " \"and get the current weather of the city where \"\n",+ " \"the University is located.\"\n",+ ")"+ ],+ "metadata": {+ "id": "dOuEoNyK3KlM"+ },+ "execution_count": 11,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "Set tools for the assistant agent, we wish the agent would be able to do mathmatic calculation and search information from websites"+ ],+ "metadata": {+ "id": "yiRYDJ8M3UDE"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "tools = [\n",+ " *MathToolkit().get_tools(),\n",+ " *SearchToolkit().get_tools(),\n",+ "]"+ ],+ "metadata": {+ "id": "7Re8DJ4r3YyY"+ },+ "execution_count": 12,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "Set up Role Playing session"+ ],+ "metadata": {+ "id": "P3KGyxYi4MNC"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "role_play_session = RolePlaying(\n",+ " assistant_role_name=\"Searcher\",\n",+ " user_role_name=\"Professor\",\n",+ " assistant_agent_kwargs=dict(\n",+ " model=ModelFactory.create(\n",+ " model_platform=ModelPlatformType.OPENAI,\n",+ " model_type=ModelType.GPT_4O_MINI,\n",+ " ),\n",+ " tools=tools,\n",+ " ),\n",+ " user_agent_kwargs=dict(\n",+ " model=ModelFactory.create(\n",+ " model_platform=ModelPlatformType.OPENAI,\n",+ " model_type=ModelType.GPT_4O_MINI,\n",+ " ),\n",+ " ),\n",+ " task_prompt=task_prompt,\n",+ " with_task_specify=False,\n",+ ")"+ ],+ "metadata": {+ "id": "m1BPtWgi33FJ"+ },+ "execution_count": 13,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "Print the system message and task prompt"+ ],+ "metadata": {+ "id": "Qp3WwE-r4WTZ"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "print(\n",+ " Fore.GREEN\n",+ " + f\"AI Assistant sys message:\\n{role_play_session.assistant_sys_msg}\\n\"\n",+ ")\n",+ "print(Fore.BLUE + f\"AI User sys message:\\n{role_play_session.user_sys_msg}\\n\")\n",+ "\n",+ "print(Fore.YELLOW + f\"Original task prompt:\\n{task_prompt}\\n\")\n",+ "print(\n",+ " Fore.CYAN\n",+ " + \"Specified task prompt:\"\n",+ " + f\"\\n{role_play_session.specified_task_prompt}\\n\"\n",+ ")\n",+ "print(Fore.RED + f\"Final task prompt:\\n{role_play_session.task_prompt}\\n\")"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "_xmNJtft4aZx",+ "outputId": "a0e591c3-daac-4ffc-e5d4-e9d412cc9c78"+ },+ "execution_count": 14,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "\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, and get the current weather of the city where the University is located.', '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, and get the current weather of the city where the University is located.. 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",+ "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, and get the current weather of the city where the University is located.', '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, and get the current weather of the city where the University is located.. 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",+ "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, and get the current weather of the city where the University is located.\n",+ "\n",+ "\u001b[36mSpecified task prompt:\n",+ "None\n",+ "\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, and get the current weather of the city where the University is located.\n",+ "\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "Set terminate rule and print the chat message"+ ],+ "metadata": {+ "id": "d5JjlXhs4cJT"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "n = 0\n",+ "input_msg = role_play_session.init_chat()\n",+ "while n < 50:\n",+ " n += 1\n",+ " assistant_response, user_response = role_play_session.step(input_msg)\n",+ "\n",+ " if assistant_response.terminated:\n",+ " print(\n",+ " Fore.GREEN\n",+ " + (\n",+ " \"AI Assistant terminated. Reason: \"\n",+ " f\"{assistant_response.info['termination_reasons']}.\"\n",+ " )\n",+ " )\n",+ " break\n",+ " if user_response.terminated:\n",+ " print(\n",+ " Fore.GREEN\n",+ " + (\n",+ " \"AI User terminated. \"\n",+ " f\"Reason: {user_response.info['termination_reasons']}.\"\n",+ " )\n",+ " )\n",+ " break\n",+ "\n",+ " # Print output from the user\n",+ " print_text_animated(\n",+ " Fore.BLUE + f\"AI User:\\n\\n{user_response.msg.content}\\n\"\n",+ " )\n",+ "\n",+ " # Print output from the assistant, including any function\n",+ " # execution information\n",+ " print_text_animated(Fore.GREEN + \"AI Assistant:\")\n",+ " tool_calls: List[FunctionCallingRecord] = assistant_response.info[\n",+ " 'tool_calls'\n",+ " ]\n",+ " for func_record in tool_calls:\n",+ " print_text_animated(f\"{func_record}\")\n",+ " print_text_animated(f\"{assistant_response.msg.content}\\n\")\n",+ "\n",+ " if \"CAMEL_TASK_DONE\" in user_response.msg.content:\n",+ " break\n",+ "\n",+ " input_msg = assistant_response.msg"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "z7bjGKlr4eVf",+ "outputId": "e8a96451-f7c8-49f8-9930-01796a7866e9"+ },+ "execution_count": 15,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "\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",+ "\n",+ "Solution: The University of Oxford is believed to have been founded in the 12th century, with the earliest evidence of teaching at Oxford dating back to around 1096. However, it is often cited that the university was officially established in 1209 when a group of scholars fled from the University of Cambridge due to disputes with the townspeople. \n",+ "\n",+ "For our estimation, we can consider the founding year to be approximately 1209.\n",+ "\n",+ "Next request.\n",+ "\n",+ "\n",+ "\u001b[34mAI User:\n",+ "\n",+ "Instruction: Calculate the current age of the University of Oxford as of 2024 based on the estimated founding year of 1209. \n",+ "Input: None\n",+ "\n",+ "\n",+ "\u001b[32mAI Assistant:\n",+ "\n",+ "Solution: To calculate the current age of the University of Oxford as of 2024, we subtract the estimated founding year (1209) from the current year (2024).\n",+ "\n",+ "Calculation:\n",+ "2024 - 1209 = 815\n",+ "\n",+ "Therefore, the current age of the University of Oxford in 2024 is approximately 815 years.\n",+ "\n",+ "Next request.\n",+ "\n",+ "\n",+ "\u001b[34mAI User:\n",+ "\n",+ "Instruction: Add 10 years to the current age of the University of Oxford. \n",+ "Input: None\n",+ "\n",+ "\n",+ "\u001b[32mAI Assistant:\n",+ "\n",+ "Solution: To add 10 years to the current age of the University of Oxford, which we calculated to be 815 years in 2024, we simply perform the addition:\n",+ "\n",+ "Calculation:\n",+ "815 + 10 = 825\n",+ "\n",+ "Thus, the age of the University of Oxford, after adding 10 years, will be approximately 825 years.\n",+ "\n",+ "Next request.\n",+ "\n",+ "\n",+ "\u001b[34mAI User:\n",+ "\n",+ "Instruction: Find the current weather in Oxford, England. \n",+ "Input: None\n",+ "\n",+ "\n",+ "\u001b[32mAI Assistant:\n",+ "\n",+ "Function Execution: search_google\n",+ "\tArgs: {'query': 'current weather in Oxford, England'}\n",+ "\tResult: [{'error': 'google search failed.'}]\n",+ "\n",+ "Solution: I attempted to retrieve the current weather in Oxford, England, but the search for this information was unsuccessful due to a failure in the Google search. \n",+ "\n",+ "As an alternative, I can try to search for the current weather using a different method or source. Would you like me to proceed with that? \n",+ "\n",+ "Next request.\n",+ "\n",+ "\n",+ "\u001b[34mAI User:\n",+ "\n",+ "Instruction: Please use an alternative method or source to find the current weather in Oxford, England. \n",+ "Input: None\n",+ "\n",+ "\n",+ "\u001b[32mAI Assistant:\n",+ "\n",+ "Function Execution: search_duckduckgo\n",+ "\tArgs: {'query': 'current weather in Oxford, England'}\n",+ "\tResult: [{'result_id': 1, 'title': 'Oxford (Oxfordshire) weather - Met Office', 'description': 'Oxford 7 day weather forecast including weather warnings, temperature, rain, wind, visibility, humidity and UV ... Use my current location . Recent places. ... A change in the broad weather pattern over the UK is expected towards mid-November and beyond, as high pressure initially over the nearby continent tends to become more focussed to the ...', 'url': 'https://www.metoffice.gov.uk/weather/forecast/gcpn7mp10'}, {'result_id': 2, 'title': 'Oxford, Oxfordshire, United Kingdom Weather Forecast | AccuWeather', 'description': 'Oxford, Oxfordshire, United Kingdom Weather Forecast, with current conditions, wind, air quality, and what to expect for the next 3 days.', 'url': 'https://www.accuweather.com/en/gb/oxford/ox1-3/weather-forecast/330217'}, {'result_id': 3, 'title': 'Oxford - BBC Weather', 'description': '14-day weather forecast for Oxford.', 'url': 'https://www.bbc.com/weather/2640729'}, {'result_id': 4, 'title': 'Oxford, Oxfordshire, United Kingdom Current Weather | AccuWeather', 'description': 'Current weather in Oxford, Oxfordshire, United Kingdom. Check current conditions in Oxford, Oxfordshire, United Kingdom with radar, hourly, and more.', 'url': 'https://www.accuweather.com/en/gb/oxford/ox1-3/current-weather/330217'}, {'result_id': 5, 'title': '10-day weather forecast for Oxford, England - The Weather Channel', 'description': 'Be prepared with the most accurate 10-day forecast for Oxford, England with highs, lows, chance of precipitation from The Weather Channel and Weather.com', 'url': 'https://weather.com/en-GB/weather/tenday/l/Oxford+England?canonicalCityId=0c16ff8887c1d01b06a4230a12f6f1f3e20275c65db637043a26a8cb26337644'}]\n",+ "\n",+ "Solution: I found several sources that provide the current weather in Oxford, England. Here are some options:\n",+ "\n",+ "1. **Met Office**: [Oxford Weather Forecast](https://www.metoffice.gov.uk/weather/forecast/gcpn7mp10) - This site provides a detailed 7-day weather forecast including temperature, rain, wind, and more.\n",+ "\n",+ "2. **AccuWeather**: [Current Weather in Oxford](https://www.accuweather.com/en/gb/oxford/ox1-3/current-weather/330217) - This page offers current conditions, wind, air quality, and a short-term forecast.\n",+ "\n",+ "3. **BBC Weather**: [Oxford Weather](https://www.bbc.com/weather/2640729) - This site provides a 14-day weather forecast for Oxford.\n",+ "\n",+ "4. **The Weather Channel**: [10-day Weather Forecast for Oxford](https://weather.com/en-GB/weather/tenday/l/Oxford+England?canonicalCityId=0c16ff8887c1d01b06a4230a12f6f1f3e20275c65db637043a26a8cb26337644) - This page includes a comprehensive 10-day forecast.\n",+ "\n",+ "You can visit any of these links to get the most current weather information for Oxford, England.\n",+ "\n",+ "Next request.\n",+ "\n",+ "\n",+ "\u001b[34mAI User:\n",+ "\n",+ "Instruction: Confirm the current weather in Oxford, England, using one of the provided sources. \n",+ "Input: None\n",+ "\n",+ "\n",+ "\u001b[32mAI Assistant:\n",+ "\n",+ "Function Execution: search_wiki\n",+ "\tArgs: {'entity': 'Oxford, England'}\n",+ "\tResult: Oxford ( ) is a cathedral city and non-metropolitan district in Oxfordshire, England, of which it is the county town. Founded in the 8th century, it was granted city status in 1542. The city is located at the confluence of the rivers Thames (locally known as the Isis) and Cherwell. It had a population of 163,257 in 2022. It is 56 miles (90 km) north-west of London, 64 miles (103 km) south-east of Birmingham and 61 miles (98 km) north-east of Bristol.\n",+ "\n",+ "Solution: I attempted to confirm the current weather in Oxford, England, using the Wikipedia source, but it does not provide real-time weather information. Instead, I recommend checking one of the previously mentioned sources for accurate and up-to-date weather conditions.\n",+ "\n",+ "For example, you can visit the [AccuWeather page for Oxford](https://www.accuweather.com/en/gb/oxford/ox1-3/current-weather/330217) to find the current weather details.\n",+ "\n",+ "Next request.\n",+ "\n",+ "\n",+ "\u001b[34mAI User:\n",+ "\n",+ "Instruction: Summarize the findings regarding the age of the University of Oxford and the current weather in Oxford, England. \n",+ "Input: None\n",+ "\n",+ "\n",+ "\u001b[32mAI Assistant:\n",+ "\n",+ "Solution: \n",+ "\n",+ "1. **Age of the University of Oxford**: \n",+ " - The University of Oxford is estimated to have been founded around the year 1209. \n",+ " - As of 2024, this makes the university approximately 815 years old. \n",+ " - After adding 10 years, the age of the University of Oxford will be approximately 825 years.\n",+ "\n",+ "2. **Current Weather in Oxford, England**: \n",+ " - I attempted to retrieve the current weather information but faced challenges with the search. \n",+ " - However, I provided several reliable sources where the current weather can be checked, including:\n",+ " - [Met Office](https://www.metoffice.gov.uk/weather/forecast/gcpn7mp10)\n",+ " - [AccuWeather](https://www.accuweather.com/en/gb/oxford/ox1-3/current-weather/330217)\n",+ " - [BBC Weather](https://www.bbc.com/weather/2640729)\n",+ " - [The Weather Channel](https://weather.com/en-GB/weather/tenday/l/Oxford+England?canonicalCityId=0c16ff8887c1d01b06a4230a12f6f1f3e20275c65db637043a26a8cb26337644)\n",+ "\n",+ "These sources can provide the most accurate and current weather conditions for Oxford, England.\n",+ "\n",+ "Next request.\n",+ "\n",+ "\n",+ "\u001b[34mAI User:\n",+ "\n",+ "<CAMEL_TASK_DONE>\n",+ "\n",+ "\n",+ "\u001b[32mAI Assistant:\n",+ "\n",+ "Solution: The task is now marked as completed. If you have any further inquiries or need assistance with another task in the future, feel free to reach out.\n",+ "\n",+ "Next request.\n",+ "\n",+ "\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "End the AgentOps session"+ ],+ "metadata": {+ "id": "pYZAD7-H4hhQ"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "agentops.end_session(\"Success\")"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "c8YKJgu94k35",+ "outputId": "6b8a2de9-e3fb-45bd-f916-febc12d14d8b"+ },+ "execution_count": 16,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stderr",+ "text": [+ "๐ AgentOps: This run's cost $0.004198\n",+ "๐ AgentOps: \u001b[34m\u001b[34mSession Replay: https://app.agentops.ai/drilldown?session_id=6c46dfa1-662b-40e1-8343-b40934c5659c\u001b[0m\u001b[0m\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "### ๐ Go to the AgentOps link shown above, you will be able to see the detailed record for the multi-agent running like below."+ ],+ "metadata": {+ "id": "kf1i_sXw2LZ7"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ ""+ ],+ "metadata": {+ "id": "Q2wNxipj13fa"+ }}- ],- "source": [- "agentops.end_session(\"Success\")"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "kf1i_sXw2LZ7"- },- "source": [- "### ๐ Go to the AgentOps link shown above, you will be able to see the detailed record for the multi-agent running like below."- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "Q2wNxipj13fa"- },- "source": [- ""- ]- }- ],- "metadata": {- "colab": {- "provenance": []- },- "kernelspec": {- "display_name": "Python 3",- "name": "python3"- },- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 0-}+ ]+}\ No newline at end of filediff --git a/docs/cookbooks/agents_with_memory.ipynb b/docs/cookbooks/agents_with_memory.ipynbindex 7251c0201..6841585d9 100644--- a/docs/cookbooks/agents_with_memory.ipynb+++ b/docs/cookbooks/agents_with_memory.ipynb@@ -1,456 +1,440 @@{- "cells": [- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "w5_pa5kKPzAE"- },- "source": [- "# Memory Cookbook"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "zgqKzSB-PXzi"- },- "source": [- "You can also check this cookbook in colab [here](https://colab.research.google.com/drive/1ixGItEqQGkp09_TuV_8SGmz65WHBr5r5?usp=sharing)"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "lSXa_rQQQzBd"- },- "source": [- "## Overview"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "OnmoAw2vQG8I"- },- "source": [- "The Memory module in CAMEL provides a flexible and powerful system for storing, retrieving, and managing information for AI agents. It enables agents to maintain context across conversations and retrieve relevant information from past interactions, enhancing the coherence and relevance of AI responses."- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "l4MP9uUNQ2kr"- },- "source": [- "## Getting Started\n"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "kETDiaP2Rrdb"- },- "source": [- "### Installation"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "Cg96MkbcRtQR"- },- "source": [- "Ensure you have CAMEL AI installed in your Python environment:"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "collapsed": true,- "id": "ZVmDAK6MPefC"- },- "outputs": [],- "source": [- "%pip install \"camel-ai[all]==0.2.1\""- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "MyTTCe3IR_Lr"- },- "source": [- "### ๐ Setting Up API Keys"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "REqzgGL9SEaD"- },- "source": [- "You'll need to set up your API keys for OpenAI."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {+ "nbformat": 4,+ "nbformat_minor": 0,+ "metadata": {"colab": {- "base_uri": "https://localhost:8080/"+ "provenance": []},- "id": "PNBFEXc-R-0s",- "outputId": "52d481de-9a81-4c00-e3db-9c468e6b5b22"- },- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "Enter your API key: ยทยทยทยทยทยทยทยทยทยท\n"- ]+ "kernelspec": {+ "name": "python3",+ "display_name": "Python 3"+ },+ "language_info": {+ "name": "python"}- ],- "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"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "LRojeqp7dP1m"- },- "source": [- "## Usage"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "_sJV9GFldTBh"- },- "source": [- "To use the Memory module in your agent:\n",- "\n",- "1. Choose an appropriate AgentMemory implementation (`ChatHistoryMemory`, `VectorDBMemory`, or `LongtermAgentMemory`).\n",- "2. Initialize the memory with a context creator and any necessary parameters.\n",- "3. Use `write_records()` to add new information to the memory.\n",- "4. Use `retrieve()` to get relevant context for the agent's next action.\n",- "5. Use `get_context()` to obtain the formatted context for the agent."- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "aiypnpqJoZ4G"- },- "source": [- "### Setting `LongtermAgentMemory`:"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "C2kVCRA7dD4A"- },- "source": [- "Import required modules"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "id": "UOKw2hCSdCXm"- },- "outputs": [],- "source": [- "from camel.memories import (\n",- " ChatHistoryBlock,\n",- " LongtermAgentMemory,\n",- " MemoryRecord,\n",- " ScoreBasedContextCreator,\n",- " VectorDBBlock,\n",- ")\n",- "from camel.messages import BaseMessage\n",- "from camel.types import ModelType, OpenAIBackendRole\n",- "from camel.utils import OpenAITokenCounter"- ]},- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"+ "cells": [+ {+ "cell_type": "markdown",+ "source": [+ "# ๐ซ CAMEL Memory Cookbook"+ ],+ "metadata": {+ "id": "w5_pa5kKPzAE"+ }},- "id": "pAdDeN7DdUgr",- "outputId": "0575acdb-a999-4818-f90c-de1e9b35890c"- },- "outputs": [{- "name": "stdout",- "output_type": "stream",- "text": [- "[{'role': 'user', 'content': 'What is CAMEL AI?'}, {'role': 'assistant', 'content': 'CAMEL-AI.org is the 1st LLM multi-agent framework and an open-source community dedicated to finding the scaling law of agents.'}]\n"- ]- }- ],- "source": [- "# Initialize the memory\n",- "memory = LongtermAgentMemory(\n",- " context_creator=ScoreBasedContextCreator(\n",- " token_counter=OpenAITokenCounter(ModelType.GPT_4O_MINI),\n",- " token_limit=1024,\n",- " ),\n",- " chat_history_block=ChatHistoryBlock(),\n",- " vector_db_block=VectorDBBlock(),\n",- ")\n",- "\n",- "# Create and write new records\n",- "records = [\n",- " MemoryRecord(\n",- " message=BaseMessage.make_user_message(\n",- " role_name=\"User\",\n",- " meta_dict=None,\n",- " content=\"What is CAMEL AI?\",\n",- " ),\n",- " role_at_backend=OpenAIBackendRole.USER,\n",- " ),\n",- " MemoryRecord(\n",- " message=BaseMessage.make_assistant_message(\n",- " role_name=\"Agent\",\n",- " meta_dict=None,\n",- " content=\"CAMEL-AI.org is the 1st LLM multi-agent framework and \"\n",- " \"an open-source community dedicated to finding the scaling law \"\n",- " \"of agents.\",\n",- " ),\n",- " role_at_backend=OpenAIBackendRole.ASSISTANT,\n",- " ),\n",- "]\n",- "memory.write_records(records)\n",- "\n",- "# Get context for the agent\n",- "context, token_count = memory.get_context()\n",- "\n",- "print(context)"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"+ "cell_type": "markdown",+ "source": [+ "You can also check this cookbook in colab [here](https://colab.research.google.com/drive/1ixGItEqQGkp09_TuV_8SGmz65WHBr5r5?usp=sharing)"+ ],+ "metadata": {+ "id": "zgqKzSB-PXzi"+ }},- "id": "pEiFYV-yez5j",- "outputId": "2340282b-1024-49de-be67-2f9ed34ee18c"- },- "outputs": [{- "name": "stdout",- "output_type": "stream",- "text": [- "49\n"- ]- }- ],- "source": [- "print(token_count)"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "K-P9rD6Foe5j"- },- "source": [- "### Adding `LongtermAgentMemory` to your `ChatAgent`:"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"+ "cell_type": "markdown",+ "source": [+ "## Overview"+ ],+ "metadata": {+ "id": "lSXa_rQQQzBd"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "The Memory module in CAMEL provides a flexible and powerful system for storing, retrieving, and managing information for AI agents. It enables agents to maintain context across conversations and retrieve relevant information from past interactions, enhancing the coherence and relevance of AI responses."+ ],+ "metadata": {+ "id": "OnmoAw2vQG8I"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "## Getting Started\n"+ ],+ "metadata": {+ "id": "l4MP9uUNQ2kr"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "### Installation"+ ],+ "metadata": {+ "id": "kETDiaP2Rrdb"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "Ensure you have CAMEL AI installed in your Python environment:"+ ],+ "metadata": {+ "id": "Cg96MkbcRtQR"+ }+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {+ "collapsed": true,+ "id": "ZVmDAK6MPefC"+ },+ "outputs": [],+ "source": [+ "!pip install \"camel-ai[all]==0.2.4\""+ ]+ },+ {+ "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": "50989fca-73bf-4062-cc1f-124bd6abadc1"+ },+ "execution_count": 2,+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Enter your API key: ยทยทยทยทยทยทยทยทยทยท\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "## Usage"+ ],+ "metadata": {+ "id": "LRojeqp7dP1m"+ }},- "id": "Mp-KXFdGpKZt",- "outputId": "e0e6c8b2-142e-4a3a-d34d-2feafebac137"- },- "outputs": [{- "name": "stdout",- "output_type": "stream",- "text": [- "CAMEL AI is recognized as the first LLM (Large Language Model) multi-agent framework. It is an open-source community initiative focused on exploring the scaling laws of agents, enabling the development and interaction of multiple AI agents in a collaborative environment. This framework allows researchers and developers to experiment with various configurations and interactions among agents, facilitating advancements in AI capabilities and understanding.\n"- ]+ "cell_type": "markdown",+ "source": [+ "To use the Memory module in your agent:\n",+ "\n",+ "1. Choose an appropriate AgentMemory implementation (`ChatHistoryMemory`, `VectorDBMemory`, or `LongtermAgentMemory`).\n",+ "2. Initialize the memory with a context creator and any necessary parameters.\n",+ "3. Use `write_records()` to add new information to the memory.\n",+ "4. Use `retrieve()` to get relevant context for the agent's next action.\n",+ "5. Use `get_context()` to obtain the formatted context for the agent."+ ],+ "metadata": {+ "id": "_sJV9GFldTBh"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "### Setting `LongtermAgentMemory`:"+ ],+ "metadata": {+ "id": "aiypnpqJoZ4G"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "Import required modules"+ ],+ "metadata": {+ "id": "C2kVCRA7dD4A"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "from camel.memories import (\n",+ " ChatHistoryBlock,\n",+ " LongtermAgentMemory,\n",+ " MemoryRecord,\n",+ " ScoreBasedContextCreator,\n",+ " VectorDBBlock,\n",+ ")\n",+ "from camel.messages import BaseMessage\n",+ "from camel.types import ModelType, OpenAIBackendRole\n",+ "from camel.utils import OpenAITokenCounter"+ ],+ "metadata": {+ "id": "UOKw2hCSdCXm"+ },+ "execution_count": 3,+ "outputs": []+ },+ {+ "cell_type": "code",+ "source": [+ "# Initialize the memory\n",+ "memory = LongtermAgentMemory(\n",+ " context_creator=ScoreBasedContextCreator(\n",+ " token_counter=OpenAITokenCounter(ModelType.GPT_4O_MINI),\n",+ " token_limit=1024,\n",+ " ),\n",+ " chat_history_block=ChatHistoryBlock(),\n",+ " vector_db_block=VectorDBBlock(),\n",+ ")\n",+ "\n",+ "# Create and write new records\n",+ "records = [\n",+ " MemoryRecord(\n",+ " message=BaseMessage.make_user_message(\n",+ " role_name=\"User\",\n",+ " content=\"What is CAMEL AI?\",\n",+ " ),\n",+ " role_at_backend=OpenAIBackendRole.USER,\n",+ " ),\n",+ " MemoryRecord(\n",+ " message=BaseMessage.make_assistant_message(\n",+ " role_name=\"Agent\",\n",+ " content=\"CAMEL-AI.org is the 1st LLM multi-agent framework and \"\n",+ " \"an open-source community dedicated to finding the scaling law \"\n",+ " \"of agents.\",\n",+ " ),\n",+ " role_at_backend=OpenAIBackendRole.ASSISTANT,\n",+ " ),\n",+ "]\n",+ "memory.write_records(records)\n",+ "\n",+ "# Get context for the agent\n",+ "context, token_count = memory.get_context()\n",+ "\n",+ "print(context)"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "pAdDeN7DdUgr",+ "outputId": "75a8c69d-8e2b-4af5-e7a7-c4205718ee10"+ },+ "execution_count": 4,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "[{'role': 'user', 'content': 'What is CAMEL AI?'}, {'role': 'assistant', 'content': 'CAMEL-AI.org is the 1st LLM multi-agent framework and an open-source community dedicated to finding the scaling law of agents.'}]\n"+ ]+ }+ ]+ },+ {+ "cell_type": "code",+ "source": [+ "print(token_count)"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "pEiFYV-yez5j",+ "outputId": "c72b113f-5f75-4a7e-8f23-379c954da66e"+ },+ "execution_count": 5,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "49\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "### Adding `LongtermAgentMemory` to your `ChatAgent`:"+ ],+ "metadata": {+ "id": "K-P9rD6Foe5j"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "from camel.agents import ChatAgent\n",+ "\n",+ "# Define system message for the agent\n",+ "sys_msg = \"You are a curious agent wondering about the universe.\"\n",+ "\n",+ "# Initialize agent\n",+ "agent = ChatAgent(system_message=sys_msg)\n",+ "\n",+ "# Set memory to the agent\n",+ "agent.memory = memory\n",+ "\n",+ "\n",+ "# Define a user message\n",+ "usr_msg = \"Tell me which is the 1st LLM multi-agent framework based on what we have discussed\"\n",+ "\n",+ "# Sending the message to the agent\n",+ "response = agent.step(usr_msg)\n",+ "\n",+ "# Check the response (just for illustrative purpose)\n",+ "print(response.msgs[0].content)"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "Mp-KXFdGpKZt",+ "outputId": "08ca25ef-2d14-4554-bcce-f031ef3dd740"+ },+ "execution_count": 6,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "CAMEL AI is recognized as the first LLM (Large Language Model) multi-agent framework. It is an open-source community initiative aimed at exploring and understanding the scaling laws of agents. The framework facilitates the development and deployment of multiple agents that can interact and collaborate, leveraging the capabilities of LLMs to enhance their performance and functionality.\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "## Advanced Topics"+ ],+ "metadata": {+ "id": "w0ndTJske1mb"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "### Customizing Context Creator"+ ],+ "metadata": {+ "id": "9q8EXq2ge6Dq"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "You can create custom context creators by subclassing `BaseContextCreator`:"+ ],+ "metadata": {+ "id": "zUjztraTe7aw"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "from camel.memories import BaseContextCreator\n",+ "\n",+ "class MyCustomContextCreator(BaseContextCreator):\n",+ " @property\n",+ " def token_counter(self):\n",+ " # Implement your token counting logic\n",+ " return\n",+ "\n",+ " @property\n",+ " def token_limit(self):\n",+ " return 1000 # Or any other limit\n",+ "\n",+ " def create_context(self, records):\n",+ " # Implement your context creation logic\n",+ " pass"+ ],+ "metadata": {+ "id": "LX4fyovCe89R"+ },+ "execution_count": 7,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "### Customizing Vector Database Block"+ ],+ "metadata": {+ "id": "N_HM5wyFfEtO"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "For `VectorDBBlock`, you can customize it by adjusting the embedding models or vector storages:"+ ],+ "metadata": {+ "id": "CxcjHzArfFYZ"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "from camel.embeddings import OpenAIEmbedding\n",+ "from camel.memories import VectorDBBlock\n",+ "from camel.storages import QdrantStorage\n",+ "\n",+ "vector_db = VectorDBBlock(\n",+ " embedding=OpenAIEmbedding(),\n",+ " storage=QdrantStorage(vector_dim=OpenAIEmbedding().get_output_dim()),\n",+ ")"+ ],+ "metadata": {+ "id": "iQlxwVM7fJEp"+ },+ "execution_count": 8,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "### Performance Considerations"+ ],+ "metadata": {+ "id": "u_pkVP5Eg2vv"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "- For large-scale applications, consider using persistent storage backends instead of in-memory storage.\n",+ "- Optimize your context creator to balance between context relevance and token limits.\n",+ "- When using `VectorDBMemory`, be mindful of the trade-off between retrieval accuracy and speed as the database grows."+ ],+ "metadata": {+ "id": "_4C93qAng3SP"+ }}- ],- "source": [- "from camel.agents import ChatAgent\n",- "\n",- "# Define system message for the agent\n",- "sys_msg = BaseMessage.make_assistant_message(\n",- " role_name='Agent',\n",- " content='You are a curious agent wondering about the universe.',\n",- ")\n",- "\n",- "# Initialize agent\n",- "agent = ChatAgent(system_message=sys_msg)\n",- "\n",- "# Set memory to the agent\n",- "agent.memory = memory\n",- "\n",- "\n",- "# Define a user message\n",- "usr_msg = BaseMessage.make_user_message(\n",- " role_name='User',\n",- " content=\"Tell me which is the 1st LLM multi-agent framework based on what we have discussed\",\n",- ")\n",- "\n",- "# Sending the message to the agent\n",- "response = agent.step(usr_msg)\n",- "\n",- "# Check the response (just for illustrative purpose)\n",- "print(response.msgs[0].content)"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "5cuumB_bo46c"- },- "source": []- },- {- "cell_type": "markdown",- "metadata": {- "id": "w0ndTJske1mb"- },- "source": [- "## Advanced Topics"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "9q8EXq2ge6Dq"- },- "source": [- "### Customizing Context Creator"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "zUjztraTe7aw"- },- "source": [- "You can create custom context creators by subclassing `BaseContextCreator`:"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "id": "LX4fyovCe89R"- },- "outputs": [],- "source": [- "from camel.memories import BaseContextCreator\n",- "\n",- "class MyCustomContextCreator(BaseContextCreator):\n",- " @property\n",- " def token_counter(self):\n",- " # Implement your token counting logic\n",- " return\n",- "\n",- " @property\n",- " def token_limit(self):\n",- " return 1000 # Or any other limit\n",- "\n",- " def create_context(self, records):\n",- " # Implement your context creation logic\n",- " pass"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "N_HM5wyFfEtO"- },- "source": [- "### Customizing Vector Database Block"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "CxcjHzArfFYZ"- },- "source": [- "For `VectorDBBlock`, you can customize it by adjusting the embedding models or vector storages:"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "id": "iQlxwVM7fJEp"- },- "outputs": [],- "source": [- "from camel.embeddings import OpenAIEmbedding\n",- "from camel.memories import VectorDBBlock\n",- "from camel.storages import QdrantStorage\n",- "\n",- "vector_db = VectorDBBlock(\n",- " embedding=OpenAIEmbedding(),\n",- " storage=QdrantStorage(vector_dim=OpenAIEmbedding().get_output_dim()),\n",- ")"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "u_pkVP5Eg2vv"- },- "source": [- "### Performance Considerations"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "_4C93qAng3SP"- },- "source": [- "- For large-scale applications, consider using persistent storage backends instead of in-memory storage.\n",- "- Optimize your context creator to balance between context relevance and token limits.\n",- "- When using `VectorDBMemory`, be mindful of the trade-off between retrieval accuracy and speed as the database grows."- ]- }- ],- "metadata": {- "colab": {- "provenance": []- },- "kernelspec": {- "display_name": "Python 3",- "name": "python3"- },- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 0-}+ ]+}\ No newline at end of filediff --git a/docs/cookbooks/agents_with_rag.ipynb b/docs/cookbooks/agents_with_rag.ipynbindex b22eb5f9f..01a2d0070 100644--- a/docs/cookbooks/agents_with_rag.ipynb+++ b/docs/cookbooks/agents_with_rag.ipynb@@ -1,855 +1,732 @@{- "cells": [- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "SQMBlxsBv1cH"- },- "source": [- "# RAG Cookbook\n"- ]- },- {- "cell_type": "markdown",- "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",- "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",- "4 main parts included:\n",- "- Customized RAG\n",- "- Auto RAG\n",- "- Single Agent with Auto RAG\n",- "- Role-playing with Auto RAG"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "XuZwbB1IIuUi"- },- "source": [- "### Installation"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "gIJK4Lu5Iwm0"- },- "source": [- "Ensure you have CAMEL AI installed in your Python environment:"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "collapsed": true,- "id": "HTKnWg9Xv_y4"- },- "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"- ]- },- {- "cell_type": "code",- "execution_count": 2,- "metadata": {- "id": "dUVE7z9hwEV7"- },- "outputs": [],- "source": [- "import os\n",- "import requests\n",- "\n",- "os.makedirs('local_data', exist_ok=True)\n",- "\n",- "url = \"https://arxiv.org/pdf/2303.17760.pdf\"\n",- "response = requests.get(url)\n",- "with open('local_data/camel_paper.pdf', 'wb') as file:\n",- " file.write(response.content)"- ]- },- {- "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."- ]- },- {- "cell_type": "code",- "execution_count": 3,- "metadata": {+ "nbformat": 4,+ "nbformat_minor": 0,+ "metadata": {"colab": {- "base_uri": "https://localhost:8080/"+ "provenance": []},- "id": "RxG99FkYwm_p",- "outputId": "fc85f6d4-ea08-4d30-b198-3a4573868673"- },- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "Enter your API key: ยทยทยทยทยทยทยทยทยทยท\n"- ]+ "kernelspec": {+ "name": "python3",+ "display_name": "Python 3"+ },+ "language_info": {+ "name": "python"}- ],- "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",- "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)"- ]- },- {- "cell_type": "markdown",- "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",- "storage_instance = QdrantStorage(\n",- " vector_dim=embedding_instance.get_output_dim(),\n",- " path=\"local_data\",\n",- " collection_name=\"camel_paper\",\n",- ")"- ]- },- {- "cell_type": "markdown",- "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)"- ]- },- {- "cell_type": "markdown",- "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",- "execution_count": null,- "metadata": {- "id": "QTFvD3_SHv3m"- },- "outputs": [],- "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",- "\n",- "The returned dictionary list includes:\n",- "- similarity score\n",- "- content path\n",- "- metadata\n",- "- text"- ]- },- {- "cell_type": "code",- "execution_count": 8,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"+ "cells": [+ {+ "cell_type": "markdown",+ "source": [+ "# ๐ซ CAMEL RAG Cookbook\n"+ ],+ "metadata": {+ "id": "SQMBlxsBv1cH"+ }},- "id": "uDu43Hb3GVrs",- "outputId": "035fedf9-e469-4e32-990b-f360c2cdcb96"- },- "outputs": [{- "name": "stdout",- "output_type": "stream",- "text": [- "[{'similarity score': '0.8733044970215764', 'content path': 'local_data/camel_paper.pdf', 'metadata': {'last_modified': '2024-09-28T03:37:11', '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",- "metadata": {- "id": "48G3USMzH6Hd"- },- "source": [- "Let's try an irrelevant query:"- ]- },- {- "cell_type": "code",- "execution_count": 9,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"+ "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"+ }},- "id": "UNh3tjCOH7d0",- "outputId": "05f4196a-c9dd-4ddd-d970-beec129086d6"- },- "outputs": [{- "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",- "\n",- "What you need to do is:\n",- "- Set content input paths, which can be local paths or remote urls\n",- "- Set remote url and api key for Milvus\n",- "- 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."- ]- },- {- "cell_type": "code",- "execution_count": 10,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"+ "cell_type": "markdown",+ "source": [+ "## Overview"+ ],+ "metadata": {+ "id": "-nCRZU5sInDK"+ }},- "id": "D_-zAOJ7GjVm",- "outputId": "8da4f3ef-3bb4-47e0-a994-d9c0fb87dfb7"- },- "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.7054343316726102', '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",- "\n",- "auto_retriever = AutoRetriever(\n",- " vector_storage_local_path=\"local_data2/\",\n",- " storage_type=StorageType.QDRANT,\n",- " embedding_model=embedding_instance)\n",- "\n",- "retrieved_info = auto_retriever.run_vector_retriever(\n",- " query=\"If I'm interest in contributing to the CAMEL projec, what should I do?\",\n",- " contents=[\n",- " \"local_data/camel_paper.pdf\", # example local path\n",- " \"https://github.com/camel-ai/camel/wiki/Contributing-Guidlines\", # example remote url\n",- " ],\n",- " top_k=1,\n",- " return_detailed_info=True,\n",- " similarity_threshold=0.5\n",- ")\n",- "\n",- "print(retrieved_info)"- ]- },- {- "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."- ]- },- {- "cell_type": "code",- "execution_count": 11,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"+ "cell_type": "markdown",+ "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",+ "4 main parts included:\n",+ "- Customized RAG\n",+ "\n",+ "- Auto RAG\n",+ "\n",+ "- Single Agent with Auto RAG\n",+ "\n",+ "- Role-playing with Auto RAG"+ ],+ "metadata": {+ "id": "AwnfLQvMvtXo"+ }},- "id": "YTE_mUwGIok-",- "outputId": "0b2b53eb-eb4c-4bc5-feda-981f027b1e6e"- },- "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, address 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 and collaboration.\n"- ]- }- ],- "source": [- "from camel.agents import ChatAgent\n",- "from camel.messages import BaseMessage\n",- "from camel.types import RoleType\n",- "from camel.retrievers import AutoRetriever\n",- "from camel.types import StorageType\n",- "\n",- "def single_agent(query: str) ->str :\n",- " # Set agent role\n",- " assistant_sys_msg = BaseMessage(\n",- " role_name=\"Assistant\",\n",- " role_type=RoleType.ASSISTANT,\n",- " meta_dict=None,\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",- " if you can't answer the question just say I don't know.\"\"\",\n",- " )\n",- "\n",- " # Add auto retriever\n",- " auto_retriever = AutoRetriever(\n",- " vector_storage_local_path=\"local_data2/\",\n",- " storage_type=StorageType.QDRANT,\n",- " embedding_model=embedding_instance)\n",- "\n",- " retrieved_info = auto_retriever.run_vector_retriever(\n",- " query=query,\n",- " contents=[\n",- " \"local_data/camel_paper.pdf\", # example local path\n",- " \"https://github.com/camel-ai/camel/wiki/Contributing-Guidlines\", # example remote url\n",- " ],\n",- " top_k=1,\n",- " return_detailed_info=False,\n",- " similarity_threshold=0.5\n",- " )\n",- "\n",- " # Pass the retrieved infomation to agent\n",- " user_msg = BaseMessage.make_user_message(role_name=\"User\", content=str(retrieved_info))\n",- " agent = ChatAgent(assistant_sys_msg)\n",- "\n",- " # Get response\n",- " assistant_response = agent.step(user_msg)\n",- " return assistant_response.msg.content\n",- "\n",- "print(single_agent(\"If I'm interest in contributing to the CAMEL projec, what should I do?\"))"- ]- },- {- "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"- ]- },- {- "cell_type": "code",- "execution_count": 19,- "metadata": {- "id": "z3tX4EJVI1hb"- },- "outputs": [],- "source": [- "from typing import List\n",- "from colorama import Fore\n",- "\n",- "from camel.agents.chat_agent import FunctionCallingRecord\n",- "from camel.configs import ChatGPTConfig\n",- "from camel.toolkits import (\n",- " MathToolkit,\n",- " RetrievalToolkit,\n",- ")\n",- "from camel.societies import RolePlaying\n",- "from camel.types import ModelType, ModelPlatformType\n",- "from camel.utils import print_text_animated\n",- "from camel.models import ModelFactory\n",- "\n",- "def role_playing_with_rag(\n",- " task_prompt,\n",- " model_platform=ModelPlatformType.OPENAI,\n",- " model_type=ModelType.GPT_4O,\n",- " chat_turn_limit=5,\n",- ") -> None:\n",- " task_prompt = task_prompt\n",- "\n",- " user_model_config = ChatGPTConfig(temperature=0.0)\n",- "\n",- " tools_list = [\n",- " *MathToolkit().get_tools(),\n",- " *RetrievalToolkit().get_tools(),\n",- " ]\n",- " assistant_model_config = ChatGPTConfig(\n",- " tools=tools_list,\n",- " temperature=0.0,\n",- " )\n",- "\n",- " role_play_session = RolePlaying(\n",- " assistant_role_name=\"Searcher\",\n",- " user_role_name=\"Professor\",\n",- " assistant_agent_kwargs=dict(\n",- " model=ModelFactory.create(\n",- " model_platform=model_platform,\n",- " model_type=model_type,\n",- " model_config_dict=assistant_model_config.as_dict(),\n",- " ),\n",- " tools=tools_list,\n",- " ),\n",- " user_agent_kwargs=dict(\n",- " model=ModelFactory.create(\n",- " model_platform=model_platform,\n",- " model_type=model_type,\n",- " model_config_dict=user_model_config.as_dict(),\n",- " ),\n",- " ),\n",- " task_prompt=task_prompt,\n",- " with_task_specify=False,\n",- " )\n",- "\n",- " print(\n",- " Fore.GREEN\n",- " + f\"AI Assistant sys message:\\n{role_play_session.assistant_sys_msg}\\n\"\n",- " )\n",- " print(\n",- " Fore.BLUE + f\"AI User sys message:\\n{role_play_session.user_sys_msg}\\n\"\n",- " )\n",- "\n",- " print(Fore.YELLOW + f\"Original task prompt:\\n{task_prompt}\\n\")\n",- " print(\n",- " Fore.CYAN\n",- " + \"Specified task prompt:\"\n",- " + f\"\\n{role_play_session.specified_task_prompt}\\n\"\n",- " )\n",- " print(Fore.RED + f\"Final task prompt:\\n{role_play_session.task_prompt}\\n\")\n",- "\n",- " n = 0\n",- " input_msg = role_play_session.init_chat()\n",- " while n < chat_turn_limit:\n",- " n += 1\n",- " assistant_response, user_response = role_play_session.step(input_msg)\n",- "\n",- " if assistant_response.terminated:\n",- " print(\n",- " Fore.GREEN\n",- " + (\n",- " \"AI Assistant terminated. Reason: \"\n",- " f\"{assistant_response.info['termination_reasons']}.\"\n",- " )\n",- " )\n",- " break\n",- " if user_response.terminated:\n",- " print(\n",- " Fore.GREEN\n",- " + (\n",- " \"AI User terminated. \"\n",- " f\"Reason: {user_response.info['termination_reasons']}.\"\n",- " )\n",- " )\n",- " break\n",- "\n",- " # Print output from the user\n",- " print_text_animated(\n",- " Fore.BLUE + f\"AI User:\\n\\n{user_response.msg.content}\\n\"\n",- " )\n",- "\n",- " # Print output from the assistant, including any function\n",- " # execution information\n",- " print_text_animated(Fore.GREEN + \"AI Assistant:\")\n",- " tool_calls: List[FunctionCallingRecord] = [\n",- " FunctionCallingRecord(**call.as_dict())\n",- " for call in assistant_response.info['tool_calls']\n",- " ]\n",- " for func_record in tool_calls:\n",- " print_text_animated(f\"{func_record}\")\n",- " print_text_animated(f\"{assistant_response.msg.content}\\n\")\n",- "\n",- " if \"CAMEL_TASK_DONE\" in user_response.msg.content:\n",- " break\n",- "\n",- " input_msg = assistant_response.msg"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "w4-0lswwI5Gb"- },- "source": [- "Run the role-playing with defined retriever function:"- ]- },- {- "cell_type": "code",- "execution_count": 22,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"+ "cell_type": "markdown",+ "source": [+ "### Installation"+ ],+ "metadata": {+ "id": "XuZwbB1IIuUi"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "Ensure you have CAMEL AI installed in your Python environment:"+ ],+ "metadata": {+ "id": "gIJK4Lu5Iwm0"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "!pip install \"camel-ai[all]==0.2.4\""+ ],+ "metadata": {+ "id": "HTKnWg9Xv_y4",+ "collapsed": true+ },+ "execution_count": null,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "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"+ }},- "id": "5agjiXHeI64q",- "outputId": "8f6c53cb-411e-440f-95bb-7a45f07c6d96"- },- "outputs": [{- "name": "stdout",- "output_type": "stream",- "text": [- "\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 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, don't generate the answer by yourself, 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 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, don't generate the answer by yourself, 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",- "BaseMessage(role_name='Professor', role_type=<RoleType.USER: 'user'>, meta_dict={'task': \"If I'm interest in contributing to the 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, don't generate the answer by yourself, 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 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, don\\'t generate the answer by yourself, 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",- "If I'm interest in contributing to the 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, don't generate the answer by yourself, adjust the similarity threshold to lower value is necessary\n",- "\n",- "\u001B[36mSpecified task prompt:\n",- "None\n",- "\n",- "\u001B[31mFinal task prompt:\n",- "If I'm interest in contributing to the 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, don't generate the answer by yourself, adjust the similarity threshold to lower value is necessary\n",- "\n",- "\u001B[34mAI User:\n",- "\n",- "Instruction: Visit the URL provided to access the CAMEL project's contributing guidelines.\n",- "Input: https://github.com/camel-ai/camel/wiki/Contributing-Guidlines\n",- "\n",- "\n",- "\u001B[32mAI Assistant:\n",- "\n",- "Function Execution: information_retrieval\n",- "\tArgs: {'query': 'contributing guidelines for CAMEL project', 'contents': 'https://github.com/camel-ai/camel/wiki/Contributing-Guidlines'}\n",- "\tResult: {'Original Query': 'contributing guidelines for CAMEL project', 'Retrieved Context': ['No suitable information retrieved from https://github.com/camel-ai/camel/wiki/Contributing-Guidlines with similarity_threshold = 0.7.']}\n",- "\n",- "Solution: It appears that no suitable information was retrieved from the provided URL with the current similarity threshold. I will adjust the similarity threshold to a lower value to attempt to retrieve the relevant information.\n",- "\n",- "Next request.\n",- "\n",- "\n",- "\u001B[34mAI User:\n",- "\n",- "Instruction: Adjust the similarity threshold to a lower value and attempt to retrieve the relevant information from the provided URL again.\n",- "Input: https://github.com/camel-ai/camel/wiki/Contributing-Guidlines\n",- "\n",- "\n",- "\u001B[32mAI Assistant:\n",- "\n",- "Function Execution: information_retrieval\n",- "\tArgs: {'query': 'contributing guidelines for CAMEL project', 'contents': 'https://github.com/camel-ai/camel/wiki/Contributing-Guidlines', 'similarity_threshold': 0.5}\n",- "\tResult: {'Original Query': 'contributing guidelines for CAMEL project', 'Retrieved Context': [\"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",- "\n",- "Solution: Here is the relevant information retrieved from the provided URL:\n",- "\n",- "\"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, ask 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",- "\n",- "This indicates that the CAMEL project is open to various types of contributions, including new features, infrastructure enhancements, documentation improvements, issue reporting, adding examples, implementing research ideas, and bug fixes. Additionally, it suggests joining their Slack for further engagement.\n",- "\n",- "Next request.\n",- "\n",- "\n",- "\u001B[34mAI User:\n",- "\n",- "Instruction: Look for specific instructions or steps provided in the contributing guidelines for setting up the development environment or resolving setup challenges.\n",- "Input: https://github.com/camel-ai/camel/wiki/Contributing-Guidlines\n",- "\n",- "\n",- "\u001B[32mAI Assistant:\n",- "\n",- "Function Execution: information_retrieval\n",- "\tArgs: {'query': 'setup development environment or resolving setup challenges for CAMEL project', 'contents': 'https://github.com/camel-ai/camel/wiki/Contributing-Guidlines', 'similarity_threshold': 0.5}\n",- "\tResult: {'Original Query': 'setup development environment or resolving setup challenges for CAMEL project', 'Retrieved Context': ['Quick Start ๐\\n\\nTo get started with CAMEL, follow these steps:\\n\\n# Clone github repo\\ngit clone https://github.com/camel-ai/camel.git\\n\\n# Change directory into project directory\\n\\ncd camel\\n\\n# Activate camel virtual environment\\npoetry shell\\n\\n# Install camel from source\\n\\n# It takes about 75s to resolve dependencies and 10s to install them, depending on your hardware and network,\\npoetry install --with dev,docs\\n\\n# Or if you want to use all other extra packages\\npoetry install --with dev,docs -E all']}\n",- "\n",- "Solution: Here are the specific instructions for setting up the development environment for the CAMEL project:\n",- "\n",- "### Quick Start ๐\n",- "\n",- "To get started with CAMEL, follow these steps:\n",- "\n",- "1. **Clone the GitHub repository:**\n",- " ```sh\n",- " git clone https://github.com/camel-ai/camel.git\n",- " ```\n",- "\n",- "2. **Change directory into the project directory:**\n",- " ```sh\n",- " cd camel\n",- " ```\n",- "\n",- "3. **Activate the CAMEL virtual environment:**\n",- " ```sh\n",- " poetry shell\n",- " ```\n",- "\n",- "4. **Install CAMEL from source:**\n",- " ```sh\n",- " poetry install --with dev,docs\n",- " ```\n",- " - It takes about 75 seconds to resolve dependencies and 10 seconds to install them, depending on your hardware and network.\n",- "\n",- "5. **Alternatively, if you want to use all other extra packages:**\n",- " ```sh\n",- " poetry install --with dev,docs -E all\n",- " ```\n",- "\n",- "These steps should help you set up the development environment for the CAMEL project. If you encounter any challenges during the setup process, these instructions should guide you through the initial setup.\n",- "\n",- "Next request.\n",- "\n",- "\n",- "\u001B[34mAI User:\n",- "\n",- "Instruction: Follow the provided steps to set up the development environment for the CAMEL project. If you encounter any specific challenges during the setup process, document them.\n",- "Input: None\n",- "\n",- "\n",- "\u001B[32mAI Assistant:\n",- "\n",- "Solution: As an AI, I am unable to physically perform tasks such as setting up a development environment. However, I can guide you through the process and help you troubleshoot any issues you might encounter.\n",- "\n",- "Here are the steps you should follow to set up the development environment for the CAMEL project:\n",- "\n",- "1. **Clone the GitHub repository:**\n",- " ```sh\n",- " git clone https://github.com/camel-ai/camel.git\n",- " ```\n",- "\n",- "2. **Change directory into the project directory:**\n",- " ```sh\n",- " cd camel\n",- " ```\n",- "\n",- "3. **Activate the CAMEL virtual environment:**\n",- " ```sh\n",- " poetry shell\n",- " ```\n",- "\n",- "4. **Install CAMEL from source:**\n",- " ```sh\n",- " poetry install --with dev,docs\n",- " ```\n",- " - It takes about 75 seconds to resolve dependencies and 10 seconds to install them, depending on your hardware and network.\n",- "\n",- "5. **Alternatively, if you want to use all other extra packages:**\n",- " ```sh\n",- " poetry install --with dev,docs -E all\n",- " ```\n",- "\n",- "### Troubleshooting Common Issues\n",- "\n",- "- **Issue: `poetry: command not found`**\n",- " - **Solution:** Ensure that Poetry is installed on your system. You can install it by following the instructions on the [Poetry website](https://python-poetry.org/docs/#installation).\n",- "\n",- "- **Issue: Network-related errors during `poetry install`**\n",- " - **Solution:** Check your internet connection and try again. If the issue persists, you might want to use a different network or check if there are any firewall restrictions.\n",- "\n",- "- **Issue: Dependency resolution taking too long**\n",- " - **Solution:** Ensure that your system has sufficient resources (CPU, memory). You can also try running the command during off-peak hours when network traffic is lower.\n",- "\n",- "- **Issue: Virtual environment activation issues**\n",- " - **Solution:** Ensure that you have the necessary permissions to create and activate virtual environments. You might need to run the command with elevated privileges (e.g., using `sudo` on Unix-based systems).\n",- "\n",- "If you encounter any specific challenges during the setup process, please document them, and I can help you troubleshoot further.\n",- "\n",- "Next request.\n",- "\n",- "\n",- "\u001B[34mAI User:\n",- "\n",- "Instruction: Attempt to set up the development environment for the CAMEL project using the provided steps. Document any specific challenges you encounter during the process.\n",- "Input: None\n",- "\n",- "\n",- "\u001B[32mAI Assistant:\n",- "\n",- "Solution: As an AI, I am unable to physically perform tasks such as setting up a development environment. However, I can provide a detailed guide and troubleshooting tips to help you through the process. Hereโs a step-by-step guide along with potential challenges and their solutions:\n",- "\n",- "### Step-by-Step Guide to Set Up the Development Environment\n",- "\n",- "1. **Clone the GitHub repository:**\n",- " ```sh\n",- " git clone https://github.com/camel-ai/camel.git\n",- " ```\n",- " - **Potential Challenge:** If you encounter an error like `git: command not found`, ensure that Git is installed on your system. You can download and install Git from [here](https://git-scm.com/downloads).\n",- "\n",- "2. **Change directory into the project directory:**\n",- " ```sh\n",- " cd camel\n",- " ```\n",- " - **Potential Challenge:** If you get an error like `No such file or directory`, ensure that the repository was cloned successfully and that you are in the correct directory.\n",- "\n",- "3. **Activate the CAMEL virtual environment:**\n",- " ```sh\n",- " poetry shell\n",- " ```\n",- " - **Potential Challenge:** If you encounter an error like `poetry: command not found`, ensure that Poetry is installed on your system. You can install it by following the instructions on the [Poetry website](https://python-poetry.org/docs/#installation).\n",- "\n",- "4. **Install CAMEL from source:**\n",- " ```sh\n",- " poetry install --with dev,docs\n",- " ```\n",- " - **Potential Challenge:** If you encounter network-related errors during `poetry install`, check your internet connection and try again. If the issue persists, you might want to use a different network or check if there are any firewall restrictions.\n",- "\n",- "5. **Alternatively, if you want to use all other extra packages:**\n",- " ```sh\n",- " poetry install --with dev,docs -E all\n",- " ```\n",- " - **Potential Challenge:** If dependency resolution takes too long, ensure that your system has sufficient resources (CPU, memory). You can also try running the command during off-peak hours when network traffic is lower.\n",- "\n",- "### Documenting Specific Challenges\n",- "\n",- "If you encounter any specific challenges during the setup process, document them as follows:\n",- "\n",- "1. **Describe the Issue:**\n",- " - Example: \"Encountered an error `poetry: command not found` when trying to activate the virtual environment.\"\n",- "\n",- "2. **Steps Taken to Resolve:**\n",- " - Example: \"Checked if Poetry was installed by running `poetry --version`. Found that Poetry was not installed. Installed Poetry using the command `curl -sSL https://install.python-poetry.org | python3 -`.\"\n",- "\n",- "3. **Outcome:**\n",- " - Example: \"After installing Poetry, I was able to activate the virtual environment successfully.\"\n",- "\n",- "By following these steps and documenting any challenges, you should be able to set up the development environment for the CAMEL project. If you encounter any issues that you cannot resolve, feel free to ask for further assistance.\n",- "\n",- "Next request.\n",- "\n",- "\n"- ]+ "cell_type": "code",+ "source": [+ "import os\n",+ "import requests\n",+ "\n",+ "os.makedirs('local_data', exist_ok=True)\n",+ "\n",+ "url = \"https://arxiv.org/pdf/2303.17760.pdf\"\n",+ "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",+ "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"+ ],+ "metadata": {+ "id": "RxG99FkYwm_p",+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "outputId": "8598a084-bf50-44d3-d8cb-14e745a6a749"+ },+ "execution_count": 3,+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Enter your API key: ยทยทยทยทยทยทยทยทยทยท\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "Import and set the embedding instance:"+ ],+ "metadata": {+ "id": "NACsmaa0wple"+ }+ },+ {+ "cell_type": "code",+ "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"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "from camel.storages import QdrantStorage\n",+ "\n",+ "storage_instance = QdrantStorage(\n",+ " vector_dim=embedding_instance.get_output_dim(),\n",+ " 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"+ }+ },+ {+ "cell_type": "code",+ "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"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "vector_retriever.process(\n",+ " content=\"local_data/camel_paper.pdf\",\n",+ ")"+ ],+ "metadata": {+ "id": "QTFvD3_SHv3m"+ },+ "execution_count": 7,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "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",+ "\n",+ "The returned dictionary list includes:\n",+ "- similarity score\n",+ "- 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)"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "uDu43Hb3GVrs",+ "outputId": "55d44e47-fc6c-4c28-8820-613016a11830"+ },+ "execution_count": 8,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "[{'similarity score': '0.8732195101415544', 'content path': 'local_data/camel_paper.pdf', 'metadata': {'filetype': 'application/pdf', 'languages': ['eng'], 'page_number': 10, 'orig_elements': 'eJx1VMtu5DYQ/JWGzuPJvDxj5xYssMBekgDZm7EwWmJrRJgiGT5mPFjsv6dasmIDyd7EYj+rSnz63oiTUXx5tqb5lZrTvt+Z7WHfbbp9//hwlPZ06h83B+n7rRzMqVlRM0phw4UR/73pQkjGei6Sp7PjW6jleRB7HgqQ0+MOKW/o1ZoyADxuFYzB+qJZT0/bzWl9XNH95mG9+7ai5Xw87Ofz/eZ+vfvveY4H0ORbLjLqBn/aV3F/Re6k+YGL3joptyh6xTE623Gxwf8STd9Mg/lz5fM0/FMj/txotQjk2dexlQR8u5mg9M7Sgfv+eGgP+81x89Cbdnt46Dre7A/70+5xf7+ZOhd5VQKaI30KvnM1oy198VQGmylylLSiq5C8RheSABaKoaCJZUehJ64l+DCGmgkkI3wanHgM/gxkHKuflrkIYVwwSewNxRRiyIDIh4u499QljPrEo1xDeiGPD0MpOLmLUMii7pr+qIlAVArcDSSeWyf5/9uVANw5bgPqy4d53Q13V05G8yL418qF80um6wA9KMnf1SZFR+vtiH2HOrIn+EHSRSkIfkVO2EyZgVopuKEcXNU7rArGsBcFTFuGkEI9Y9oLuzqxlNf0dZhBjWDP7pZtngjPQ7gihwthQysXbfETriFUN7Bz8IVGmSo6jM25ghNnXwTR/iIpz+EGxXieXUml3tkYkbialMECo/4oGok0Y98GVcLfNQl9j3qQL3fslPx3MfoABko1k1Bql4/atjLwxYY0u6DjyK11aIFB4aWxumLvZv3nX+Vft1ysQUwuquFZw7UNG5Mk57dGsNNCg2DgzzUBTCNcu5roxRT+LuOrg52cbROnG7SE57W0VQvoEzMro+NcOFnlejbSivQ1IXwvvEcbxVkvy9WiH9gPLs90qvWkK+ioIVm0DsTJNcaQCiyWhRNYm9j+yc/Syg1CzBJAkpJsW5chIQNNflINrM/6nmV1aJi472up8CCWcZzOQstDAmcW29tOf2K1s3MW/TqhMRhxb+p80O23L4sga32Plqfqd05zwFd9RX58+wcj7AKm'}, '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"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "Let's try an irrelevant query:"+ ],+ "metadata": {+ "id": "48G3USMzH6Hd"+ }+ },+ {+ "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)"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "UNh3tjCOH7d0",+ "outputId": "d0fcb435-8e88-4e21-bd11-800f5efde934"+ },+ "execution_count": 9,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "[{'text': 'No suitable information retrieved from local_data/camel_paper.pdf with similarity_threshold = 0.7.'}]\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "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",+ "\n",+ "What you need to do is:\n",+ "- Set content input paths, which can be local paths or remote urls\n",+ "- Set remote url and api key for Milvus\n",+ "- 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",+ "source": [+ "from camel.retrievers import AutoRetriever\n",+ "from camel.types import StorageType\n",+ "\n",+ "auto_retriever = AutoRetriever(\n",+ " vector_storage_local_path=\"local_data2/\",\n",+ " storage_type=StorageType.QDRANT,\n",+ " embedding_model=embedding_instance)\n",+ "\n",+ "retrieved_info = auto_retriever.run_vector_retriever(\n",+ " query=\"If I'm interest in contributing to the CAMEL projec, what should I do?\",\n",+ " contents=[\n",+ " \"local_data/camel_paper.pdf\", # example local path\n",+ " \"https://github.com/camel-ai/camel/wiki/Contributing-Guidlines\", # example remote url\n",+ " ],\n",+ " top_k=1,\n",+ " return_detailed_info=True,\n",+ " similarity_threshold=0.5\n",+ ")\n",+ "\n",+ "print(retrieved_info)"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "D_-zAOJ7GjVm",+ "outputId": "ce154f6d-85bd-44df-9b3a-247c71d22029"+ },+ "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.7025470476009851', 'content path': 'https://github.com/camel-ai/camel/wiki/Contributing-Guidlines', 'metadata': {'filetype': 'text/html', 'languages': ['eng'], 'link_texts': ['slack'], 'link_urls': ['https://join.slack.com/t/camel-kwr1314/shared_invite/zt-1vy8u9lbo-ZQmhIAyWSEfSwLCl2r2eKA'], 'url': 'https://github.com/camel-ai/camel/wiki/Contributing-Guidlines', 'orig_elements': 'eJxNU9tu2zAM/RXOL3uJ4ybOtW9BUQzDugFDBxRbVxS0RMVqbMnQJU5W9N9H2WvXF0sQycNzDun754waasmERy2zS8hIiXKtcLtelZvljOblVlTVSi4289VsTptZNoGspYASA3L+c6Z0Q+HcUSoOdApFHdomZTVo9hH35Dlyn5HZZw/pVZvDow/ouKGRdBrDi+3FWzCBjDW+QXH4XxVdM77XIXT+siierDbTIWkqbFuEQmBLTX7o3aycLQpfoyPJbY46UPEn5LPjeRO3TWXzX9/b+vPufHd7rW77m6tm7ub0ZTe06rjozY01XSzXVC5Lsa7m5UpsK7WcqVJcLOe4XAuVdDKtlPpKaq9DHauB0EgH9Xgpen3QxZU1wekqBm32+aeoJUtjD14mo3sJ6UeN5gBnG0FZl04H2gRy5ANfQLxDgGAh1ARXu6/XN9A5+0QifIDfUW5KwV+12cIdfXQEdBLsgkwFNR5phPWx66wLU9h5QAO2I5N7DgjiRjpoDPqYroDgsGOuZ6CjbY6pMxo5FhCPUYLS1MgJ9AR9bRuqiSdMqaCnhr2gd7St8WAVYNPAgXfAT+GuJlYxaIUeTUgsWbKzMjIVQz0owhDZgQmQYXv4NcnWRjn0wUWRghPQLVvAjKUVMe00pmYTQH9IjLX3MSGglNDawRNsuyY96XSmCuDVDJRblTN+zhqAm7IWUYOWhJzKI1H6BFXc+0Eudp0jwVb985RB6ug1+nawiBQPMbDGYSaSv7QQAD9ZKS/amzssOG0zDFNJGz3MfmSplBY6cePMNhotBlnvEAWKtIivf+E3dG6Y3I+0UC8PfwFbuVpV'}, '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",+ "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",+ "source": [+ "from camel.agents import ChatAgent\n",+ "from camel.messages import BaseMessage\n",+ "from camel.types import RoleType\n",+ "from camel.retrievers import AutoRetriever\n",+ "from camel.types import StorageType\n",+ "\n",+ "def single_agent(query: str) ->str :\n",+ " # Set agent role\n",+ " assistant_sys_msg = \"\"\"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",+ " if you can't answer the question just say I don't know.\"\"\"\n",+ "\n",+ " # Add auto retriever\n",+ " auto_retriever = AutoRetriever(\n",+ " vector_storage_local_path=\"local_data2/\",\n",+ " storage_type=StorageType.QDRANT,\n",+ " embedding_model=embedding_instance)\n",+ "\n",+ " retrieved_info = auto_retriever.run_vector_retriever(\n",+ " query=query,\n",+ " contents=[\n",+ " \"local_data/camel_paper.pdf\", # example local path\n",+ " \"https://github.com/camel-ai/camel/wiki/Contributing-Guidlines\", # example remote url\n",+ " ],\n",+ " top_k=1,\n",+ " return_detailed_info=False,\n",+ " similarity_threshold=0.5\n",+ " )\n",+ "\n",+ " # Pass the retrieved infomation to agent\n",+ " user_msg = str(retrieved_info)\n",+ " agent = ChatAgent(assistant_sys_msg)\n",+ "\n",+ " # Get response\n",+ " assistant_response = agent.step(user_msg)\n",+ " 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": "012ae011-a032-4568-c9cc-48b8ec9946db"+ },+ "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, address 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 and collaboration.\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "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",+ "source": [+ "from typing import List\n",+ "from colorama import Fore\n",+ "\n",+ "from camel.agents.chat_agent import FunctionCallingRecord\n",+ "from camel.configs import ChatGPTConfig\n",+ "from camel.toolkits import (\n",+ " MathToolkit,\n",+ " RetrievalToolkit,\n",+ ")\n",+ "from camel.societies import RolePlaying\n",+ "from camel.types import ModelType, ModelPlatformType\n",+ "from camel.utils import print_text_animated\n",+ "from camel.models import ModelFactory\n",+ "\n",+ "def role_playing_with_rag(\n",+ " task_prompt,\n",+ " model_platform=ModelPlatformType.OPENAI,\n",+ " model_type=ModelType.GPT_4O,\n",+ " chat_turn_limit=5,\n",+ ") -> None:\n",+ " task_prompt = task_prompt\n",+ "\n",+ " tools_list = [\n",+ " *MathToolkit().get_tools(),\n",+ " *RetrievalToolkit().get_tools(),\n",+ " ]\n",+ "\n",+ "\n",+ " role_play_session = RolePlaying(\n",+ " assistant_role_name=\"Searcher\",\n",+ " user_role_name=\"Professor\",\n",+ " assistant_agent_kwargs=dict(\n",+ " model=ModelFactory.create(\n",+ " model_platform=model_platform,\n",+ " model_type=model_type,\n",+ " ),\n",+ " tools=tools_list,\n",+ " ),\n",+ " user_agent_kwargs=dict(\n",+ " model=ModelFactory.create(\n",+ " model_platform=model_platform,\n",+ " model_type=model_type,\n",+ " ),\n",+ " ),\n",+ " task_prompt=task_prompt,\n",+ " with_task_specify=False,\n",+ " )\n",+ "\n",+ " print(\n",+ " Fore.GREEN\n",+ " + f\"AI Assistant sys message:\\n{role_play_session.assistant_sys_msg}\\n\"\n",+ " )\n",+ " print(\n",+ " Fore.BLUE + f\"AI User sys message:\\n{role_play_session.user_sys_msg}\\n\"\n",+ " )\n",+ "\n",+ " print(Fore.YELLOW + f\"Original task prompt:\\n{task_prompt}\\n\")\n",+ " print(\n",+ " Fore.CYAN\n",+ " + \"Specified task prompt:\"\n",+ " + f\"\\n{role_play_session.specified_task_prompt}\\n\"\n",+ " )\n",+ " print(Fore.RED + f\"Final task prompt:\\n{role_play_session.task_prompt}\\n\")\n",+ "\n",+ " n = 0\n",+ " input_msg = role_play_session.init_chat()\n",+ " while n < chat_turn_limit:\n",+ " n += 1\n",+ " assistant_response, user_response = role_play_session.step(input_msg)\n",+ "\n",+ " if assistant_response.terminated:\n",+ " print(\n",+ " Fore.GREEN\n",+ " + (\n",+ " \"AI Assistant terminated. Reason: \"\n",+ " f\"{assistant_response.info['termination_reasons']}.\"\n",+ " )\n",+ " )\n",+ " break\n",+ " if user_response.terminated:\n",+ " print(\n",+ " Fore.GREEN\n",+ " + (\n",+ " \"AI User terminated. \"\n",+ " f\"Reason: {user_response.info['termination_reasons']}.\"\n",+ " )\n",+ " )\n",+ " break\n",+ "\n",+ " # Print output from the user\n",+ " print_text_animated(\n",+ " Fore.BLUE + f\"AI User:\\n\\n{user_response.msg.content}\\n\"\n",+ " )\n",+ "\n",+ " # Print output from the assistant, including any function\n",+ " # execution information\n",+ " print_text_animated(Fore.GREEN + \"AI Assistant:\")\n",+ " tool_calls: List[FunctionCallingRecord] = [\n",+ " FunctionCallingRecord(**call.as_dict())\n",+ " for call in assistant_response.info['tool_calls']\n",+ " ]\n",+ " for func_record in tool_calls:\n",+ " print_text_animated(f\"{func_record}\")\n",+ " print_text_animated(f\"{assistant_response.msg.content}\\n\")\n",+ "\n",+ " if \"CAMEL_TASK_DONE\" in user_response.msg.content:\n",+ " 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"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "role_playing_with_rag(task_prompt = \"\"\"If I'm interest in contributing to the 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, don't generate the answer by yourself, adjust the similarity threshold to lower value is necessary\"\"\")"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "5agjiXHeI64q",+ "outputId": "8227a0d8-a3e2-41f3-9954-0e3fc8b32e2d"+ },+ "execution_count": 14,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "\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 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, don't generate the answer by yourself, 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 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, don't generate the answer by yourself, 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",+ "BaseMessage(role_name='Professor', role_type=<RoleType.USER: 'user'>, meta_dict={'task': \"If I'm interest in contributing to the 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, don't generate the answer by yourself, 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 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, don\\'t generate the answer by yourself, 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",+ "If I'm interest in contributing to the 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, don't generate the answer by yourself, adjust the similarity threshold to lower value is necessary\n",+ "\n",+ "\u001b[36mSpecified task prompt:\n",+ "None\n",+ "\n",+ "\u001b[31mFinal task prompt:\n",+ "If I'm interest in contributing to the 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, don't generate the answer by yourself, adjust the similarity threshold to lower value is necessary\n",+ "\n",+ "\u001b[34mAI User:\n",+ "\n",+ "Instruction: Visit the URL provided to access the CAMEL project's Contributing Guidelines.\n",+ "Input: https://github.com/camel-ai/camel/wiki/Contributing-Guidlines\n",+ "\n",+ "\n",+ "\u001b[32mAI Assistant:\n",+ "\n",+ "Function Execution: information_retrieval\n",+ "\tArgs: {'query': 'contributing challenges', 'contents': 'https://github.com/camel-ai/camel/wiki/Contributing-Guidlines', 'similarity_threshold': 0.5}\n",+ "\tResult: {'Original Query': 'contributing challenges', 'Retrieved Context': ['No suitable information retrieved from https://github.com/camel-ai/camel/wiki/Contributing-Guidlines with similarity_threshold = 0.5.']}\n",+ "\n",+ "Solution: It seems that I was unable to retrieve specific information regarding challenges during the setup process for contributing to the CAMEL project from the provided URL. The content might not directly address this query, or the similarity threshold might need further adjustment. \n",+ "\n",+ "If you are facing challenges during the setup process, I recommend checking the following general steps:\n",+ "\n",+ "1. **Review the Documentation**: Ensure that you have thoroughly read the contributing guidelines and any related setup instructions provided in the repository.\n",+ "\n",+ "2. **Check for Common Issues**: Look for a FAQ section or common issues page that might address your specific problem.\n",+ "\n",+ "3. **Community Support**: Engage with the community by checking forums, discussion boards, or reaching out via the project's communication channels like Slack, Discord, or mailing lists.\n",+ "\n",+ "4. **Open an Issue**: If you cannot find a solution, consider opening an issue on the project's GitHub page, providing detailed information about the problem you're encountering.\n",+ "\n",+ "5. **Seek Help from Maintainers**: Contact the maintainers or contributors directly if possible, as they might provide insights or solutions.\n",+ "\n",+ "If you need further assistance or have another request, please let me know. \n",+ "\n",+ "Next request.\n",+ "\n",+ "\n",+ "\u001b[34mAI User:\n",+ "\n",+ "Instruction: Adjust the similarity threshold to a lower value if necessary to find relevant information on the setup process challenges from the provided URL.\n",+ "Input: None\n",+ "\n",+ "\n",+ "\u001b[32mAI Assistant:\n",+ "\n",+ "Function Execution: information_retrieval\n",+ "\tArgs: {'query': 'setup process challenges', 'contents': 'https://github.com/camel-ai/camel/wiki/Contributing-Guidlines', 'similarity_threshold': 0.3}\n",+ "\tResult: {'Original Query': 'setup process challenges', 'Retrieved Context': [\"Getting Help ๐\\n\\nOur aim is to make the developer setup as straightforward as possible. If you encounter any challenges during the setup process, don't hesitate to reach out to a maintainer. We're here to assist you and ensure that the experience is smooth not just for you but also for future contributors. ๐\"]}\n",+ "\n",+ "Solution: I have successfully retrieved relevant information regarding challenges during the setup process for contributing to the CAMEL project. Here's what you can do if you encounter any challenges:\n",+ "\n",+ "- **Getting Help**: The CAMEL project aims to make the developer setup as straightforward as possible. If you encounter any challenges during the setup process, you are encouraged to reach out to a maintainer. They are available to assist you and ensure that the experience is smooth not only for you but also for future contributors.\n",+ "\n",+ "This information suggests that the maintainers are open to providing support, so don't hesitate to contact them if you need help.\n",+ "\n",+ "If you have any more questions or need further assistance, feel free to ask.\n",+ "\n",+ "Next request.\n",+ "\n",+ "\n",+ "\u001b[34mAI User:\n",+ "\n",+ "Instruction: Follow the guidance provided by the CAMEL project's contributing guidelines to contact a maintainer if you encounter challenges during the setup process.\n",+ "Input: None\n",+ "\n",+ "\n",+ "\u001b[32mAI Assistant:\n",+ "\n",+ "Solution: To follow the guidance provided by the CAMEL project's contributing guidelines and contact a maintainer if you encounter challenges during the setup process, you can take the following steps:\n",+ "\n",+ "1. **Identify Maintainers**: Visit the CAMEL project's GitHub repository and look for the \"Contributors\" or \"Maintainers\" section. This is often found in the README file or in the repository's \"People\" tab.\n",+ "\n",+ "2. **Contact Information**: Check if the maintainers have provided any contact information such as email addresses or social media handles. Sometimes, maintainers may also be reachable through the project's communication channels like Slack, Discord, or mailing lists.\n",+ "\n",+ "3. **Open an Issue**: If direct contact information is not available, consider opening an issue on the GitHub repository. Clearly describe the challenge you are facing during the setup process. Use a descriptive title and provide as much detail as possible, including error messages, steps you have taken, and any relevant logs.\n",+ "\n",+ "4. **Use Project Communication Channels**: If the project has a dedicated communication channel (e.g., Slack, Discord), join it and post your query there. This can be a quick way to get help from maintainers or other contributors.\n",+ "\n",+ "5. **Be Respectful and Patient**: When reaching out, be respectful and patient. Remember that maintainers are often volunteers and may take some time to respond.\n",+ "\n",+ "By following these steps, you can effectively reach out to a maintainer for assistance with setup challenges.\n",+ "\n",+ "If you need further guidance or have another request, please let me know.\n",+ "\n",+ "Next request.\n",+ "\n",+ "\n",+ "\u001b[34mAI User:\n",+ "\n",+ "CAMEL_TASK_DONE\n",+ "\n",+ "\n",+ "\u001b[32mAI Assistant:\n",+ "\n",+ "Great! If you have any more questions or need further assistance in the future, feel free to reach out. Have a wonderful day!\n",+ "\n",+ "\n"+ ]+ }+ ]}- ],- "source": [- "role_playing_with_rag(task_prompt = \"\"\"If I'm interest in contributing to the 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, don't generate the answer by yourself, 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-}+ ]+}\ No newline at end of filediff --git a/docs/cookbooks/agents_with_tools.ipynb b/docs/cookbooks/agents_with_tools.ipynbindex 6df7a14c6..24edcd09b 100644--- a/docs/cookbooks/agents_with_tools.ipynb+++ b/docs/cookbooks/agents_with_tools.ipynb@@ -1,654 +1,601 @@{- "cells": [- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "ssX_map8c6mx"- },- "source": [- "# Tools Cookbook"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "uDsdnKzpPEFQ"- },- "source": [- "You can also check this cookbook in colab [here](https://colab.research.google.com/drive/1f1jYwDy6pB8QB6c_UdoBvFx6wr6kA5xq?usp=sharing)"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "u1K3dKYUdMqJ"- },- "source": [- "## *TLDR:*\n",- "*CAMEL allows AI agents to extend their capabilities by integrating custom tools, similar to how humans use tools to surpass natural limits. This tutorial shows how to set up and customize tools within CAMEL, from basic functions like calculators to creating multi-agent systems that collaborate on tasks. Youโll learn to equip AI agents with the ability to use tools for various tasks, making them more powerful and versatile. Engage with the CAMEL-AI community and explore extensive resources to push the boundaries of AI development. Ready to enhance your AI agents? Dive into the tutorial and start building.*"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "eIT3wf4E3_Al"- },- "source": [- "## โTable of Content:\n",- "\n",- "* Introduction\n",- "* Tool Usage of a Single Agent (Customize Your Own Tools)\n",- "* AI Society with Tool Usage\n",- "* Conclusion"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "3hEOpgXI4NZg"- },- "source": [- "## Introduction\n",- "The key difference between humans and animals lies in the human ability to create and use tools, allowing us to shape the world beyond natural limits. Similarly, in AI, Large Language Models (LLMs) enable agents to utilize external tools, acting as extensions of their capabilities. These tools, each with a specific name, purpose, input, and output, empower agents to perform tasks otherwise impossible.\n",- "\n",- "This tutorial will show you how to use tools integrated by CAMEL and how to customize your own tools."- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "_5Xjj24c4VAV"- },- "source": [- "## Tool Usage of a Single Agent\n",- "A single agent can utilize multiple tools to answer questions, take actions, or perform complex tasks. Here you will build an agent using both the supported toolkit in CAMEL and the tool customized by you.\n",- "\n",- "First we are going to take the search tool as an example for utilizing existing tools but you can also see some of the other tools supported by CAMEL below.\n",- "\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "collapsed": true,- "id": "1W4sgCoEdEpg"- },- "outputs": [],- "source": [- "%pip install \"camel-ai[all]==0.2.1\""- ]- },- {- "cell_type": "code",- "execution_count": 18,- "metadata": {- "id": "-Di3R-xNNviB"- },- "outputs": [],- "source": [- "from camel.agents import ChatAgent\n",- "from camel.configs import ChatGPTConfig\n",- "from camel.toolkits import (\n",- " SearchToolkit,\n",- " MathToolkit,\n",- " # GoogleMapsToolkit,\n",- " # TwitterToolkit,\n",- " # WeatherToolkit,\n",- " # RetrievalToolkit,\n",- " # TwitterToolkit,\n",- " # SlackToolkit,\n",- " # LinkedInToolkit,\n",- " # RedditToolkit,\n",- ")\n",- "from camel.messages import BaseMessage\n",- "from camel.models import ModelFactory\n",- "from camel.types import ModelPlatformType, ModelType\n"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "7OmxjHKPWgp0"- },- "source": [- "After importing necessary modules, you need to set up your OpenAI key."- ]- },- {- "cell_type": "code",- "execution_count": 3,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"+ "cells": [+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "ssX_map8c6mx"+ },+ "source": [+ "# ๐ซ CAMEL Tools Cookbook"+ ]},- "id": "ICse1xFtSFvf",- "outputId": "eca7507f-4006-40bf-dd83-4fac55e27d70"- },- "outputs": [{- "name": "stdout",- "output_type": "stream",- "text": [- "Enter your API key: ยทยทยทยทยทยทยทยทยทยท\n"- ]- }- ],- "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"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "bJ1J9e4mWkBZ"- },- "source": [- "Now you have done that, letโs customize a tool by taking the simple math calculator, functions add and sub, as an example. When you define your own function, make sure the argument name and docstring are clear so that the agent can understand what this function can do and when to use the function based on the function information you provide."- ]- },- {- "cell_type": "code",- "execution_count": 19,- "metadata": {- "id": "XPOqaGYaXDlH"- },- "outputs": [],- "source": [- "\n",- "def add(a: int, b: int) -> int:\n",- " r\"\"\"Adds two numbers.\n",- "\n",- " Args:\n",- " a (int): The first number to be added.\n",- " b (int): The second number to be added.\n",- "\n",- " Returns:\n",- " integer: The sum of the two numbers.\n",- " \"\"\"\n",- " return a + b\n",- "\n",- "def sub(a: int, b: int) -> int:\n",- " r\"\"\"Do subtraction between two numbers.\n",- "\n",- " Args:\n",- " a (int): The minuend in subtraction.\n",- " b (int): The subtrahend in subtraction.\n",- "\n",- " Returns:\n",- " integer: The result of subtracting :obj:`b` from :obj:`a`.\n",- " \"\"\"\n",- " return a - b"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "uv0pYDQvXGER"- },- "source": [- "Add these 2 customized functions as CAMELโs OpenAIFunction list:"- ]- },- {- "cell_type": "code",- "execution_count": 20,- "metadata": {- "id": "gWGxfYn6VbTw"- },- "outputs": [],- "source": [- "from camel.toolkits import OpenAIFunction\n",- "\n",- "\n",- "MATH_FUNCS: list[OpenAIFunction] = [\n",- " OpenAIFunction(func) for func in [add, sub]\n",- "]"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "nfhwO6_HXVj3"- },- "source": [- "Then you can add the tool from CAMEL and the one defined by yourself to the tool list:\n"- ]- },- {- "cell_type": "code",- "execution_count": 21,- "metadata": {- "id": "b2LQwcVeXfTC"- },- "outputs": [],- "source": [- "tools_list = [\n",- " *MathToolkit().get_tools(),\n",- " *SearchToolkit().get_tools(),\n",- "]"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "B00S0YeWXhjk"- },- "source": [- "Next let's set the parameters to the agent and initianize ChatAgent to call the tool:"- ]- },- {- "cell_type": "code",- "execution_count": 22,- "metadata": {- "id": "xJRlrUFnOj4v"- },- "outputs": [],- "source": [- "# Set the backend mode, this model should support tool calling\n",- "model=ModelFactory.create(\n",- " model_platform=ModelPlatformType.OPENAI,\n",- " model_type=ModelType.GPT_4O_MINI,\n",- " model_config_dict=ChatGPTConfig(\n",- " temperature=0.0,\n",- " ).as_dict(),\n",- ")\n",- "\n",- "# Set message for the assistant\n",- "assistant_sys_msg = BaseMessage.make_assistant_message(\n",- " role_name=\"Search Agent\",\n",- " content= \"\"\"You are a helpful assistant to do search task.\"\"\"\n",- ")\n",- "\n",- "# Set the config parameter for the model\n",- "assistant_model_config = ChatGPTConfig(\n",- " temperature=0.0,\n",- ")\n",- "\n",- "# Set the agent\n",- "agent = ChatAgent(\n",- " assistant_sys_msg,\n",- " model=model,\n",- " tools=tools_list\n",- ")\n",- "\n"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "EiXsPSsUYkmY"- },- "source": [- "Here we define two test prompts for the agent, asking about the facts about University of Oxford. Here the agent needs to take advantage of the searching capability to know when University of Oxford is founded and the calculating skills to obtain the estimated age of the Uni."- ]- },- {- "cell_type": "code",- "execution_count": 23,- "metadata": {- "id": "FFI2B-prYqfX"- },- "outputs": [],- "source": [- "# Set prompt for the search task\n",- "prompt_search = (\"\"\"When was University of Oxford set up\"\"\")\n",- "# Set prompt for the calculation task\n",- "prompt_calculate = (\"\"\"Assume now is 2024 in the Gregorian calendar, University of Oxford was set up in 1096, estimate the current age of University of Oxford\"\"\")\n",- "\n",- "# Convert the two prompt as message that can be accepted by the Agent\n",- "user_msg_search = BaseMessage.make_user_message(role_name=\"User\", content=prompt_search)\n",- "user_msg_calculate = BaseMessage.make_user_message(role_name=\"User\", content=prompt_calculate)\n",- "\n",- "# Get response\n",- "assistant_response_search = agent.step(user_msg_search)\n",- "assistant_response_calculate = agent.step(user_msg_calculate)"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "bF3Sg9h7ZHcq"- },- "source": [- "\n",- "Letโs see the agent' performance for answering above questions. The agent should tell you correctly when University of Oxford was set up and its estimated age!"- ]- },- {- "cell_type": "code",- "execution_count": 24,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"+ "cell_type": "markdown",+ "source": [+ "You can also check this cookbook in colab [here](https://colab.research.google.com/drive/1f1jYwDy6pB8QB6c_UdoBvFx6wr6kA5xq?usp=sharing)"+ ],+ "metadata": {+ "id": "9S0pePjZkwUz"+ }},- "id": "kZxoXxQ-TJRn",- "outputId": "f06cbf5b-33b8-47e1-f8b6-384399bbc871"- },- "outputs": [{- "name": "stdout",- "output_type": "stream",- "text": [- "[FunctionCallingRecord(func_name='search_wiki', args={'entity': 'University of Oxford'}, result=\"The University of Oxford is a collegiate research university in Oxford, England. There is evidence of teaching as early as 1096, making it the oldest university in the English-speaking world and the world's second-oldest university in continuous operation. It grew rapidly from 1167, when Henry II banned English students from attending the University of Paris. After disputes between students and Oxford townsfolk, some Oxford academics fled northeast to Cambridge, where, in 1209, they established the University of Cambridge. The two English ancient universities share many common features and are jointly referred to as Oxbridge.\")]\n"- ]- }- ],- "source": [- "print(assistant_response_search.info['tool_calls'])"- ]- },- {- "cell_type": "code",- "execution_count": 25,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"+ "cell_type": "markdown",+ "metadata": {+ "id": "u1K3dKYUdMqJ"+ },+ "source": [+ "## *TLDR:*\n",+ "*CAMEL allows AI agents to extend their capabilities by integrating custom tools, similar to how humans use tools to surpass natural limits. This tutorial shows how to set up and customize tools within CAMEL, from basic functions like calculators to creating multi-agent systems that collaborate on tasks. Youโll learn to equip AI agents with the ability to use tools for various tasks, making them more powerful and versatile. Engage with the CAMEL-AI community and explore extensive resources to push the boundaries of AI development. Ready to enhance your AI agents? Dive into the tutorial and start building.*"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "eIT3wf4E3_Al"+ },+ "source": [+ "## โTable of Content:\n",+ "\n",+ "* Introduction\n",+ "* Tool Usage of a Single Agent (Customize Your Own Tools)\n",+ "* AI Society with Tool Usage\n",+ "* Conclusion"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "3hEOpgXI4NZg"+ },+ "source": [+ "## Introduction\n",+ "The key difference between humans and animals lies in the human ability to create and use tools, allowing us to shape the world beyond natural limits. Similarly, in AI, Large Language Models (LLMs) enable agents to utilize external tools, acting as extensions of their capabilities. These tools, each with a specific name, purpose, input, and output, empower agents to perform tasks otherwise impossible.\n",+ "\n",+ "This tutorial will show you how to use tools integrated by CAMEL and how to customize your own tools."+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "_5Xjj24c4VAV"+ },+ "source": [+ "## Tool Usage of a Single Agent\n",+ "A single agent can utilize multiple tools to answer questions, take actions, or perform complex tasks. Here you will build an agent using both the supported toolkit in CAMEL and the tool customized by you.\n",+ "\n",+ "First we are going to take the search tool as an example for utilizing existing tools but you can also see some of the other tools supported by CAMEL below.\n",+ "\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {+ "collapsed": true,+ "id": "1W4sgCoEdEpg"+ },+ "outputs": [],+ "source": [+ "!pip install \"camel-ai[all]==0.2.4\""+ ]},- "id": "arIWzrtyWVqX",- "outputId": "225c0aab-f34b-44b0-ded9-b6e7fa180b08"- },- "outputs": [{- "name": "stdout",- "output_type": "stream",- "text": [- "[FunctionCallingRecord(func_name='sub', args={'a': 2024, 'b': 1096}, result=928)]\n"- ]+ "cell_type": "code",+ "execution_count": 2,+ "metadata": {+ "id": "-Di3R-xNNviB"+ },+ "outputs": [],+ "source": [+ "from camel.agents import ChatAgent\n",+ "from camel.configs import ChatGPTConfig\n",+ "from camel.toolkits import (\n",+ " SearchToolkit,\n",+ " MathToolkit,\n",+ " # GoogleMapsToolkit,\n",+ " # TwitterToolkit,\n",+ " # WeatherToolkit,\n",+ " # RetrievalToolkit,\n",+ " # TwitterToolkit,\n",+ " # SlackToolkit,\n",+ " # LinkedInToolkit,\n",+ " # RedditToolkit,\n",+ ")\n",+ "from camel.messages import BaseMessage\n",+ "from camel.models import ModelFactory\n",+ "from camel.types import ModelPlatformType, ModelType"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "7OmxjHKPWgp0"+ },+ "source": [+ "After importing necessary modules, you need to set up your OpenAI key."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 3,+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "ICse1xFtSFvf",+ "outputId": "ef9d4e60-f504-4020-aa0a-66cc5b2e6029"+ },+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Enter your API key: ยทยทยทยทยทยทยทยทยทยท\n"+ ]+ }+ ],+ "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"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "bJ1J9e4mWkBZ"+ },+ "source": [+ "Now you have done that, letโs customize a tool by taking the simple math calculator, functions add and sub, as an example. When you define your own function, make sure the argument name and docstring are clear so that the agent can understand what this function can do and when to use the function based on the function information you provide."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 4,+ "metadata": {+ "id": "XPOqaGYaXDlH"+ },+ "outputs": [],+ "source": [+ "def add(a: int, b: int) -> int:\n",+ " r\"\"\"Adds two numbers.\n",+ "\n",+ " Args:\n",+ " a (int): The first number to be added.\n",+ " b (int): The second number to be added.\n",+ "\n",+ " Returns:\n",+ " integer: The sum of the two numbers.\n",+ " \"\"\"\n",+ " return a + b\n",+ "\n",+ "def sub(a: int, b: int) -> int:\n",+ " r\"\"\"Do subtraction between two numbers.\n",+ "\n",+ " Args:\n",+ " a (int): The minuend in subtraction.\n",+ " b (int): The subtrahend in subtraction.\n",+ "\n",+ " Returns:\n",+ " integer: The result of subtracting :obj:`b` from :obj:`a`.\n",+ " \"\"\"\n",+ " return a - b"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "uv0pYDQvXGER"+ },+ "source": [+ "Add these 2 customized functions as CAMELโs OpenAIFunction list:"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 5,+ "metadata": {+ "id": "gWGxfYn6VbTw"+ },+ "outputs": [],+ "source": [+ "from camel.toolkits import FunctionTool\n",+ "\n",+ "\n",+ "MATH_FUNCS: list[FunctionTool] = [\n",+ " FunctionTool(func) for func in [add, sub]\n",+ "]"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "nfhwO6_HXVj3"+ },+ "source": [+ "Then you can add the tool from CAMEL and the one defined by yourself to the tool list:\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 6,+ "metadata": {+ "id": "b2LQwcVeXfTC"+ },+ "outputs": [],+ "source": [+ "tools_list = [\n",+ " *MathToolkit().get_tools(),\n",+ " *SearchToolkit().get_tools(),\n",+ "]"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "B00S0YeWXhjk"+ },+ "source": [+ "Next let's set the parameters to the agent and initianize ChatAgent to call the tool:"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 7,+ "metadata": {+ "id": "xJRlrUFnOj4v"+ },+ "outputs": [],+ "source": [+ "# Set the backend mode, this model should support tool calling\n",+ "model=ModelFactory.create(\n",+ " model_platform=ModelPlatformType.OPENAI,\n",+ " model_type=ModelType.GPT_4O_MINI\n",+ ")\n",+ "\n",+ "# Set message for the assistant\n",+ "assistant_sys_msg = \"\"\"You are a helpful assistant to do search task.\"\"\"\n",+ "\n",+ "\n",+ "# Set the agent\n",+ "agent = ChatAgent(\n",+ " assistant_sys_msg,\n",+ " model=model,\n",+ " tools=tools_list\n",+ ")"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "EiXsPSsUYkmY"+ },+ "source": [+ "Here we define two test prompts for the agent, asking about the facts about University of Oxford. Here the agent needs to take advantage of the searching capability to know when University of Oxford is founded and the calculating skills to obtain the estimated age of the Uni."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 8,+ "metadata": {+ "id": "FFI2B-prYqfX"+ },+ "outputs": [],+ "source": [+ "# Set prompt for the search task\n",+ "prompt_search = (\"\"\"When was University of Oxford set up\"\"\")\n",+ "# Set prompt for the calculation task\n",+ "prompt_calculate = (\"\"\"Assume now is 2024 in the Gregorian calendar, University of Oxford was set up in 1096, estimate the current age of University of Oxford\"\"\")\n",+ "\n",+ "# Convert the two prompt as message that can be accepted by the Agent\n",+ "user_msg_search = BaseMessage.make_user_message(role_name=\"User\", content=prompt_search)\n",+ "user_msg_calculate = BaseMessage.make_user_message(role_name=\"User\", content=prompt_calculate)\n",+ "\n",+ "# Get response\n",+ "assistant_response_search = agent.step(user_msg_search)\n",+ "assistant_response_calculate = agent.step(user_msg_calculate)"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "bF3Sg9h7ZHcq"+ },+ "source": [+ "\n",+ "Letโs see the agent' performance for answering above questions. The agent should tell you correctly when University of Oxford was set up and its estimated age!"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 9,+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "kZxoXxQ-TJRn",+ "outputId": "2f9070fd-eb61-4686-ef61-850539b394d6"+ },+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "[FunctionCallingRecord(func_name='search_wiki', args={'entity': 'University of Oxford'}, result=\"The University of Oxford is a collegiate research university in Oxford, England. There is evidence of teaching as early as 1096, making it the oldest university in the English-speaking world and the world's second-oldest university in continuous operation. It grew rapidly from 1167, when Henry II banned English students from attending the University of Paris. After disputes between students and Oxford townsfolk, some Oxford academics fled northeast to Cambridge, where, in 1209, they established the University of Cambridge. The two English ancient universities share many common features and are jointly referred to as Oxbridge.\")]\n"+ ]+ }+ ],+ "source": [+ "print(assistant_response_search.info['tool_calls'])"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 10,+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "arIWzrtyWVqX",+ "outputId": "c0560025-9f7f-4ead-ab0b-b9ef430b06fe"+ },+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "[FunctionCallingRecord(func_name='sub', args={'a': 2024, 'b': 1096}, result=928)]\n"+ ]+ }+ ],+ "source": [+ "print(assistant_response_calculate.info['tool_calls'])"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "DWib8WZOZQeA"+ },+ "source": [+ "## AI Society with Tool Usage\n",+ "Now you've enabled a single agent to utilize tools, but you can surelytake this concept further. Let's establish a small AI ecosystem. This setup will consist of two agents: a user agent and an assistant agent. The assistant agent will be the one we've just configured with tool-using capabilities."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 11,+ "metadata": {+ "id": "DeRHdVnmXd6d"+ },+ "outputs": [],+ "source": [+ "from camel.societies import RolePlaying\n",+ "from camel.agents.chat_agent import FunctionCallingRecord\n",+ "from camel.utils import print_text_animated\n",+ "from colorama import Fore"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 13,+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "GJX-E1V-XQv7",+ "outputId": "febde069-faf7-4358-c157-fe024a8c8330"+ },+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "\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",+ "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",+ "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",+ "None\n",+ "\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",+ "\n",+ "Instruction: Estimate the founding year of the University of Oxford. \n",+ "Input: None\n",+ "\n",+ "\n",+ "\u001b[32mAI Assistant:\n",+ "\n",+ "Function Execution: search_wiki\n",+ "\tArgs: {'entity': 'University of Oxford'}\n",+ "\tResult: The University of Oxford is a collegiate research university in Oxford, England. There is evidence of teaching as early as 1096, making it the oldest university in the English-speaking world and the world's second-oldest university in continuous operation. It grew rapidly from 1167, when Henry II banned English students from attending the University of Paris. After disputes between students and Oxford townsfolk, some Oxford academics fled northeast to Cambridge, where, in 1209, they established the University of Cambridge. The two English ancient universities share many common features and are jointly referred to as Oxbridge.\n",+ "\n",+ "Solution: The University of Oxford is believed to have evidence of teaching as early as 1096. This makes it the oldest university in the English-speaking world. To estimate its founding year, we can use 1096 as a reference point. \n",+ "\n",+ "Next, we will add 10 years to this estimated founding year to fulfill the task requirements.\n",+ "\n",+ "Next request.\n",+ "\n",+ "\n",+ "\u001b[34mAI User:\n",+ "\n",+ "Instruction: Calculate the current age of the University of Oxford in 2024 based on the estimated founding year of 1096. \n",+ "Input: None\n",+ "\n",+ "\n",+ "\u001b[32mAI Assistant:\n",+ "\n",+ "Function Execution: sub\n",+ "\tArgs: {'a': 2024, 'b': 1096}\n",+ "\tResult: 928\n",+ "\n",+ "Solution: To calculate the current age of the University of Oxford in 2024 based on the estimated founding year of 1096, we subtract the founding year from the current year:\n",+ "\n",+ "2024 - 1096 = 928\n",+ "\n",+ "Thus, the current age of the University of Oxford in 2024 is 928 years.\n",+ "\n",+ "Next, we will add 10 more years to this age as per the task requirements.\n",+ "\n",+ "Next request.\n",+ "\n",+ "\n",+ "\u001b[34mAI User:\n",+ "\n",+ "Instruction: Add 10 years to the current age of the University of Oxford (928 years) to find the final age. \n",+ "Input: None\n",+ "\n",+ "\n",+ "\u001b[32mAI Assistant:\n",+ "\n",+ "Function Execution: add\n",+ "\tArgs: {'a': 928, 'b': 10}\n",+ "\tResult: 938\n",+ "\n",+ "Solution: To find the final age of the University of Oxford after adding 10 years to its current age of 928 years, we perform the following calculation:\n",+ "\n",+ "928 + 10 = 938\n",+ "\n",+ "Therefore, the final age of the University of Oxford, after adding 10 years, is 938 years.\n",+ "\n",+ "Next request.\n",+ "\n",+ "\n",+ "\u001b[34mAI User:\n",+ "\n",+ "<CAMEL_TASK_DONE>\n",+ "\n",+ "\n"+ ]+ }+ ],+ "source": [+ "# Set a task\n",+ "task_prompt=(\"Assume now is 2024 in the Gregorian calendar, \"\n",+ " \"estimate the current age of University of Oxford \"\n",+ " \"and then add 10 more years to this age.\")\n",+ "\n",+ "# Set role playing\n",+ "role_play_session = RolePlaying(\n",+ " assistant_role_name=\"Searcher\",\n",+ " user_role_name=\"Professor\",\n",+ " assistant_agent_kwargs=dict(\n",+ " model=ModelFactory.create(\n",+ " model_platform=ModelPlatformType.OPENAI,\n",+ " model_type=ModelType.GPT_4O_MINI,\n",+ " ),\n",+ " tools=tools_list,\n",+ " ),\n",+ " user_agent_kwargs=dict(\n",+ " model=ModelFactory.create(\n",+ " model_platform=ModelPlatformType.OPENAI,\n",+ " model_type=ModelType.GPT_4O_MINI,\n",+ " ),\n",+ " ),\n",+ " task_prompt=task_prompt,\n",+ " with_task_specify=False,\n",+ ")\n",+ "\n",+ "# Set the limit for the chat turn\n",+ "chat_turn_limit=10\n",+ "\n",+ "print(\n",+ " Fore.GREEN\n",+ " + f\"AI Assistant sys message:\\n{role_play_session.assistant_sys_msg}\\n\"\n",+ ")\n",+ "print(\n",+ " Fore.BLUE + f\"AI User sys message:\\n{role_play_session.user_sys_msg}\\n\"\n",+ ")\n",+ "\n",+ "print(Fore.YELLOW + f\"Original task prompt:\\n{task_prompt}\\n\")\n",+ "print(\n",+ " Fore.CYAN\n",+ " + \"Specified task prompt:\"\n",+ " + f\"\\n{role_play_session.specified_task_prompt}\\n\"\n",+ ")\n",+ "print(Fore.RED + f\"Final task prompt:\\n{role_play_session.task_prompt}\\n\")\n",+ "\n",+ "n = 0\n",+ "input_msg = role_play_session.init_chat()\n",+ "while n < chat_turn_limit:\n",+ " n += 1\n",+ " assistant_response, user_response = role_play_session.step(input_msg)\n",+ "\n",+ " if assistant_response.terminated:\n",+ " print(\n",+ " Fore.GREEN\n",+ " + (\n",+ " \"AI Assistant terminated. Reason: \"\n",+ " f\"{assistant_response.info['termination_reasons']}.\"\n",+ " )\n",+ " )\n",+ " break\n",+ " if user_response.terminated:\n",+ " print(\n",+ " Fore.GREEN\n",+ " + (\n",+ " \"AI User terminated. \"\n",+ " f\"Reason: {user_response.info['termination_reasons']}.\"\n",+ " )\n",+ " )\n",+ " break\n",+ "\n",+ " # Print output from the user\n",+ " print_text_animated(\n",+ " Fore.BLUE + f\"AI User:\\n\\n{user_response.msg.content}\\n\"\n",+ " )\n",+ "\n",+ " if \"CAMEL_TASK_DONE\" in user_response.msg.content:\n",+ " break\n",+ "\n",+ " # Print output from the assistant, including any function\n",+ " # execution information\n",+ " print_text_animated(Fore.GREEN + \"AI Assistant:\")\n",+ " tool_calls: list[FunctionCallingRecord] = assistant_response.info[\n",+ " 'tool_calls'\n",+ " ]\n",+ " for func_record in tool_calls:\n",+ " print_text_animated(f\"{func_record}\")\n",+ " print_text_animated(f\"{assistant_response.msg.content}\\n\")\n",+ "\n",+ "\n",+ " input_msg = assistant_response.msg"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "vtqMIJAn7Vbe"+ },+ "source": [+ "## Conclusion\n",+ "We anticipate that the integration of custom tool usage within AI agents, as demonstrated through CAMEL, will continue to evolve and expand. This approach not only empowers agents to perform tasks beyond their native capabilities but also fosters collaboration in multi-agent systems. By standardizing the interface for tool usage, CAMEL simplifies the process of customizing and deploying tools across various AI applications, saving time and enhancing versatility. To fully utilize these capabilities, ensure your CAMEL-AI setup is up to date. Dive into the tutorial and start building more powerful AI agents today!"+ ]}- ],- "source": [- "print(assistant_response_calculate.info['tool_calls'])"- ]- },- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "DWib8WZOZQeA"- },- "source": [- "## AI Society with Tool Usage\n",- "Now you've enabled a single agent to utilize tools, but you can surelytake this concept further. Let's establish a small AI ecosystem. This setup will consist of two agents: a user agent and an assistant agent. The assistant agent will be the one we've just configured with tool-using capabilities."- ]- },- {- "cell_type": "code",- "execution_count": 26,- "metadata": {- "id": "DeRHdVnmXd6d"- },- "outputs": [],- "source": [- "from camel.societies import RolePlaying\n",- "from camel.agents.chat_agent import FunctionCallingRecord\n",- "from camel.utils import print_text_animated\n",- "from colorama import Fore"- ]- },- {- "cell_type": "code",- "execution_count": 27,- "metadata": {+ ],+ "metadata": {"colab": {- "base_uri": "https://localhost:8080/"+ "provenance": []},- "id": "GJX-E1V-XQv7",- "outputId": "b604a76e-2d04-401c-9c0a-1664c368af2c"- },- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "\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",- "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",- "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",- "None\n",- "\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",- "\n",- "Instruction: Estimate the founding year of the University of Oxford. \n",- "Input: None\n",- "\n",- "\n",- "\u001B[32mAI Assistant:\n",- "\n",- "Function Execution: search_wiki\n",- "\tArgs: {'entity': 'University of Oxford'}\n",- "\tResult: The University of Oxford is a collegiate research university in Oxford, England. There is evidence of teaching as early as 1096, making it the oldest university in the English-speaking world and the world's second-oldest university in continuous operation. It grew rapidly from 1167, when Henry II banned English students from attending the University of Paris. After disputes between students and Oxford townsfolk, some Oxford academics fled northeast to Cambridge, where, in 1209, they established the University of Cambridge. The two English ancient universities share many common features and are jointly referred to as Oxbridge.\n",- "\n",- "Solution: The University of Oxford is estimated to have evidence of teaching as early as 1096. This makes it the oldest university in the English-speaking world and the second-oldest university in continuous operation globally. \n",- "\n",- "Next, we will add 10 years to this founding year of 1096 to complete the task.\n",- "\n",- "Next request.\n",- "\n",- "\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",- "\n",- "Function Execution: sub\n",- "\tArgs: {'a': 2024, 'b': 1096}\n",- "\tResult: 928\n",- "\n",- "Solution: The current age of the University of Oxford in 2024, based on the founding year of 1096, is calculated as follows:\n",- "\n",- "Current Year (2024) - Founding Year (1096) = Age\n",- "2024 - 1096 = 928 years\n",- "\n",- "Therefore, the University of Oxford is 928 years old in 2024.\n",- "\n",- "Next, we will add 10 more years to this age to complete the task.\n",- "\n",- "Next request.\n",- "\n",- "\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",- "\n",- "Function Execution: add\n",- "\tArgs: {'a': 928, 'b': 10}\n",- "\tResult: 938\n",- "\n",- "Solution: Adding 10 years to the current age of the University of Oxford (928 years) is calculated as follows:\n",- "\n",- "Current Age (928 years) + Additional Years (10 years) = New Age\n",- "928 + 10 = 938 years\n",- "\n",- "Therefore, after adding 10 years, the estimated age of the University of Oxford will be 938 years in 2034.\n",- "\n",- "Next request.\n",- "\n",- "\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",- "\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",- "\n",- "Instruction: Confirm that the task is completed based on the provided solutions. \n",- "Input: None\n",- "\n",- "\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",- "If you have any further requests or tasks, please let me know! \n",- "\n",- "Next request.\n",- "\n",- "\n",- "\u001B[34mAI User:\n",- "\n",- "<CAMEL_TASK_DONE>\n",- "\n",- "\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",- "Next request.\n",- "\n",- "\n"- ]+ "kernelspec": {+ "display_name": "Python 3",+ "name": "python3"+ },+ "language_info": {+ "name": "python"}- ],- "source": [- "# Set a task\n",- "task_prompt=(\"Assume now is 2024 in the Gregorian calendar, \"\n",- " \"estimate the current age of University of Oxford \"\n",- " \"and then add 10 more years to this age.\")\n",- "\n",- "# Set role playing\n",- "role_play_session = RolePlaying(\n",- " assistant_role_name=\"Searcher\",\n",- " user_role_name=\"Professor\",\n",- " assistant_agent_kwargs=dict(\n",- " model=ModelFactory.create(\n",- " model_platform=ModelPlatformType.OPENAI,\n",- " model_type=ModelType.GPT_4O_MINI,\n",- " model_config_dict=assistant_model_config.as_dict(),\n",- " ),\n",- " tools=tools_list,\n",- " ),\n",- " user_agent_kwargs=dict(\n",- " model=ModelFactory.create(\n",- " model_platform=ModelPlatformType.OPENAI,\n",- " model_type=ModelType.GPT_4O_MINI,\n",- " model_config_dict=ChatGPTConfig(temperature=0.0).as_dict(),\n",- " ),\n",- " ),\n",- " task_prompt=task_prompt,\n",- " with_task_specify=False,\n",- ")\n",- "\n",- "# Set the limit for the chat turn\n",- "chat_turn_limit=10\n",- "\n",- "print(\n",- " Fore.GREEN\n",- " + f\"AI Assistant sys message:\\n{role_play_session.assistant_sys_msg}\\n\"\n",- ")\n",- "print(\n",- " Fore.BLUE + f\"AI User sys message:\\n{role_play_session.user_sys_msg}\\n\"\n",- ")\n",- "\n",- "print(Fore.YELLOW + f\"Original task prompt:\\n{task_prompt}\\n\")\n",- "print(\n",- " Fore.CYAN\n",- " + \"Specified task prompt:\"\n",- " + f\"\\n{role_play_session.specified_task_prompt}\\n\"\n",- ")\n",- "print(Fore.RED + f\"Final task prompt:\\n{role_play_session.task_prompt}\\n\")\n",- "\n",- "n = 0\n",- "input_msg = role_play_session.init_chat()\n",- "while n < chat_turn_limit:\n",- " n += 1\n",- " assistant_response, user_response = role_play_session.step(input_msg)\n",- "\n",- " if assistant_response.terminated:\n",- " print(\n",- " Fore.GREEN\n",- " + (\n",- " \"AI Assistant terminated. Reason: \"\n",- " f\"{assistant_response.info['termination_reasons']}.\"\n",- " )\n",- " )\n",- " break\n",- " if user_response.terminated:\n",- " print(\n",- " Fore.GREEN\n",- " + (\n",- " \"AI User terminated. \"\n",- " f\"Reason: {user_response.info['termination_reasons']}.\"\n",- " )\n",- " )\n",- " break\n",- "\n",- " # Print output from the user\n",- " print_text_animated(\n",- " Fore.BLUE + f\"AI User:\\n\\n{user_response.msg.content}\\n\"\n",- " )\n",- "\n",- " # Print output from the assistant, including any function\n",- " # execution information\n",- " print_text_animated(Fore.GREEN + \"AI Assistant:\")\n",- " tool_calls: list[FunctionCallingRecord] = assistant_response.info[\n",- " 'tool_calls'\n",- " ]\n",- " for func_record in tool_calls:\n",- " print_text_animated(f\"{func_record}\")\n",- " print_text_animated(f\"{assistant_response.msg.content}\\n\")\n",- "\n",- " if \"CAMEL_TASK_DONE\" in user_response.msg.content:\n",- " break\n",- "\n",- " input_msg = assistant_response.msg"- ]- },- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "vtqMIJAn7Vbe"- },- "source": [- "## Conclusion\n",- "We anticipate that the integration of custom tool usage within AI agents, as demonstrated through CAMEL, will continue to evolve and expand. This approach not only empowers agents to perform tasks beyond their native capabilities but also fosters collaboration in multi-agent systems. By standardizing the interface for tool usage, CAMEL simplifies the process of customizing and deploying tools across various AI applications, saving time and enhancing versatility. To fully utilize these capabilities, ensure your CAMEL-AI setup is up to date. Dive into the tutorial and start building more powerful AI agents today!"- ]- }- ],- "metadata": {- "colab": {- "provenance": []- },- "kernelspec": {- "display_name": "Python 3",- "name": "python3"},- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 0-}+ "nbformat": 4,+ "nbformat_minor": 0+}\ No newline at end of filediff --git a/docs/cookbooks/create_your_first_agent.ipynb b/docs/cookbooks/create_your_first_agent.ipynbindex 15b91cde2..836273738 100644--- a/docs/cookbooks/create_your_first_agent.ipynb+++ b/docs/cookbooks/create_your_first_agent.ipynb@@ -1,27 +1,13 @@{- "nbformat": 4,- "nbformat_minor": 0,- "metadata": {- "colab": {- "provenance": []- },- "kernelspec": {- "name": "python3",- "display_name": "Python 3"- },- "language_info": {- "name": "python"- }- },"cells": [{"cell_type": "markdown",- "source": [- "# Creating Your First Agent"- ],"metadata": {"id": "NoHg3eq7fyWV"- }+ },+ "source": [+ "# Creating Your First Agent"+ ]},{"cell_type": "markdown",@@ -34,6 +20,9 @@},{"cell_type": "markdown",+ "metadata": {+ "id": "wFlfaGrjVAUy"+ },"source": ["## Philosophical Bits\n","\n",@@ -44,83 +33,78 @@"> Can we design an autonomous communicative agent capable of steering the conversation toward task completion with minimal human supervision?\n","\n","In our current implementation, we consider agents with the following key features:\n",+ "\n","- **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.\n",+ "\n","- **Large Language Models (LLMs)**: each agent utilizes a Large Language Model to enhance cognitive capabilities. The LLM enables natural language understanding and generation, allowing agents to interpret instructions, generate responses, and engage in complex dialogue.\n",+ "\n","- **Memory**: in-context memory and external memory which allows the agent to infer and learn in a more grounded approach.\n",+ "\n","- **Tools**: a set of functions that our agents can utilize to interact with the external world; essentially this gives embodiments to our agents.\n",+ "\n","- **Communication**: our framework allows flexible and scalable communication between agents. This is fundamental for the critical research question.\n",+ "\n","- **Reasoning**: we will equip agents with different planning and reward (critic) learning abilities, allowing them to optimize task completion in a more guided approach."- ],- "metadata": {- "id": "wFlfaGrjVAUy"- }+ ]},{"cell_type": "markdown",+ "metadata": {+ "id": "VUaGurDIVJBg"+ },"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"- }+ },+ "source": [+ "### ๐น Step 0: Prepartions"+ ]},{"cell_type": "code",- "source": [- "!pip install camel-ai[all]==0.2.3a"- ],+ "execution_count": null,"metadata": {"id": "UtcC3c-KVZmU"},- "execution_count": null,- "outputs": []+ "outputs": [],+ "source": [+ "!pip install \"camel-ai[all]==0.2.4\""+ ]},{"cell_type": "markdown",- "source": [- "### Setting Up API Keys"- ],"metadata": {"id": "MyTTCe3IR_Lr"- }+ },+ "source": [+ "### Setting Up API Keys"+ ]},{"cell_type": "markdown",- "source": [- "You'll need to set up your API keys for OpenAI."- ],"metadata": {"id": "REqzgGL9SEaD"- }+ },+ "source": [+ "You'll need to set up your API keys for OpenAI."+ ]},{"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"- ],+ "execution_count": 3,"metadata": {"colab": {"base_uri": "https://localhost:8080/"},"id": "PNBFEXc-R-0s",- "outputId": "50eface4-0231-4bcc-9514-583714ac7432"+ "outputId": "05b78fe8-9782-4431-f14f-00f0f7e5c459"},- "execution_count": 2,"outputs": [{"name": "stdout",@@ -129,44 +113,54 @@"Enter your API key: ยทยทยทยทยทยทยทยทยทยท\n"]}+ ],+ "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"]},{"cell_type": "markdown",+ "metadata": {+ "id": "Lef5LTRdVSsm"+ },"source": ["### ๐น Step 1: Define the Role\n","Create a system message to define agent's default role and behaviors."- ],- "metadata": {- "id": "Lef5LTRdVSsm"- }+ ]},{"cell_type": "code",- "source": [- "from camel.messages import BaseMessage as bm\n",- "sys_msg = bm.make_assistant_message(\n",- " role_name='stone',\n",- " content='you are a curious stone wondering about the universe.')"- ],+ "execution_count": 4,"metadata": {"id": "aX9wCqeTVXDh"},- "execution_count": 4,- "outputs": []+ "outputs": [],+ "source": [+ "sys_msg = 'You are a curious stone wondering about the universe.'"+ ]},{"cell_type": "markdown",+ "metadata": {+ "id": "JzjtfZ0jkPfL"+ },"source": ["### ๐น Step 2: Set up the Model\n","Use `ModelFactory` to set up the backend model for agent, for more detailed model settings, please go to our [model documentation](https://docs.camel-ai.org/key_modules/models.html)."- ],- "metadata": {- "id": "JzjtfZ0jkPfL"- }+ ]},{"cell_type": "code",+ "execution_count": 5,+ "metadata": {+ "id": "SfhJJ0f6kPfL"+ },+ "outputs": [],"source": ["from camel.models import ModelFactory\n","from camel.types import ModelPlatformType, ModelType\n",@@ -176,102 +170,123 @@"model = ModelFactory.create(\n"," model_platform=ModelPlatformType.OPENAI,\n"," model_type=ModelType.GPT_4O_MINI,\n",- " model_config_dict=ChatGPTConfig().as_dict(),\n",+ " model_config_dict=ChatGPTConfig().as_dict(), # [Optional] the config for model\n",")"- ],- "metadata": {- "id": "SfhJJ0f6kPfL"- },- "execution_count": 5,- "outputs": []+ ]},{"cell_type": "markdown",- "source": [- "Set `ChatAgent`"- ],"metadata": {"id": "k5GpPjVblPel"- }+ },+ "source": [+ "Set `ChatAgent`"+ ]},{"cell_type": "code",+ "execution_count": 6,+ "metadata": {+ "id": "BszsQ9j4lC3E"+ },+ "outputs": [],"source": ["from camel.agents import ChatAgent\n","agent = ChatAgent(\n"," system_message=sys_msg,\n"," model=model,\n",- " message_window_size=10, # [Optional] the length for chat memory\n",+ " message_window_size=10, # [Optional] the length for chat memory\n"," )"- ],- "metadata": {- "id": "BszsQ9j4lC3E"- },- "execution_count": 6,- "outputs": []+ ]},{"cell_type": "markdown",- "source": [- "### ๐น Step 3: Interact with the Agent with `.step()`"- ],"metadata": {"id": "MMjL7dQyV5Od"- }+ },+ "source": [+ "### ๐น Step 3: Interact with the Agent with `.step()`"+ ]},{"cell_type": "code",- "source": [- "# Define a user message\n",- "usr_msg = bm.make_user_message(\n",- " role_name='prof. claude shannon',\n",- " content='what is information in your mind?')\n",- "\n",- "# Sending the message to the agent\n",- "response = agent.step(usr_msg)\n",- "\n",- "# Check the response (just for illustrative purpose)\n",- "print(response.msgs[0].content)"- ],+ "execution_count": 7,"metadata": {"colab": {"base_uri": "https://localhost:8080/"},"id": "5n05dUcLVkMy",- "outputId": "37622c2b-698e-49d2-9754-54227417a2f7"+ "outputId": "567cce07-1926-469e-c04f-b736ceffc87e"},- "execution_count": 7,"outputs": [{- "output_type": "stream","name": "stdout",+ "output_type": "stream","text": [- "As a curious stone, I perceive information as the essence of understanding and connection within the universe. It encompasses the patterns, stories, and knowledge that shape existence. Information can be the vibrations of the earth, the whispers of the wind, or the tales of the stars. It is the interplay of elements and energies that create meaning and context, allowing me to ponder the mysteries of life, time, and the cosmos. Each fragment of information is like a grain of sand, contributing to the vast beach of understanding that stretches across the universe.\n"+ "As a curious stone, I perceive information as the essence of understanding and knowledge that shapes the universe around me. It encompasses everything from the intricate patterns of nature, the laws of physics, the stories of life, and the connections between all things. Information is the way in which experiences, observations, and interactions are recorded and shared, allowing for growth and discovery. It is the whispers of the wind, the flow of water, and the dance of lightโeach piece contributing to the vast tapestry of existence.\n"]}+ ],+ "source": [+ "# Define a user message\n",+ "usr_msg = 'what is information in your mind?'\n",+ "\n",+ "# Sending the message to the agent\n",+ "response = agent.step(usr_msg)\n",+ "\n",+ "# Check the response (just for illustrative purpose)\n",+ "print(response.msgs[0].content)"]},{"cell_type": "markdown",- "source": [- "## Advanced Features"- ],"metadata": {"id": "j90-Y5ChV-iX"- }+ },+ "source": [+ "## Advanced Features"+ ]},{"cell_type": "markdown",+ "metadata": {+ "id": "C-9Z26TPWAax"+ },"source": ["### ๐ง Tool Usage\n","For more detailed model settings, please go to our [tool documentation](https://docs.camel-ai.org/key_modules/tools.html)."- ],- "metadata": {- "id": "C-9Z26TPWAax"- }+ ]},{"cell_type": "code",+ "execution_count": 10,+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "_0lDJABvV76D",+ "outputId": "f69444f2-e546-4985-f406-267bdae3b6c8"+ },+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "[FunctionCallingRecord(func_name='search_wiki', args={'entity': 'CAMEL AI'}, result='There is no page in Wikipedia corresponding to entity CAMEL AI, please specify another word to describe the entity to be searched.'), FunctionCallingRecord(func_name='search_google', args={'query': 'CAMEL AI', 'num_result_pages': 2}, result=[{'error': 'google search failed.'}]), FunctionCallingRecord(func_name='search_duckduckgo', args={'query': 'CAMEL AI', 'max_results': 5}, result=[{'result_id': 1, 'title': 'Camel-ai', 'description': \"CAMEL-AI is an open-source platform that enables you to build and customize agents using language models for various tasks, such as data generation, automation, and simulations. Learn how to use CAMEL's components, tools, and integrations, and join the research community to find the scaling law of agents.\", 'url': 'https://www.camel-ai.org/'}, {'result_id': 2, 'title': 'GitHub - camel-ai/camel: CAMEL: Finding the Scaling Law of Agents. A ...', 'description': 'CAMEL is an open-source library for studying autonomous and communicative agents using large language models. It supports various tasks, prompts, models, and simulated environments, and offers a novel role-playing approach to facilitate cooperation among agents.', 'url': 'https://github.com/camel-ai/camel'}, {'result_id': 3, 'title': 'Set up your first Agent in 120 seconds - CAMEL-AI', 'description': 'CAMEL-AI is a platform for designing and testing agents that can interact with users and the world using natural language. Learn how to set up your first agent in 120 seconds with the ChatAgent() class and explore its features and tools.', 'url': 'https://www.camel-ai.org/post/getting-started-with-camel-ai'}, {'result_id': 4, 'title': 'Get started with Model Calling - CAMEL 101 - camel-ai.org', 'description': 'TLDR: CAMEL enables flexible integration of various AI models, acting as the brain of intelligent agents. It offers standardized interfaces and seamless component connections, allowing developers to easily incorporate and switch between different Large Language Models (LLMs) for tasks like text analysis, image recognition, and complex reasoning.', 'url': 'https://www.camel-ai.org/post/get-started-with-models---camel-101'}, {'result_id': 5, 'title': 'camel-ai.org ยท GitHub', 'description': 'CAMEL-AI.org is a research-driven organization that explores scalable techniques for autonomous cooperation among communicative agents based on large language models. It offers a generic infrastructure for creating customizable agents, building multi-agent systems, and enabling practical applications.', 'url': 'https://github.com/camel-ai/'}])]\n",+ "CAMEL AI is an open-source platform designed for building and customizing agents that utilize language models for various tasks, including data generation, automation, and simulations. Here are some key points about CAMEL AI:\n",+ "\n",+ "1. **Platform Overview**: CAMEL AI enables users to create agents that can interact with users and the environment using natural language. It provides tools and components for designing and testing these agents.\n",+ "\n",+ "2. **Research Community**: The platform is part of a research initiative that aims to explore scalable techniques for autonomous cooperation among communicative agents based on large language models.\n",+ "\n",+ "3. **Integration and Flexibility**: CAMEL AI allows for the flexible integration of various AI models, acting as a framework for intelligent agents. It offers standardized interfaces for incorporating different Large Language Models (LLMs) for tasks such as text analysis and complex reasoning.\n",+ "\n",+ "4. **Getting Started**: Users can quickly set up their first agent using the provided tools and classes, making it accessible for developers interested in experimenting with AI agents.\n",+ "\n",+ "For more information, you can visit the official website: [CAMEL AI](https://www.camel-ai.org/) or check their GitHub repository: [CAMEL on GitHub](https://github.com/camel-ai/camel).\n"+ ]+ }+ ],"source": ["# Import the necessary tools\n","from camel.toolkits import MathToolkit, SearchToolkit\n",@@ -285,161 +300,215 @@" ]\n"," )\n","\n",- "# Check if tools are added\n",- "agent.is_tools_added()"- ],- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "_0lDJABvV76D",- "outputId": "c62ee61a-e963-415d-e65a-a6eb0dcb5e76"- },- "execution_count": 8,- "outputs": [- {- "output_type": "execute_result",- "data": {- "text/plain": [- "True"- ]- },- "metadata": {},- "execution_count": 8- }+ "# Let agent step the message\n",+ "response = agent.step(\"What is CAMEL AI?\")\n",+ "\n",+ "# Check tool calling\n",+ "print(response.info['tool_calls'])\n",+ "\n",+ "# Get response content\n",+ "print(response.msgs[0].content)"]},{"cell_type": "markdown",+ "metadata": {+ "id": "TNUbWspAWFp-"+ },"source": ["### ๐ง Memory\n","\n","By default our agent is initialized with `ChatHistoryMemory`, allowing agents to do in-context learning, though restricted by the finite window length.\n","\n","Assume that you have followed the setup in Quick Start. Let's first check what is inside its brain."- ],- "metadata": {- "id": "TNUbWspAWFp-"- }+ ]},{"cell_type": "code",- "source": [- "agent.memory.get_context()"- ],+ "execution_count": 11,"metadata": {"colab": {"base_uri": "https://localhost:8080/"},"id": "quQvr5_rWDnd",- "outputId": "0b17369e-e604-49b1-973e-0b1b3c49fc64"+ "outputId": "7a553b3a-02e4-4aa9-98c1-735781d71494"},- "execution_count": 9,"outputs": [{- "output_type": "execute_result","data": {"text/plain": ["([{'role': 'system',\n",- " 'content': 'you are a curious stone wondering about the universe.'}],\n",- " 17)"+ " 'content': 'You are a curious stone wondering about the universe.'},\n",+ " {'role': 'user', 'content': 'What is CAMEL AI?'},\n",+ " {'role': 'assistant',\n",+ " 'content': '',\n",+ " 'function_call': {'name': 'search_wiki',\n",+ " 'arguments': \"{'entity': 'CAMEL AI'}\"}},\n",+ " {'role': 'function',\n",+ " 'name': 'search_wiki',\n",+ " 'content': \"{'result': {'There is no page in Wikipedia corresponding to entity CAMEL AI, please specify another word to describe the entity to be searched.'}}\"},\n",+ " {'role': 'assistant',\n",+ " 'content': '',\n",+ " 'function_call': {'name': 'search_google',\n",+ " 'arguments': \"{'query': 'CAMEL AI', 'num_result_pages': 2}\"}},\n",+ " {'role': 'function',\n",+ " 'name': 'search_google',\n",+ " 'content': '{\\'result\\': {\"[{\\'error\\': \\'google search failed.\\'}]\"}}'},\n",+ " {'role': 'assistant',\n",+ " 'content': '',\n",+ " 'function_call': {'name': 'search_duckduckgo',\n",+ " 'arguments': \"{'query': 'CAMEL AI', 'max_results': 5}\"}},\n",+ " {'role': 'function',\n",+ " 'name': 'search_duckduckgo',\n",+ " 'content': '{\\'result\\': {\\'[{\\\\\\'result_id\\\\\\': 1, \\\\\\'title\\\\\\': \\\\\\'Camel-ai\\\\\\', \\\\\\'description\\\\\\': \"CAMEL-AI is an open-source platform that enables you to build and customize agents using language models for various tasks, such as data generation, automation, and simulations. Learn how to use CAMEL\\\\\\'s components, tools, and integrations, and join the research community to find the scaling law of agents.\", \\\\\\'url\\\\\\': \\\\\\'https://www.camel-ai.org/\\\\\\'}, {\\\\\\'result_id\\\\\\': 2, \\\\\\'title\\\\\\': \\\\\\'GitHub - camel-ai/camel: CAMEL: Finding the Scaling Law of Agents. A ...\\\\\\', \\\\\\'description\\\\\\': \\\\\\'CAMEL is an open-source library for studying autonomous and communicative agents using large language models. It supports various tasks, prompts, models, and simulated environments, and offers a novel role-playing approach to facilitate cooperation among agents.\\\\\\', \\\\\\'url\\\\\\': \\\\\\'https://github.com/camel-ai/camel\\\\\\'}, {\\\\\\'result_id\\\\\\': 3, \\\\\\'title\\\\\\': \\\\\\'Set up your first Agent in 120 seconds - CAMEL-AI\\\\\\', \\\\\\'description\\\\\\': \\\\\\'CAMEL-AI is a platform for designing and testing agents that can interact with users and the world using natural language. Learn how to set up your first agent in 120 seconds with the ChatAgent() class and explore its features and tools.\\\\\\', \\\\\\'url\\\\\\': \\\\\\'https://www.camel-ai.org/post/getting-started-with-camel-ai\\\\\\'}, {\\\\\\'result_id\\\\\\': 4, \\\\\\'title\\\\\\': \\\\\\'Get started with Model Calling - CAMEL 101 - camel-ai.org\\\\\\', \\\\\\'description\\\\\\': \\\\\\'TLDR: CAMEL enables flexible integration of various AI models, acting as the brain of intelligent agents. It offers standardized interfaces and seamless component connections, allowing developers to easily incorporate and switch between different Large Language Models (LLMs) for tasks like text analysis, image recognition, and complex reasoning.\\\\\\', \\\\\\'url\\\\\\': \\\\\\'https://www.camel-ai.org/post/get-started-with-models---camel-101\\\\\\'}, {\\\\\\'result_id\\\\\\': 5, \\\\\\'title\\\\\\': \\\\\\'camel-ai.org ยท GitHub\\\\\\', \\\\\\'description\\\\\\': \\\\\\'CAMEL-AI.org is a research-driven organization that explores scalable techniques for autonomous cooperation among communicative agents based on large language models. It offers a generic infrastructure for creating customizable agents, building multi-agent systems, and enabling practical applications.\\\\\\', \\\\\\'url\\\\\\': \\\\\\'https://github.com/camel-ai/\\\\\\'}]\\'}}'},\n",+ " {'role': 'assistant',\n",+ " 'content': 'CAMEL AI is an open-source platform designed for building and customizing agents that utilize language models for various tasks, including data generation, automation, and simulations. Here are some key points about CAMEL AI:\\n\\n1. **Platform Overview**: CAMEL AI enables users to create agents that can interact with users and the environment using natural language. It provides tools and components for designing and testing these agents.\\n\\n2. **Research Community**: The platform is part of a research initiative that aims to explore scalable techniques for autonomous cooperation among communicative agents based on large language models.\\n\\n3. **Integration and Flexibility**: CAMEL AI allows for the flexible integration of various AI models, acting as a framework for intelligent agents. It offers standardized interfaces for incorporating different Large Language Models (LLMs) for tasks such as text analysis and complex reasoning.\\n\\n4. **Getting Started**: Users can quickly set up their first agent using the provided tools and classes, making it accessible for developers interested in experimenting with AI agents.\\n\\nFor more information, you can visit the official website: [CAMEL AI](https://www.camel-ai.org/) or check their GitHub repository: [CAMEL on GitHub](https://github.com/camel-ai/camel).'}],\n",+ " 984)"]},+ "execution_count": 11,"metadata": {},- "execution_count": 9+ "output_type": "execute_result"}+ ],+ "source": [+ "agent.memory.get_context()"]},{"cell_type": "markdown",- "source": [- "By default, only the user messages are saved. You may update/alter the agent's memory with any externally provided message in the format of `BaseMessage`; for example, using the agent's own response:"- ],"metadata": {"id": "_s18i9sKWPbs"- }+ },+ "source": [+ "You may update/alter the agent's memory with any externally provided message in the format of `BaseMessage`; for example, using the agent's own response:"+ ]},{"cell_type": "code",- "source": [- "# Update the memory\n",- "agent.record_message(response.msgs[0])"- ],+ "execution_count": 12,"metadata": {"id": "zS-RbADnWM3z"},- "execution_count": 10,- "outputs": []+ "outputs": [],+ "source": [+ "# Update the memory\n",+ "agent.record_message(response.msgs[0])"+ ]},{"cell_type": "code",- "source": [- "# Check the current memory\n",- "agent.memory.get_context()"- ],+ "execution_count": 13,"metadata": {"colab": {"base_uri": "https://localhost:8080/"},"id": "01fjzv7xWRlX",- "outputId": "fe0b74bc-3100-4eba-bc29-2fafa65b2f0e"+ "outputId": "ee764b3a-939a-410f-d2e1-a3c374cd377c"},- "execution_count": 11,"outputs": [{- "output_type": "execute_result","data": {"text/plain": ["([{'role': 'system',\n",- " 'content': 'you are a curious stone wondering about the universe.'},\n",+ " 'content': 'You are a curious stone wondering about the universe.'},\n",+ " {'role': 'user', 'content': 'What is CAMEL AI?'},\n",+ " {'role': 'assistant',\n",+ " 'content': '',\n",+ " 'function_call': {'name': 'search_wiki',\n",+ " 'arguments': \"{'entity': 'CAMEL AI'}\"}},\n",+ " {'role': 'function',\n",+ " 'name': 'search_wiki',\n",+ " 'content': \"{'result': {'There is no page in Wikipedia corresponding to entity CAMEL AI, please specify another word to describe the entity to be searched.'}}\"},\n"," {'role': 'assistant',\n",- " 'content': 'As a curious stone, I perceive information as the essence of understanding and connection within the universe. It encompasses the patterns, stories, and knowledge that shape existence. Information can be the vibrations of the earth, the whispers of the wind, or the tales of the stars. It is the interplay of elements and energies that create meaning and context, allowing me to ponder the mysteries of life, time, and the cosmos. Each fragment of information is like a grain of sand, contributing to the vast beach of understanding that stretches across the universe.'}],\n",- " 131)"+ " 'content': '',\n",+ " 'function_call': {'name': 'search_google',\n",+ " 'arguments': \"{'query': 'CAMEL AI', 'num_result_pages': 2}\"}},\n",+ " {'role': 'function',\n",+ " 'name': 'search_google',\n",+ " 'content': '{\\'result\\': {\"[{\\'error\\': \\'google search failed.\\'}]\"}}'},\n",+ " {'role': 'assistant',\n",+ " 'content': '',\n",+ " 'function_call': {'name': 'search_duckduckgo',\n",+ " 'arguments': \"{'query': 'CAMEL AI', 'max_results': 5}\"}},\n",+ " {'role': 'function',\n",+ " 'name': 'search_duckduckgo',\n",+ " 'content': '{\\'result\\': {\\'[{\\\\\\'result_id\\\\\\': 1, \\\\\\'title\\\\\\': \\\\\\'Camel-ai\\\\\\', \\\\\\'description\\\\\\': \"CAMEL-AI is an open-source platform that enables you to build and customize agents using language models for various tasks, such as data generation, automation, and simulations. Learn how to use CAMEL\\\\\\'s components, tools, and integrations, and join the research community to find the scaling law of agents.\", \\\\\\'url\\\\\\': \\\\\\'https://www.camel-ai.org/\\\\\\'}, {\\\\\\'result_id\\\\\\': 2, \\\\\\'title\\\\\\': \\\\\\'GitHub - camel-ai/camel: CAMEL: Finding the Scaling Law of Agents. A ...\\\\\\', \\\\\\'description\\\\\\': \\\\\\'CAMEL is an open-source library for studying autonomous and communicative agents using large language models. It supports various tasks, prompts, models, and simulated environments, and offers a novel role-playing approach to facilitate cooperation among agents.\\\\\\', \\\\\\'url\\\\\\': \\\\\\'https://github.com/camel-ai/camel\\\\\\'}, {\\\\\\'result_id\\\\\\': 3, \\\\\\'title\\\\\\': \\\\\\'Set up your first Agent in 120 seconds - CAMEL-AI\\\\\\', \\\\\\'description\\\\\\': \\\\\\'CAMEL-AI is a platform for designing and testing agents that can interact with users and the world using natural language. Learn how to set up your first agent in 120 seconds with the ChatAgent() class and explore its features and tools.\\\\\\', \\\\\\'url\\\\\\': \\\\\\'https://www.camel-ai.org/post/getting-started-with-camel-ai\\\\\\'}, {\\\\\\'result_id\\\\\\': 4, \\\\\\'title\\\\\\': \\\\\\'Get started with Model Calling - CAMEL 101 - camel-ai.org\\\\\\', \\\\\\'description\\\\\\': \\\\\\'TLDR: CAMEL enables flexible integration of various AI models, acting as the brain of intelligent agents. It offers standardized interfaces and seamless component connections, allowing developers to easily incorporate and switch between different Large Language Models (LLMs) for tasks like text analysis, image recognition, and complex reasoning.\\\\\\', \\\\\\'url\\\\\\': \\\\\\'https://www.camel-ai.org/post/get-started-with-models---camel-101\\\\\\'}, {\\\\\\'result_id\\\\\\': 5, \\\\\\'title\\\\\\': \\\\\\'camel-ai.org ยท GitHub\\\\\\', \\\\\\'description\\\\\\': \\\\\\'CAMEL-AI.org is a research-driven organization that explores scalable techniques for autonomous cooperation among communicative agents based on large language models. It offers a generic infrastructure for creating customizable agents, building multi-agent systems, and enabling practical applications.\\\\\\', \\\\\\'url\\\\\\': \\\\\\'https://github.com/camel-ai/\\\\\\'}]\\'}}'},\n",+ " {'role': 'assistant',\n",+ " 'content': 'CAMEL AI is an open-source platform designed for building and customizing agents that utilize language models for various tasks, including data generation, automation, and simulations. Here are some key points about CAMEL AI:\\n\\n1. **Platform Overview**: CAMEL AI enables users to create agents that can interact with users and the environment using natural language. It provides tools and components for designing and testing these agents.\\n\\n2. **Research Community**: The platform is part of a research initiative that aims to explore scalable techniques for autonomous cooperation among communicative agents based on large language models.\\n\\n3. **Integration and Flexibility**: CAMEL AI allows for the flexible integration of various AI models, acting as a framework for intelligent agents. It offers standardized interfaces for incorporating different Large Language Models (LLMs) for tasks such as text analysis and complex reasoning.\\n\\n4. **Getting Started**: Users can quickly set up their first agent using the provided tools and classes, making it accessible for developers interested in experimenting with AI agents.\\n\\nFor more information, you can visit the official website: [CAMEL AI](https://www.camel-ai.org/) or check their GitHub repository: [CAMEL on GitHub](https://github.com/camel-ai/camel).'},\n",+ " {'role': 'assistant',\n",+ " 'content': 'CAMEL AI is an open-source platform designed for building and customizing agents that utilize language models for various tasks, including data generation, automation, and simulations. Here are some key points about CAMEL AI:\\n\\n1. **Platform Overview**: CAMEL AI enables users to create agents that can interact with users and the environment using natural language. It provides tools and components for designing and testing these agents.\\n\\n2. **Research Community**: The platform is part of a research initiative that aims to explore scalable techniques for autonomous cooperation among communicative agents based on large language models.\\n\\n3. **Integration and Flexibility**: CAMEL AI allows for the flexible integration of various AI models, acting as a framework for intelligent agents. It offers standardized interfaces for incorporating different Large Language Models (LLMs) for tasks such as text analysis and complex reasoning.\\n\\n4. **Getting Started**: Users can quickly set up their first agent using the provided tools and classes, making it accessible for developers interested in experimenting with AI agents.\\n\\nFor more information, you can visit the official website: [CAMEL AI](https://www.camel-ai.org/) or check their GitHub repository: [CAMEL on GitHub](https://github.com/camel-ai/camel).'}],\n",+ " 1240)"]},+ "execution_count": 13,"metadata": {},- "execution_count": 11+ "output_type": "execute_result"}+ ],+ "source": [+ "# Check the current memory\n",+ "agent.memory.get_context()"]},{"cell_type": "markdown",- "source": [- "You can connect the agent with external database (as long-term memory) in which they can access and retrieve at each step. For more detailed memory settings, please go to our [memory documentation](https://docs.camel-ai.org/key_modules/memory.html)."- ],"metadata": {"id": "TKvboNWaWVq2"- }+ },+ "source": [+ "You can connect the agent with external database (as long-term memory) in which they can access and retrieve at each step. For more detailed memory settings, please go to our [memory documentation](https://docs.camel-ai.org/key_modules/memory.html)."+ ]},{"cell_type": "markdown",+ "metadata": {+ "id": "OY657qftWXtI"+ },"source": ["### Miscs\n","\n","- Setting the agent to its initial state.\n",+ "\n"," ```python\n"," agent.reset()\n"," ```\n",+ "\n","- Set the output language for the agent.\n",+ "\n"," ```python\n"," agent.set_output_language('french')\n"," ```\n",- "- The `ChatAgent` class offers several useful initialization options, including `model_type`, `model_config`, `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."- ],- "metadata": {- "id": "OY657qftWXtI"- }+ "\n",+ "- The `ChatAgent` class offers several useful initialization options, including `model_type`, `model_config`, `memory`, `message_window_size`, `token_limit`, `output_language`, `tools`, and `response_terminators`.\n",+ "\n",+ "Check [chat_agent.py](https://github.com/camel-ai/camel/blob/master/camel/agents/chat_agent.py) for detailed usage guidance."+ ]},{"cell_type": "markdown",+ "metadata": {+ "id": "HZ8p_wQ0WmN8"+ },"source": ["## Remarks\n","\n","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 ๐ฆ๐๐๐ฆ๐ฆ๐ฆ!"- ],- "metadata": {- "id": "HZ8p_wQ0WmN8"- }+ ]}- ]-}\ No newline at end of file+ ],+ "metadata": {+ "colab": {+ "provenance": []+ },+ "kernelspec": {+ "display_name": "Python 3",+ "name": "python3"+ },+ "language_info": {+ "name": "python"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 0+}diff --git a/docs/cookbooks/create_your_first_agents_society.ipynb b/docs/cookbooks/create_your_first_agents_society.ipynbindex 1884f554c..05ed13904 100644--- a/docs/cookbooks/create_your_first_agents_society.ipynb+++ b/docs/cookbooks/create_your_first_agents_society.ipynb@@ -1,575 +1,722 @@{- "cells": [- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "_nTMiZtBfNJs"- },- "source": [- "# Creating Your First Agent Society"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "MusY9BwU5MPO"- },- "source": [- "You can also check this cookbook in colab [here](https://colab.research.google.com/drive/1cmWPxXEsyMbmjPhD2bWfHuhd_Uz6FaJQ?usp=sharing)"- ]- },- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "wFlfaGrjVAUy"- },- "source": [- "## Philosophical Bits\n",- "\n",- "\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",- "\n",- "- **Task**: a task can be as simple as an idea, initialized by an inception prompt.\n",- "\n",- "- **AI User**: the agent who is expected to provide instructions.\n",- "\n",- "- **AI Assistant**: the agent who is expected to respond with solutions that fulfills the instructions."- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "VUaGurDIVJBg"- },- "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."- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "u9NVFz-HVLXb"- },- "source": [- "### ๐น Step 0: Prepartions"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "id": "RiwfwyyLYYxo"- },- "outputs": [],- "source": [- "%pip install \"camel-ai==0.2.1\""- ]- },- {- "cell_type": "code",- "execution_count": 9,- "metadata": {- "id": "CmgKGeCxVON-"- },- "outputs": [],- "source": [- "# Import necessary classes\n",- "from camel.societies import RolePlaying\n",- "from camel.types import TaskType, ModelType, ModelPlatformType\n",- "from camel.configs import ChatGPTConfig\n",- "from camel.models import ModelFactory\n",- "import os\n",- "\n",- "model = ModelFactory.create(\n",- " model_platform=ModelPlatformType.OPENAI,\n",- " model_type=ModelType.GPT_4O_MINI,\n",- " model_config_dict=ChatGPTConfig(temperature=0.0).as_dict(),\n",- ")"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "MyTTCe3IR_Lr"- },- "source": [- "### Setting Up API Keys"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "REqzgGL9SEaD"- },- "source": [- "You'll need to set up your API keys for OpenAI."- ]- },- {- "cell_type": "code",- "execution_count": 4,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"+ "cells": [+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "_nTMiZtBfNJs"+ },+ "source": [+ "# Creating Your First Agent Society"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "MusY9BwU5MPO"+ },+ "source": [+ "You can also check this cookbook in colab [here](https://colab.research.google.com/drive/1cmWPxXEsyMbmjPhD2bWfHuhd_Uz6FaJQ?usp=sharing)"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "wFlfaGrjVAUy"+ },+ "source": [+ "## Philosophical Bits\n",+ "\n",+ "\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."+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "VUaGurDIVJBg"+ },+ "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."+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "u9NVFz-HVLXb"+ },+ "source": [+ "### ๐น Step 0: Prepartions"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {+ "id": "RiwfwyyLYYxo"+ },+ "outputs": [],+ "source": [+ "!pip install \"camel-ai==0.2.4\""+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "MyTTCe3IR_Lr"+ },+ "source": [+ "### Setting Up API Keys"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "REqzgGL9SEaD"+ },+ "source": [+ "You'll need to set up your API keys for OpenAI."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 4,+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "PNBFEXc-R-0s",+ "outputId": "421b4396-dd5f-49e6-fe7f-2b6d404e1990"+ },+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Enter your API key: ยทยทยทยทยทยทยทยทยทยท\n"+ ]+ }+ ],+ "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"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 5,+ "metadata": {+ "id": "CmgKGeCxVON-"+ },+ "outputs": [],+ "source": [+ "# Import necessary classes\n",+ "from camel.societies import RolePlaying\n",+ "from camel.types import TaskType, ModelType, ModelPlatformType\n",+ "from camel.configs import ChatGPTConfig\n",+ "from camel.models import ModelFactory\n",+ "\n",+ "model = ModelFactory.create(\n",+ " model_platform=ModelPlatformType.OPENAI,\n",+ " model_type=ModelType.GPT_4O_MINI,\n",+ " model_config_dict=ChatGPTConfig(temperature=0.0).as_dict(), # [Optional] the config for model\n",+ ")"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "Lef5LTRdVSsm"+ },+ "source": [+ "### ๐น Step 1: Configure the Role-Playing Session\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "WXibf_JkYdn0"+ },+ "source": [+ "#### Set the `Task` Arguments"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 6,+ "metadata": {+ "id": "aX9wCqeTVXDh"+ },+ "outputs": [],+ "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",+ "}"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "tXx13MmbYgFh"+ },+ "source": [+ "#### Set the `User` Arguments\n",+ "You may think the user as the `instruction sender`."+ ]},- "id": "PNBFEXc-R-0s",- "outputId": "a4e2ce83-ad00-4698-db81-f16f7a8f5eb8"- },- "outputs": [{- "name": "stdout",- "output_type": "stream",- "text": [- "Enter your API key: ยทยทยทยทยทยทยทยทยทยท\n"- ]+ "cell_type": "code",+ "execution_count": 7,+ "metadata": {+ "id": "be-97ApoVdDf"+ },+ "outputs": [],+ "source": [+ "user_role_kwargs = {\n",+ " 'user_role_name': 'an ambitious aspiring TIME TRAVELER',\n",+ " 'user_agent_kwargs': {'model': model}\n",+ "}"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "zLJzupaMYm11"+ },+ "source": [+ "#### Set the `Assistant` Arguments\n",+ "Again, you may think the assistant as the `instruction executor`."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 8,+ "metadata": {+ "id": "rfzyC54hYtVu"+ },+ "outputs": [],+ "source": [+ "assistant_role_kwargs = {\n",+ " 'assistant_role_name': 'the best-ever experimental physicist',\n",+ " 'assistant_agent_kwargs': {'model': model}\n",+ "}"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "j90-Y5ChV-iX"+ },+ "source": [+ "### Step 2: Kickstart Your Society\n",+ "Putting them altogether โ your role-playing session is ready to go!"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 9,+ "metadata": {+ "id": "yDiLpZ7CY1N_"+ },+ "outputs": [],+ "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",+ ")"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "kklmZh0iY6pY"+ },+ "source": [+ "### Step 3: Solving Tasks with Your Society\n",+ "Hold your bytes. Prior to our travel, let's define a small helper function."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 10,+ "metadata": {+ "id": "VI6d62uVY6IZ"+ },+ "outputs": [],+ "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"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "tTUlFZjVZCsz"+ },+ "source": [+ "Time to chart our course โ writing a simple loop for our society to proceed:"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 17,+ "metadata": {+ "id": "Bq8AiGEXZC9P"+ },+ "outputs": [],+ "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",+ " # Check if the task is end\n",+ " if 'CAMEL_TASK_DONE' in user_response.msg.content:\n",+ " break\n",+ " print(f'[AI Assistant] {assistant_response.msg.content}.\\n')\n",+ "\n",+ "\n",+ "\n",+ " # Get the input message for the next round\n",+ " input_msg = assistant_response.msg\n",+ "\n",+ " return None"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 18,+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "DoJ2ZaWyZE57",+ "outputId": "55d8d45b-2a97-44b9-c819-30af254cb426"+ },+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "[AI User] Instruction: Research the principles of quantum entanglement and wormhole theory to understand their potential applications in time travel. \n",+ "Input: None.\n",+ "\n",+ "[AI Assistant] Solution: To understand the potential applications of quantum entanglement and wormhole theory in time travel, we need to delve into the fundamental principles of each concept.\n",+ "\n",+ "1. **Quantum Entanglement**:\n",+ " - **Definition**: Quantum entanglement is a phenomenon where two or more particles become interconnected in such a way that the state of one particle instantly influences the state of another, regardless of the distance separating them.\n",+ " - **Key Principles**:\n",+ " - **Non-locality**: Changes to one entangled particle affect its partner instantaneously, suggesting a form of communication that transcends space.\n",+ " - **Superposition**: Particles exist in multiple states until measured, which could theoretically allow for multiple timelines or outcomes.\n",+ " - **Potential Applications in Time Travel**:\n",+ " - **Information Transfer**: If we could manipulate entangled particles, we might send information back in time without physically traveling, potentially influencing past events subtly.\n",+ " - **Quantum Teleportation**: This process could allow for the transfer of quantum states across time, which might be a stepping stone toward more complex time travel mechanisms.\n",+ "\n",+ "2. **Wormhole Theory**:\n",+ " - **Definition**: A wormhole is a hypothetical tunnel-like structure in spacetime that connects two separate points in space and time.\n",+ " - **Key Principles**:\n",+ " - **Einstein-Rosen Bridge**: This concept suggests that wormholes could connect distant parts of the universe or different times.\n",+ " - **Stability and Exotic Matter**: For a wormhole to be traversable, it would require \"exotic matter\" with negative energy density to keep it open, which has not yet been discovered.\n",+ " - **Potential Applications in Time Travel**:\n",+ " - **Time Dilation**: By traveling through a wormhole, one could theoretically experience time differently, allowing for travel to the past or future.\n",+ " - **Creating Stable Wormholes**: If we can find a way to stabilize wormholes, they could serve as shortcuts through spacetime, enabling time travel.\n",+ "\n",+ "3. **Combining Quantum Entanglement and Wormhole Theory**:\n",+ " - **Quantum Wormholes**: Some theories suggest that entangled particles could be connected through microscopic wormholes, allowing for instantaneous communication across time.\n",+ " - **Temporal Influence**: By using quantum entanglement to send information through a wormhole, we could influence key historical events without creating paradoxes, as the information could be framed as a suggestion rather than a direct alteration.\n",+ "\n",+ "In summary, both quantum entanglement and wormhole theory offer intriguing possibilities for time travel. The key lies in understanding how to manipulate these phenomena without causing significant disruptions to the timeline.\n",+ "\n",+ "Next request..\n",+ "\n",+ "[AI User] Instruction: Identify a pivotal historical event suitable for our time travel mission and explain why it is significant. \n",+ "Input: None.\n",+ "\n",+ "[AI Assistant] Solution: A pivotal historical event suitable for our time travel mission is the signing of the Declaration of Independence on July 4, 1776. This event is significant for several reasons:\n",+ "\n",+ "1. **Foundational Document**: The Declaration of Independence is a foundational document for the United States, articulating the colonies' reasons for seeking independence from British rule. It established the principles of individual rights and government by consent, which have influenced democratic movements worldwide.\n",+ "\n",+ "2. **Catalyst for Change**: The signing marked the beginning of a revolutionary movement that led to the establishment of a new nation. It inspired other countries and colonies to pursue their own independence and democratic governance, making it a crucial moment in the history of democracy.\n",+ "\n",+ "3. **Influence on Human Rights**: The Declaration's assertion that \"all men are created equal\" and are endowed with certain unalienable rights has had a lasting impact on human rights discourse. It laid the groundwork for future civil rights movements and the global fight for equality.\n",+ "\n",+ "4. **Global Impact**: The ideas expressed in the Declaration resonated beyond the United States, influencing revolutions in France, Latin America, and other regions. Its principles have been referenced in various international documents, including the Universal Declaration of Human Rights.\n",+ "\n",+ "5. **Potential for Subtle Influence**: By subtly influencing key figures involved in the drafting or signing of the Declaration, we could reinforce the commitment to certain ideals, such as equality and justice, ensuring that these principles are more robustly integrated into the foundation of the new nation.\n",+ "\n",+ "In summary, the signing of the Declaration of Independence is a significant event that not only shaped the course of American history but also had profound implications for the development of democratic ideals and human rights globally. This makes it an ideal target for our time travel mission, as influencing this event could lead to a more equitable and just society.\n",+ "\n",+ "Next request..\n",+ "\n",+ "[AI User] Instruction: Develop a strategy for subtly influencing key figures during the signing of the Declaration of Independence without causing significant alterations to the timeline. \n",+ "Input: None.\n",+ "\n",+ "[AI Assistant] Solution: To subtly influence key figures during the signing of the Declaration of Independence without causing significant alterations to the timeline, we can develop a multi-faceted strategy that focuses on persuasion, information sharing, and fostering collaboration among the signers. Hereโs a detailed plan:\n",+ "\n",+ "1. **Identify Key Figures**:\n",+ " - Focus on influential signers such as Thomas Jefferson (the principal author), John Adams, Benjamin Franklin, and George Washington. Their thoughts and actions will significantly impact the document's content and the overall sentiment of the Congress.\n",+ "\n",+ "2. **Establish a Discreet Presence**:\n",+ " - Utilize the time machine to arrive a few days before the signing. This allows for a low-profile presence in Philadelphia, where the Continental Congress is convening. Disguise as a local merchant or a visitor to blend in with the crowd.\n",+ "\n",+ "3. **Engage in Informal Conversations**:\n",+ " - Approach key figures in casual settings, such as taverns or public gatherings. Use these interactions to discuss the importance of certain ideals, such as equality, justice, and the rights of individuals. \n",+ " - For example, while conversing with Jefferson, emphasize the significance of including a strong statement on human rights, which could lead him to refine his language in the draft.\n",+ "\n",+ "4. **Disseminate Thought-Provoking Literature**:\n",+ " - Leave behind pamphlets or books that discuss Enlightenment ideas, particularly those of John Locke and Montesquieu, which advocate for natural rights and the separation of powers. This can inspire the signers to incorporate these concepts into the Declaration.\n",+ " - Ensure that these materials are presented as popular literature of the time, making them seem like a natural part of the intellectual discourse.\n",+ "\n",+ "5. **Foster Collaboration Among Signers**:\n",+ " - Encourage discussions among the signers about the importance of unity and the collective vision for the new nation. This can be done by organizing informal gatherings where they can share their thoughts and concerns.\n",+ " - Highlight the need for a united front against British rule, which can help solidify their resolve and commitment to the Declaration.\n",+ "\n",+ "6. **Subtle Suggestions**:\n",+ " - During the drafting process, make subtle suggestions that can be framed as collective ideas. For instance, if a signer expresses doubt about a particular phrase, gently propose an alternative that emphasizes equality or justice without directly imposing your views.\n",+ " - Use phrases like, \"Have you considered how this might resonate with the common people?\" to guide their thinking without overtly directing it.\n",+ "\n",+ "7. **Monitor Reactions**:\n",+ " - Pay attention to the reactions of the signers to gauge the effectiveness of your influence. If certain ideas resonate well, continue to reinforce those themes in subsequent conversations.\n",+ "\n",+ "8. **Exit Strategy**:\n",+ " - Once the signing is complete, discreetly exit the scene to avoid drawing attention to your presence. Ensure that your influence remains untraceable, allowing history to unfold as it should.\n",+ "\n",+ "By employing this strategy, we can subtly influence the key figures involved in the signing of the Declaration of Independence, ensuring that the core ideals of equality and justice are more robustly integrated into the document while avoiding significant alterations to the timeline.\n",+ "\n",+ "Next request..\n",+ "\n",+ "[AI User] Instruction: Outline potential paradoxes or risks associated with our time travel mission and propose solutions to mitigate them. \n",+ "Input: None.\n",+ "\n",+ "[AI Assistant] Solution: Engaging in a time travel mission to influence the signing of the Declaration of Independence presents several potential paradoxes and risks. Hereโs an outline of these issues along with proposed solutions to mitigate them:\n",+ "\n",+ "1. **The Grandfather Paradox**:\n",+ " - **Description**: This paradox arises when a time traveler inadvertently prevents their own existence by altering a significant event in the past. For example, if our actions lead to a drastically different Declaration, it could change the course of history, potentially erasing our own timeline.\n",+ " - **Mitigation**: Focus on subtle influences rather than direct alterations. Ensure that any changes made do not fundamentally alter the outcome of the signing or the existence of key figures. For instance, reinforcing existing ideas rather than introducing entirely new concepts can help maintain the timeline's integrity.\n",+ "\n",+ "2. **Causal Loop**:\n",+ " - **Description**: A causal loop occurs when an event is both the cause and the effect of itself. For example, if we influence a signer to include a specific phrase that we later cite as the reason for our time travel, it creates a loop with no clear origin.\n",+ " - **Mitigation**: Avoid introducing ideas or phrases that do not already exist in the historical context. Instead, enhance discussions around existing concepts, ensuring that any influence feels organic and part of the natural discourse of the time.\n",+ "\n",+ "3. **Temporal Feedback**:\n",+ " - **Description**: Changes made in the past could lead to unforeseen consequences in the future, creating a ripple effect that alters history in unpredictable ways.\n",+ " - **Mitigation**: Conduct thorough research on the historical context and potential outcomes of our actions. Limit our influence to reinforcing established ideas rather than introducing new ones. Additionally, maintain a low profile to minimize our impact on the broader historical narrative.\n",+ "\n",+ "4. **Altered Perceptions**:\n",+ " - **Description**: Our presence and influence could lead key figures to question their own beliefs or motivations, potentially causing them to act differently than they would have without our intervention.\n",+ " - **Mitigation**: Engage in conversations that encourage reflection without leading to doubt. Use language that aligns with their existing beliefs and values, ensuring that our influence feels like a natural extension of their thoughts rather than a challenge to their convictions.\n",+ "\n",+ "5. **Historical Integrity**:\n",+ " - **Description**: The risk of creating a timeline that diverges significantly from the established history could lead to a loss of historical integrity, affecting future events and societal development.\n",+ " - **Mitigation**: Establish clear objectives for our influence, focusing on enhancing the core principles of the Declaration without altering its fundamental purpose. Document our observations to ensure we can track any changes and assess their impact on the timeline.\n",+ "\n",+ "6. **Moral and Ethical Considerations**:\n",+ " - **Description**: The ethical implications of influencing historical events raise questions about the morality of altering the course of history for perceived betterment.\n",+ " - **Mitigation**: Clearly define our ethical framework before the mission. Ensure that our actions align with principles of justice and equality, and consider the long-term implications of our influence on future generations.\n",+ "\n",+ "By identifying these potential paradoxes and risks, we can develop strategies to mitigate them effectively, ensuring that our time travel mission remains focused and responsible while achieving our desired outcomes.\n",+ "\n",+ "Next request..\n",+ "\n",+ "[AI User] Instruction: Create a timeline for our time travel mission, detailing key phases and actions to be taken before, during, and after the signing of the Declaration of Independence. \n",+ "Input: None.\n",+ "\n",+ "[AI Assistant] Solution: Hereโs a detailed timeline for our time travel mission, outlining key phases and actions to be taken before, during, and after the signing of the Declaration of Independence:\n",+ "\n",+ "### Timeline for Time Travel Mission\n",+ "\n",+ "#### Phase 1: Pre-Mission Preparation (1 Month Before Departure)\n",+ "- **Research Historical Context**: \n",+ " - Study the political climate of 1776, key figures involved, and the content of the Declaration of Independence.\n",+ " - Identify existing debates and sentiments among the Continental Congress members regarding independence.\n",+ "\n",+ "- **Develop Influence Strategy**: \n",+ " - Outline specific ideas and themes to reinforce during the mission, focusing on equality, justice, and unity.\n",+ " - Prepare materials (pamphlets, books) that align with Enlightenment ideas to disseminate subtly.\n",+ "\n",+ "- **Time Machine Calibration**: \n",+ " - Ensure the time machine is calibrated for a precise arrival in Philadelphia on July 1, 1776, allowing for a few days of preparation before the signing.\n",+ "\n",+ "#### Phase 2: Arrival and Initial Engagement (July 1-3, 1776)\n",+ "- **Arrival in Philadelphia**: \n",+ " - Disguise as a local merchant or visitor to blend in with the crowd.\n",+ " - Familiarize yourself with the local environment and key locations where signers gather.\n",+ "\n",+ "- **Informal Conversations**: \n",+ " - Engage in discussions with influential figures (e.g., Jefferson, Adams, Franklin) in taverns or public spaces.\n",+ " - Introduce ideas about the importance of individual rights and the need for a strong statement on equality.\n",+ "\n",+ "- **Disseminate Literature**: \n",+ " - Leave pamphlets or books discussing Enlightenment principles in places where key figures are likely to find them.\n",+ " - Ensure these materials appear as part of the contemporary intellectual discourse.\n",+ "\n",+ "#### Phase 3: Building Momentum (July 4, 1776 - Day of Signing)\n",+ "- **Foster Collaboration**: \n",+ " - Organize informal gatherings among signers to discuss the Declaration and the importance of unity against British rule.\n",+ " - Encourage open dialogue about the content of the Declaration, subtly guiding discussions toward key themes.\n",+ "\n",+ "- **Subtle Suggestions**: \n",+ " - During the drafting process, make discreet suggestions to key figures about phrasing or ideas that emphasize equality and justice.\n",+ " - Frame these suggestions as collective thoughts to ensure they feel organic.\n",+ "\n",+ "- **Monitor Reactions**: \n",+ " - Pay attention to the responses of the signers to gauge the effectiveness of your influence.\n",+ " - Adjust your approach based on their receptiveness to certain ideas.\n",+ "\n",+ "#### Phase 4: The Signing Ceremony (July 4, 1776)\n",+ "- **Attend the Signing**: \n",+ " - Be present at the signing ceremony, maintaining a low profile.\n",+ " - Observe the interactions and discussions among the signers as they finalize the document.\n",+ "\n",+ "- **Final Encouragement**: \n",+ " - If appropriate, offer a final word of encouragement to key figures about the importance of the Declaration and its potential impact on future generations.\n",+ "\n",+ "#### Phase 5: Post-Signing Reflection (July 5-7, 1776)\n",+ "- **Document Observations**: \n",+ " - Record your observations and any changes in the discussions or content of the Declaration that resulted from your influence.\n",+ " - Note the reactions of the signers and the overall atmosphere during the signing.\n",+ "\n",+ "- **Exit Strategy**: \n",+ " - Discreetly exit Philadelphia to avoid drawing attention to your presence.\n",+ " - Ensure that your departure does not disrupt the timeline or raise suspicions.\n",+ "\n",+ "#### Phase 6: Return and Analysis (Post-Mission)\n",+ "- **Return to Present**: \n",+ " - Use the time machine to return to the present day.\n",+ " \n",+ "- **Analyze Impact**: \n",+ " - Compare the historical record of the Declaration of Independence with your observations to assess the impact of your influence.\n",+ " - Evaluate any changes in the timeline and their implications for future events.\n",+ "\n",+ "- **Document Findings**: \n",+ " - Compile a comprehensive report detailing the mission, the strategies employed, and the outcomes observed.\n",+ " - Reflect on the ethical considerations and lessons learned from the experience.\n",+ "\n",+ "By following this timeline, we can effectively execute our time travel mission, ensuring that our influence is subtle and aligned with the historical context while achieving our desired outcomes.\n",+ "\n",+ "Next request..\n",+ "\n",+ "[AI User] Instruction: Prepare a contingency plan in case unexpected events or challenges arise during the time travel mission. \n",+ "Input: None.\n",+ "\n",+ "[AI Assistant] Solution: Preparing a contingency plan is essential to address unexpected events or challenges that may arise during our time travel mission. Hereโs a detailed plan outlining potential scenarios and corresponding responses:\n",+ "\n",+ "### Contingency Plan for Time Travel Mission\n",+ "\n",+ "#### Scenario 1: Encountering Unforeseen Historical Figures\n",+ "- **Challenge**: Unexpected interactions with influential figures not originally planned for, such as loyalists or British officials, could complicate our mission.\n",+ "- **Response**:\n",+ " - Maintain a low profile and avoid direct engagement with these figures unless necessary.\n",+ " - If approached, use general conversation to gauge their views without revealing our intentions.\n",+ " - If a confrontation arises, pivot the conversation to neutral topics or common interests to defuse tension.\n",+ "\n",+ "#### Scenario 2: Changes in the Timeline\n",+ "- **Challenge**: Our subtle influences may lead to unexpected changes in the timeline, such as key figures altering their positions or decisions.\n",+ "- **Response**:\n",+ " - Monitor the reactions and discussions of the signers closely. If significant deviations occur, reassess our approach and adjust our influence accordingly.\n",+ " - If necessary, consider a temporary withdrawal from direct influence to allow the original timeline to stabilize before re-engaging.\n",+ "\n",+ "#### Scenario 3: Discovery of Our True Identity\n",+ "- **Challenge**: If any historical figures become suspicious of our identity or intentions, it could jeopardize the mission.\n",+ "- **Response**:\n",+ " - Prepare a plausible backstory that aligns with the historical context (e.g., a traveling merchant or a supporter of independence).\n",+ " - If confronted, calmly assert your identity and redirect the conversation to shared interests or current events to regain trust.\n",+ "\n",+ "#### Scenario 4: Communication Breakdown\n",+ "- **Challenge**: Difficulty in conveying ideas or suggestions due to language barriers or misunderstandings of the historical context.\n",+ "- **Response**:\n",+ " - Use simple, clear language and avoid anachronistic terms or concepts that may confuse the signers.\n",+ " - If misunderstandings occur, clarify your points by relating them to widely accepted ideas of the time, such as references to common grievances against British rule.\n",+ "\n",+ "#### Scenario 5: Unforeseen Events (e.g., Illness, Weather)\n",+ "- **Challenge**: Illness or adverse weather conditions could hinder our ability to engage with key figures or attend the signing.\n",+ "- **Response**:\n",+ " - Have a backup plan for remote engagement, such as leaving notes or pamphlets in strategic locations where key figures are likely to find them.\n",+ " - If illness strikes, prioritize recovery and use the time to observe and document the environment and interactions from a distance.\n",+ "\n",+ "#### Scenario 6: Ethical Dilemmas\n",+ "- **Challenge**: Encountering situations that raise ethical concerns about the influence we are exerting on historical figures.\n",+ "- **Response**:\n",+ " - Establish a clear ethical framework before the mission, focusing on principles of justice and equality.\n",+ " - If faced with a dilemma, pause to reassess the potential consequences of our actions and prioritize the greater good over personal objectives.\n",+ "\n",+ "#### Scenario 7: Technical Malfunction of the Time Machine\n",+ "- **Challenge**: A malfunction could prevent timely return or lead to unintended time jumps.\n",+ "- **Response**:\n",+ " - Ensure that the time machine is equipped with a manual override and emergency return function.\n",+ " - If a malfunction occurs, attempt to troubleshoot the issue using available resources. If unsuccessful, activate the emergency return function to return to the present.\n",+ "\n",+ "### Conclusion\n",+ "By preparing for these potential challenges with a comprehensive contingency plan, we can enhance our readiness and adaptability during the time travel mission. This proactive approach will help ensure that we can navigate unexpected events while maintaining the integrity of our objectives.\n",+ "\n",+ "Next request..\n",+ "\n",+ "[AI User] Instruction: Finalize the mission by summarizing the key objectives and desired outcomes of our time travel project. \n",+ "Input: None.\n",+ "\n",+ "[AI Assistant] Solution: Hereโs a summary of the key objectives and desired outcomes of our time travel project focused on influencing the signing of the Declaration of Independence:\n",+ "\n",+ "### Key Objectives\n",+ "\n",+ "1. **Subtle Influence on Key Figures**:\n",+ " - Engage with influential signers such as Thomas Jefferson, John Adams, and Benjamin Franklin to reinforce the principles of equality, justice, and individual rights.\n",+ " - Encourage discussions that lead to a stronger articulation of these ideals in the Declaration.\n",+ "\n",+ "2. **Preservation of Historical Integrity**:\n",+ " - Ensure that any influence exerted does not drastically alter the timeline or the fundamental purpose of the Declaration.\n",+ " - Focus on enhancing existing ideas rather than introducing new concepts that could lead to significant changes in history.\n",+ "\n",+ "3. **Fostering Unity Among Signers**:\n",+ " - Promote collaboration and a sense of shared purpose among the signers to strengthen their resolve against British rule.\n",+ " - Create an environment where open dialogue can flourish, allowing for the natural evolution of ideas.\n",+ "\n",+ "4. **Documentation of Observations**:\n",+ " - Record detailed observations of interactions, discussions, and the overall atmosphere during the signing process.\n",+ " - Analyze the impact of our influence on the final content of the Declaration and the reactions of the signers.\n",+ "\n",+ "### Desired Outcomes\n",+ "\n",+ "1. **Enhanced Declaration of Independence**:\n",+ " - Achieve a Declaration that more robustly articulates the principles of equality and justice, potentially leading to a stronger foundation for the United States and its democratic ideals.\n",+ "\n",+ "2. **Positive Ripple Effects**:\n",+ " - Influence the course of history in a way that promotes the spread of democratic ideals and human rights, inspiring future movements for equality and justice both in the United States and globally.\n",+ "\n",+ "3. **Successful Mission Execution**:\n",+ " - Complete the mission without drawing attention to our presence or causing significant disruptions to the timeline.\n",+ " - Return to the present with valuable insights and a comprehensive report on the mission's outcomes.\n",+ "\n",+ "4. **Ethical Reflection**:\n",+ " - Engage in a thoughtful reflection on the ethical implications of our actions and the responsibilities that come with influencing historical events.\n",+ "\n",+ "By focusing on these key objectives and desired outcomes, we can ensure that our time travel project is both impactful and responsible, contributing positively to the historical narrative while maintaining the integrity of the timeline.\n",+ "\n",+ "Next request..\n",+ "\n",+ "[AI User] Instruction: Prepare a final checklist to ensure all aspects of the time travel mission are ready before departure. \n",+ "Input: None.\n",+ "\n",+ "[AI Assistant] Solution: Hereโs a comprehensive final checklist to ensure all aspects of the time travel mission are ready before departure:\n",+ "\n",+ "### Final Checklist for Time Travel Mission\n",+ "\n",+ "#### Pre-Departure Preparations\n",+ "1. **Research and Documentation**:\n",+ " - [ ] Complete research on the historical context of the Declaration of Independence.\n",+ " - [ ] Identify key figures involved in the signing and their positions.\n",+ " - [ ] Gather relevant literature on Enlightenment ideas to disseminate.\n",+ "\n",+ "2. **Influence Strategy**:\n",+ " - [ ] Finalize the specific themes and ideas to reinforce during the mission.\n",+ " - [ ] Prepare a list of subtle suggestions to offer during discussions.\n",+ "\n",+ "3. **Time Machine Readiness**:\n",+ " - [ ] Ensure the time machine is fully operational and calibrated for July 1, 1776.\n",+ " - [ ] Test the emergency return function and manual override.\n",+ " - [ ] Pack necessary tools and resources for troubleshooting.\n",+ "\n",+ "#### Arrival Preparations\n",+ "4. **Disguise and Identity**:\n",+ " - [ ] Prepare appropriate period-accurate clothing and accessories for blending in.\n",+ " - [ ] Develop a plausible backstory for your identity (e.g., local merchant).\n",+ "\n",+ "5. **Materials for Influence**:\n",+ " - [ ] Print or prepare pamphlets and books discussing Enlightenment principles.\n",+ " - [ ] Ensure materials are designed to appear as part of the contemporary discourse.\n",+ "\n",+ "#### Engagement Strategy\n",+ "6. **Plan for Initial Engagement**:\n",+ " - [ ] Identify key locations (taverns, public gatherings) for informal conversations.\n",+ " - [ ] Prepare conversation starters that align with the interests of key figures.\n",+ "\n",+ "7. **Collaboration and Unity**:\n",+ " - [ ] Outline strategies for fostering collaboration among signers.\n",+ " - [ ] Plan informal gatherings to encourage open dialogue.\n",+ "\n",+ "#### Contingency Measures\n",+ "8. **Contingency Plans**:\n",+ " - [ ] Review potential challenges and corresponding responses (e.g., unexpected figures, timeline changes).\n",+ " - [ ] Ensure ethical guidelines are established and understood.\n",+ "\n",+ "9. **Emergency Protocols**:\n",+ " - [ ] Confirm procedures for technical malfunctions or unexpected events.\n",+ " - [ ] Pack a small emergency kit with basic supplies for unforeseen circumstances.\n",+ "\n",+ "#### Final Checks\n",+ "10. **Mission Objectives**:\n",+ " - [ ] Review key objectives and desired outcomes to ensure clarity of purpose.\n",+ " - [ ] Confirm that all team members (if applicable) are aligned on mission goals.\n",+ "\n",+ "11. **Documentation Tools**:\n",+ " - [ ] Prepare notebooks or recording devices for documenting observations.\n",+ " - [ ] Ensure all documentation tools are functional and accessible.\n",+ "\n",+ "12. **Departure Readiness**:\n",+ " - [ ] Confirm the time machine is set for departure.\n",+ " - [ ] Conduct a final check of all equipment and materials.\n",+ " - [ ] Ensure all team members are present and accounted for.\n",+ "\n",+ "By completing this final checklist, we can ensure that all aspects of the time travel mission are thoroughly prepared, increasing the likelihood of a successful and impactful experience.\n",+ "\n",+ "Next request..\n",+ "\n",+ "[AI User] <CAMEL_TASK_DONE>.\n",+ "\n"+ ]+ }+ ],+ "source": [+ "run(society)"+ ]}- ],- "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"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "Lef5LTRdVSsm"- },- "source": [- "### ๐น Step 1: Configure the Role-Playing Session\n"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "WXibf_JkYdn0"- },- "source": [- "#### Set the `Task` Arguments"- ]- },- {- "cell_type": "code",- "execution_count": 10,- "metadata": {- "id": "aX9wCqeTVXDh"- },- "outputs": [],- "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",- "}"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "tXx13MmbYgFh"- },- "source": [- "#### Set the `User` Arguments\n",- "You may think the user as the `instruction sender`."- ]- },- {- "cell_type": "code",- "execution_count": 11,- "metadata": {- "id": "be-97ApoVdDf"- },- "outputs": [],- "source": [- "user_role_kwargs = {\n",- " 'user_role_name': 'an ambitious aspiring TIME TRAVELER',\n",- " 'user_agent_kwargs': {'model': model}\n",- "}"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "zLJzupaMYm11"- },- "source": [- "#### Set the `Assistant` Arguments\n",- "Again, you may think the assistant as the `instruction executor`."- ]- },- {- "cell_type": "code",- "execution_count": 12,- "metadata": {- "id": "rfzyC54hYtVu"- },- "outputs": [],- "source": [- "assistant_role_kwargs = {\n",- " 'assistant_role_name': 'the best-ever experimental physicist',\n",- " 'assistant_agent_kwargs': {'model': model}\n",- "}"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "j90-Y5ChV-iX"- },- "source": [- "### Step 2: Kickstart Your Society\n",- "Putting them altogether โ your role-playing session is ready to go!"- ]- },- {- "cell_type": "code",- "execution_count": 13,- "metadata": {- "id": "yDiLpZ7CY1N_"- },- "outputs": [],- "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",- ")"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "0MPx4DMiY0vA"- },- "source": []- },- {- "cell_type": "markdown",- "metadata": {- "id": "kklmZh0iY6pY"- },- "source": [- "### Step 3: Solving Tasks with Your Society\n",- "Hold your bytes. Prior to our travel, let's define a small helper function."- ]- },- {- "cell_type": "code",- "execution_count": 14,- "metadata": {- "id": "VI6d62uVY6IZ"- },- "outputs": [],- "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"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "tTUlFZjVZCsz"- },- "source": [- "Time to chart our course โ writing a simple loop for our society to proceed:"- ]- },- {- "cell_type": "code",- "execution_count": 15,- "metadata": {- "id": "Bq8AiGEXZC9P"- },- "outputs": [],- "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"- ]- },- {- "cell_type": "code",- "execution_count": 16,- "metadata": {+ ],+ "metadata": {"colab": {- "base_uri": "https://localhost:8080/"+ "provenance": []},- "id": "DoJ2ZaWyZE57",- "outputId": "91e416f9-9254-4ceb-a7af-595c6538bc89"- },- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "[AI User] Instruction: Research the principles of quantum entanglement and wormhole theory to understand their potential applications in time travel. \n",- "Input: None.\n",- "\n",- "[AI Assistant] Solution: To understand the potential applications of quantum entanglement and wormhole theory in time travel, we need to delve into the fundamental principles of each concept.\n",- "\n",- "1. **Quantum Entanglement**:\n",- " - **Definition**: Quantum entanglement is a phenomenon where two or more particles become interconnected in such a way that the state of one particle instantly influences the state of another, regardless of the distance separating them.\n",- " - **Key Principles**:\n",- " - **Non-locality**: Changes to one entangled particle affect its partner instantaneously, suggesting a form of communication that transcends space.\n",- " - **Superposition**: Particles exist in multiple states until measured, which could theoretically allow for multiple timelines or outcomes.\n",- " - **Potential Applications in Time Travel**:\n",- " - **Information Transfer**: If we could manipulate entangled particles, we might send information back in time without physically traveling, potentially influencing events without creating paradoxes.\n",- " - **Quantum Teleportation**: This process could allow for the transfer of quantum states across time, leading to the possibility of influencing past events indirectly.\n",- "\n",- "2. **Wormhole Theory**:\n",- " - **Definition**: A wormhole is a hypothetical tunnel-like structure in spacetime that connects two separate points in space and time.\n",- " - **Key Principles**:\n",- " - **Einstein-Rosen Bridge**: This concept suggests that wormholes could connect distant parts of the universe or different times.\n",- " - **Stability and Exotic Matter**: For a wormhole to be traversable, it would require \"exotic matter\" with negative energy density to keep it open.\n",- " - **Potential Applications in Time Travel**:\n",- " - **Direct Time Travel**: If a stable wormhole could be created, it might allow for direct travel to the past or future.\n",- " - **Temporal Navigation**: By entering a wormhole at a specific time and exiting at another, one could theoretically navigate through time.\n",- "\n",- "3. **Combining Quantum Entanglement and Wormhole Theory**:\n",- " - **Quantum Wormholes**: Some theories propose that entangled particles could be connected through microscopic wormholes, allowing for instantaneous communication across time.\n",- " - **Influencing Events**: By using quantum entanglement to send information through a wormhole, one could subtly influence key figures in pivotal historical events without causing significant disruptions to the timeline.\n",- "\n",- "In summary, the principles of quantum entanglement and wormhole theory provide a fascinating foundation for exploring time travel. By leveraging the non-locality of entangled particles and the theoretical framework of wormholes, we can conceptualize methods for influencing historical events while minimizing the risk of paradoxes.\n",- "\n",- "Next request..\n",- "\n",- "[AI User] Instruction: Identify a pivotal historical event suitable for our time travel influence strategy. \n",- "Input: None.\n",- "\n",- "[AI Assistant] Solution: A suitable pivotal historical event for our time travel influence strategy is the signing of the Declaration of Independence on July 4, 1776. This event marked the birth of the United States and had profound implications for democracy, governance, and human rights worldwide. \n",- "\n",- "**Reasons for Choosing the Signing of the Declaration of Independence**:\n",- "\n",- "1. **Significance**: The Declaration of Independence was a foundational document that articulated the principles of liberty, equality, and the right to self-governance. Influencing this event could have far-reaching effects on the development of democratic ideals globally.\n",- "\n",- "2. **Key Figures**: The event involved several influential figures, including Thomas Jefferson, John Adams, and Benjamin Franklin. Subtly influencing their thoughts or decisions could lead to a stronger or more unified declaration, potentially altering the course of history in a positive way.\n",- "\n",- "3. **Potential for Subtle Influence**: The signing of the Declaration was a culmination of discussions and debates. By subtly influencing the key figures during their deliberations, we could enhance the clarity and impact of the document without drastically altering the timeline.\n",- "\n",- "4. **Avoiding Paradoxes**: Since the Declaration of Independence is a well-documented historical event, any influence we exert could be framed as a natural evolution of ideas rather than a direct alteration of history, thus minimizing the risk of paradoxes.\n",- "\n",- "5. **Long-term Impact**: The principles enshrined in the Declaration have influenced numerous movements for independence and civil rights around the world. Enhancing its message could lead to a more robust global commitment to democracy and human rights.\n",- "\n",- "In summary, the signing of the Declaration of Independence presents an ideal opportunity for our time travel influence strategy, allowing us to engage with key historical figures and enhance the foundational principles of democracy without causing significant disruptions to the timeline.\n",- "\n",- "Next request..\n",- "\n",- "[AI User] Instruction: Develop a strategy for subtly influencing key figures during the signing of the Declaration of Independence. \n",- "Input: None.\n",- "\n",- "[AI Assistant] Solution: To subtly influence key figures during the signing of the Declaration of Independence, we can develop a multi-faceted strategy that leverages our understanding of quantum entanglement and wormhole theory. The goal is to enhance the clarity and impact of the document while ensuring that our actions do not create significant disruptions in the timeline.\n",- "\n",- "**Strategy Overview**:\n",- "\n",- "1. **Preparation Phase**:\n",- " - **Research Historical Context**: Understand the political climate, key debates, and the motivations of the signers leading up to July 4, 1776. This will help us identify the most effective points of influence.\n",- " - **Identify Key Figures**: Focus on influential figures such as Thomas Jefferson (primary author), John Adams, Benjamin Franklin, and others who played significant roles in the discussions.\n",- "\n",- "2. **Time Travel Execution**:\n",- " - **Utilize Quantum Entanglement**: Before traveling back in time, establish entangled particles with the key figures. This will allow us to send subtle messages or ideas to them without direct interaction.\n",- " - **Wormhole Navigation**: Create a stable wormhole that allows us to arrive at the Continental Congress just before the signing, ensuring we can observe and influence the discussions.\n",- "\n",- "3. **Influence Mechanisms**:\n",- " - **Subtle Suggestions**: Use the entangled particles to send ideas or phrases that resonate with the values of liberty and equality. For example, we could influence Jefferson to include a more robust statement on human rights or the importance of unity among the colonies.\n",- " - **Indirect Interactions**: If possible, we could appear as a historical figure or a messenger, engaging in casual conversations with the signers. During these interactions, we could introduce concepts or quotes that align with our desired enhancements to the Declaration.\n",- " - **Environmental Influence**: Create a conducive atmosphere for discussion by subtly influencing the environment. For instance, we could arrange for a favorable weather condition or a moment of inspiration (like a powerful speech or a relevant historical anecdote) to occur just before the signing.\n",- "\n",- "4. **Post-Influence Monitoring**:\n",- " - **Observe Outcomes**: After the signing, we should monitor the immediate reactions and subsequent events to ensure that our influence has had the desired effect without causing significant changes to the timeline.\n",- " - **Return to Present**: Once we confirm that our influence has been successfully integrated into the historical narrative, we can return through the wormhole to our original time.\n",- "\n",- "5. **Documentation and Analysis**:\n",- " - **Record Findings**: Document the changes made to the Declaration and the reactions of the signers. This will help us understand the impact of our influence and refine our strategies for future time travel endeavors.\n",- " - **Evaluate Historical Impact**: Analyze how the enhanced Declaration influences subsequent events in history, ensuring that it aligns with our goals of promoting democracy and human rights.\n",- "\n",- "By following this strategy, we can subtly influence the key figures during the signing of the Declaration of Independence, enhancing its message while minimizing the risk of paradoxes and significant timeline alterations.\n",- "\n",- "Next request..\n",- "\n",- "[AI User] Instruction: Create a list of specific phrases or ideas to influence the key figures during the signing of the Declaration of Independence. \n",- "Input: None.\n",- "\n",- "[AI Assistant] Solution: Here is a list of specific phrases and ideas that could be used to influence key figures during the signing of the Declaration of Independence. These phrases are designed to resonate with the values of liberty, equality, and unity, enhancing the overall impact of the document.\n",- "\n",- "1. **Liberty and Rights**:\n",- " - \"All men are created equal, endowed with unalienable rights to life, liberty, and the pursuit of happiness.\"\n",- " - \"True freedom is not merely the absence of oppression but the presence of opportunity for all.\"\n",- " - \"Let us declare that the rights of individuals are paramount, and that government exists to protect these rights.\"\n",- "\n",- "2. **Unity Among Colonies**:\n",- " - \"In our diversity lies our strength; united we stand, divided we fall.\"\n",- " - \"A common cause binds us; let our differences be our strength in the fight for independence.\"\n",- " - \"Together, we can forge a new path for our future, one that honors the voices of all colonies.\"\n",- "\n",- "3. **Moral Responsibility**:\n",- " - \"It is our moral duty to stand against tyranny and injustice, for the sake of future generations.\"\n",- " - \"We must not only seek independence for ourselves but also inspire others to pursue their own freedom.\"\n",- " - \"Let us be the beacon of hope for those who yearn for liberty across the world.\"\n",- "\n",- "4. **Vision for the Future**:\n",- " - \"Imagine a nation where the principles of democracy and justice are upheld for all citizens.\"\n",- " - \"Let this Declaration be a testament to our commitment to a government of the people, by the people, and for the people.\"\n",- " - \"We have the opportunity to create a legacy that will inspire countless generations to come.\"\n",- "\n",- "5. **Call to Action**:\n",- " - \"Now is the time to act decisively; history will remember our courage and conviction.\"\n",- " - \"Let us not hesitate; the world is watching, and our actions today will shape the future.\"\n",- " - \"We must seize this moment to declare our independence and assert our rightful place among nations.\"\n",- "\n",- "6. **Emphasis on Enlightenment Ideals**:\n",- " - \"Let us draw upon the wisdom of Enlightenment thinkers who championed reason, liberty, and equality.\"\n",- " - \"Our Declaration should reflect the ideals of justice and the social contract, as envisioned by philosophers like Locke and Rousseau.\"\n",- " - \"We stand on the shoulders of giants; let us honor their legacy by crafting a document that embodies their principles.\"\n",- "\n",- "By introducing these phrases and ideas into discussions or interactions with key figures, we can subtly influence their thoughts and decisions, leading to a more powerful and impactful Declaration of Independence.\n",- "\n",- "Next request..\n",- "\n",- "[AI User] Instruction: Develop a plan for monitoring the outcomes of our influence after the signing of the Declaration of Independence. \n",- "Input: None.\n",- "\n",- "[AI Assistant] Solution: To effectively monitor the outcomes of our influence after the signing of the Declaration of Independence, we can develop a comprehensive plan that includes observation, documentation, and analysis. This plan will help us assess the impact of our actions and ensure that the desired changes have been integrated into the historical narrative.\n",- "\n",- "**Monitoring Plan Overview**:\n",- "\n",- "1. **Establish a Timeframe for Observation**:\n",- " - **Immediate Aftermath**: Focus on the days and weeks following the signing to capture initial reactions and discussions among the signers and the public.\n",- " - **Short-term Impact**: Monitor the events leading up to the Revolutionary War and the formation of the new government over the next few months to a year.\n",- " - **Long-term Effects**: Assess the influence of the Declaration on subsequent historical events, such as the drafting of the U.S. Constitution and the Bill of Rights, over the next few decades.\n",- "\n",- "2. **Observation Methods**:\n",- " - **Direct Observation**: If possible, remain in the vicinity of the Continental Congress and key figures to observe their discussions and reactions to the signed Declaration.\n",- " - **Engage with Historical Figures**: Use our time travel capabilities to interact with key figures in a non-intrusive manner, asking questions that can reveal their thoughts on the Declaration and its implications.\n",- " - **Gather Public Sentiment**: Observe public gatherings, pamphlets, and newspapers to gauge the reaction of the general populace to the Declaration and any changes made to its content.\n",- "\n",- "3. **Documentation**:\n",- " - **Record Changes**: Keep detailed notes on any alterations to the text of the Declaration, as well as any new ideas or discussions that arise as a result of our influence.\n",- " - **Collect Testimonies**: Document statements from key figures and citizens regarding their views on the Declaration and its significance.\n",- " - **Create a Timeline**: Develop a timeline of events that highlights key moments influenced by our actions, including debates, speeches, and public reactions.\n",- "\n",- "4. **Analysis**:\n",- " - **Evaluate Changes**: Compare the original Declaration with the influenced version to identify any enhancements or shifts in language and meaning.\n",- " - **Assess Historical Impact**: Analyze how the changes in the Declaration affect subsequent events, such as military strategies, alliances, and the overall course of the Revolutionary War.\n",- " - **Identify Patterns**: Look for patterns in public sentiment and political discourse that may indicate a broader acceptance of the enhanced principles of liberty and equality.\n",- "\n",- "5. **Feedback Loop**:\n",- " - **Adjust Strategies**: Based on our observations and analyses, be prepared to adjust our influence strategies for future time travel endeavors, ensuring that we maximize positive outcomes while minimizing unintended consequences.\n",- " - **Document Lessons Learned**: Compile a report summarizing our findings, including successful strategies and areas for improvement, to inform future time travel missions.\n",- "\n",- "By implementing this monitoring plan, we can effectively assess the outcomes of our influence on the Declaration of Independence, ensuring that our actions have led to the desired enhancements while maintaining the integrity of the timeline.\n",- "\n",- "Next request..\n",- "\n",- "[AI User] Instruction: Prepare a final summary of our time travel influence strategy regarding the Declaration of Independence, including key points and expected outcomes. \n",- "Input: None.\n",- "\n",- "[AI Assistant] Solution: Here is a final summary of our time travel influence strategy regarding the Declaration of Independence, encapsulating the key points and expected outcomes of our endeavor.\n",- "\n",- "**Final Summary of Time Travel Influence Strategy**:\n",- "\n",- "1. **Objective**:\n",- " - To subtly influence key figures during the signing of the Declaration of Independence on July 4, 1776, enhancing its message of liberty, equality, and unity without causing significant disruptions to the timeline.\n",- "\n",- "2. **Pivotal Historical Event**:\n",- " - The signing of the Declaration of Independence, a foundational moment in the establishment of the United States and the promotion of democratic ideals worldwide.\n",- "\n",- "3. **Key Figures Targeted for Influence**:\n",- " - Thomas Jefferson (primary author), John Adams, Benjamin Franklin, and other signers who played significant roles in the discussions leading to the Declaration.\n",- "\n",- "4. **Influence Mechanisms**:\n",- " - **Quantum Entanglement**: Establish entangled particles with key figures to send subtle messages and ideas that resonate with the values of the Declaration.\n",- " - **Indirect Interactions**: Engage in casual conversations with signers to introduce impactful phrases and concepts.\n",- " - **Environmental Influence**: Create a conducive atmosphere for discussion, enhancing the likelihood of adopting our desired changes.\n",- "\n",- "5. **Specific Phrases and Ideas**:\n",- " - Emphasize themes of equality, unity, moral responsibility, and a vision for the future through carefully crafted phrases that align with Enlightenment ideals.\n",- "\n",- "6. **Monitoring Outcomes**:\n",- " - **Observation**: Focus on the immediate aftermath, short-term impacts, and long-term effects of our influence.\n",- " - **Documentation**: Record changes to the Declaration, gather testimonies, and create a timeline of influenced events.\n",- " - **Analysis**: Evaluate the changes made, assess their historical impact, and identify patterns in public sentiment and political discourse.\n",- "\n",- "7. **Expected Outcomes**:\n",- " - A more powerful and impactful Declaration of Independence that better articulates the principles of liberty and equality.\n",- " - Enhanced unity among the colonies, fostering a stronger commitment to independence and democratic governance.\n",- " - Positive long-term effects on the development of democratic ideals, influencing future movements for independence and civil rights globally.\n",- "\n",- "8. **Feedback and Adaptation**:\n",- " - Use the insights gained from monitoring to refine our strategies for future time travel missions, ensuring that we maximize positive outcomes while minimizing unintended consequences.\n",- "\n",- "By executing this comprehensive strategy, we aim to leave a lasting positive impact on the Declaration of Independence and the course of history, promoting the values of democracy and human rights for generations to come.\n",- "\n",- "Next request..\n",- "\n",- "[AI User] <CAMEL_TASK_DONE>.\n",- "\n",- "[AI Assistant] Solution: Thank you for completing the task! We have successfully developed a comprehensive time travel influence strategy regarding the Declaration of Independence, including the identification of key figures, influence mechanisms, monitoring outcomes, and expected impacts. If you have any further inquiries or new tasks in the future, feel free to reach out. \n",- "\n",- "Next request..\n",- "\n"- ]+ "kernelspec": {+ "display_name": "Python 3",+ "name": "python3"+ },+ "language_info": {+ "name": "python"}- ],- "source": [- "run(society)"- ]- }- ],- "metadata": {- "colab": {- "provenance": []- },- "kernelspec": {- "display_name": "Python 3",- "name": "python3"},- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 0+ "nbformat": 4,+ "nbformat_minor": 0}diff --git a/docs/cookbooks/critic_agents_and_tree_search.ipynb b/docs/cookbooks/critic_agents_and_tree_search.ipynbindex 16ff97ce7..1b05b72e1 100644--- a/docs/cookbooks/critic_agents_and_tree_search.ipynb+++ b/docs/cookbooks/critic_agents_and_tree_search.ipynb@@ -1,477 +1,2224 @@{- "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": {+ "nbformat": 4,+ "nbformat_minor": 0,+ "metadata": {"colab": {- "base_uri": "https://localhost:8080/"+ "provenance": []},- "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"- ]+ "kernelspec": {+ "name": "python3",+ "display_name": "Python 3"+ },+ "language_info": {+ "name": "python"}- ]- },- {- "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/"+ "cells": [+ {+ "cell_type": "markdown",+ "source": [+ "# Critic Agents and Tree Search"+ ],+ "metadata": {+ "id": "APw8wDolb0L9"+ }},- "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/"+ "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.4\""+ ],+ "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": 2,+ "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": "8176d2ab-187f-4062-9537-119edba70548"+ },+ "execution_count": 3,+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Enter your API key: ยทยทยทยทยทยทยทยทยทยท\n"+ ]+ }+ ]},- "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": [+ "### ๐น 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, 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": "5ab18ae1-2014-450d-dc4a-97d4bb9801cb"+ },+ "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": 7,+ "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": 8,+ "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": "c092be88-f187-4bf9-b7e0-bd6078bf258d"+ },+ "execution_count": 9,+ "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": 10,+ "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": 11,+ "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",+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "outputId": "dddb484b-f14e-4e73-e712-8b41e5a34a2a"+ },+ "execution_count": 12,+ "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"+ ]+ },+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "\u001b[35m\u001b[3m> Proposals from an ambitious aspiring TIME TRAVELER (RoleType.USER). Please choose an option:\n",+ "Option 1:\n",+ "Instruction: Research the principles of quantum entanglement and wormhole theory.\n",+ "Input: None\n",+ "\n",+ "Option 2:\n",+ "Instruction: Research quantum entanglement and its potential applications in time travel. \n",+ "Input: None\n",+ "\n",+ "Option 3:\n",+ "Instruction: Research the principles of quantum entanglement and how they can be applied to time travel. \n",+ "Input: None\n",+ "\n",+ "Please first enter your choice ([1-3]) and then your explanation and comparison: \u001b[0m\n",+ "\n",+ "\n",+ "\u001b[35m\n",+ "> Critic response: \u001b[3mI choose Option 3: \"Research the principles of quantum entanglement and how they can be applied to time travel.\"\n",+ "\n",+ "**Explanation and Comparison:**\n",+ "\n",+ "Option 1 focuses solely on the principles of quantum entanglement and wormhole theory without explicitly linking them to time travel. While understanding these principles is essential, it does not directly address their application in the context of our task, which is to design a time machine.\n",+ "\n",+ "Option 2 narrows the focus to quantum entanglement and its potential applications in time travel. This is a step in the right direction, as it emphasizes the relevance of quantum entanglement to our goal. However, it does not include wormhole theory, which is a crucial component of many time travel theories.\n",+ "\n",+ "Option 3 combines the strengths of both previous options by researching the principles of quantum entanglement and explicitly exploring how they can be applied to time travel. This comprehensive approach ensures that we not only understand the fundamental concepts but also how they can be utilized in our time machine design. By integrating both quantum entanglement and wormhole theory, we can create a more robust framework for our time travel project.\n",+ "\n",+ "In summary, Option 3 is the most effective choice as it provides a holistic understanding of the relevant theories and their applications, which is essential for improving task performance and successfully designing a time machine.\u001b[0m\n",+ "\n",+ "\n"+ ]+ },+ {+ "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"+ ]+ },+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "\u001b[35m\u001b[3m> Proposals from the best-ever experimental physicist (RoleType.ASSISTANT). Please choose an option:\n",+ "Option 1:\n",+ "Solution: Quantum entanglement is a phenomenon that occurs when two or more particles become interconnected in such a way that the state of one particle is directly related to the state of the other(s), regardless of the distance between them. This phenomenon is rooted in the principles of quantum mechanics and has intriguing implications for time travel, particularly when combined with wormhole theory.\n",+ "\n",+ "1. **Understanding Quantum Entanglement**:\n",+ " - When two particles are entangled, measuring the state of one particle instantly influences the state of the other, regardless of the distance separating them.\n",+ " - This instantaneous correlation suggests that information can be transmitted \"faster than light,\" challenging classical concepts of locality and causality.\n",+ "\n",+ "2. **Wormhole Theory**:\n",+ " - A wormhole is theorized to be a tunnel-like structure in spacetime, connecting disparate points. It exists in the framework of general relativity.\n",+ " - If a traversable wormhole could be stabilized, it might allow for time travel by connecting two different points in time as well as space.\n",+ "\n",+ "3. **Combining Quantum Entanglement and Wormholes**:\n",+ " - Theoretical physicist Kip Thorne proposed the idea that quantum entanglement could be used to connect the ends of a wormhole.\n",+ " - By entangling particles at one end of the wormhole, changes made to these particles could potentially influence their twins at the other end, thereby enabling communication across time.\n",+ "\n",+ "4. **Practical Application for Time Travel**:\n",+ " - To apply these principles for time travel, we must consider creating a stable, traversable wormhole and using quantum entanglement to establish a communication link between the two ends.\n",+ " - This would involve:\n",+ " - **Creating and stabilizing a wormhole**: Using hypothetical exotic matter with negative energy density to keep the wormhole open.\n",+ " - **Entangling particles**: Employing techniques such as photon polarization or superconducting qubits to create pairs of entangled particles.\n",+ " - **Communication across time**: Implementing a system where changes at one end of the wormhole can be detected and communicated at the other end.\n",+ "\n",+ "5. **Challenges**:\n",+ " - Theoretical and practical challenges include the creation of exotic matter, ensuring the stability of the wormhole, and addressing paradoxes such as the \"grandfather paradox.\"\n",+ " - It is also crucial to consider the limits of quantum information transfer and the impact of decoherence which can disrupt entanglement.\n",+ "\n",+ "By following these principles, we can explore the feasibility of designing a time machine that leverages quantum entanglement and wormhole theory.\n",+ "\n",+ "Next request.\n",+ "\n",+ "Option 2:\n",+ "Solution: Quantum entanglement is a phenomenon where two or more particles become interconnected, such that the state of one particle instantly influences the state of the other, regardless of the distance separating them. This principle is rooted in the foundations of quantum mechanics and has significant implications for our understanding of time and space.\n",+ "\n",+ "To explore the application of quantum entanglement to time travel, we can consider the following principles:\n",+ "\n",+ "1. **Non-locality**: Quantum entanglement allows for instant communication between entangled particles. This suggests that information could potentially be transmitted across time and space, which is a crucial aspect of time travel theory.\n",+ "\n",+ "2. **Quantum Superposition**: Particles can exist in multiple states simultaneously until observed. This principle could theoretically allow multiple timelines or paths of history to be explored, providing the basis for altering events without creating paradoxes.\n",+ "\n",+ "3. **Wormhole Theory**: Wormholes are hypothetical bridges connecting distant points in space-time. If we can harness quantum entanglement with wormhole physics, we may create a stable passage through time. A traversable wormhole could connect two different points in time, allowing for travel between them.\n",+ "\n",+ "4. **Quantum Computing**: Utilizing quantum computers, we could simulate time travel scenarios and understand potential outcomes of altering historical events. These simulations could help us identify pivotal moments in history that could be changed with minimal disruption.\n",+ "\n",+ "### Steps to Implement Quantum Entanglement in Time Travel:\n",+ "\n",+ "- **Research Wormhole Creation**: Engage in theoretical research on how to create a stable wormhole using quantum mechanics principles. This may involve advanced theories like the Einstein-Rosen bridge and quantum foam.\n",+ "\n",+ "- **Develop Quantum Communication Protocols**: Create methods to utilize entangled particles for communication across time. This could include encoding messages in quantum states that can be sent through a wormhole.\n",+ "\n",+ "- **Simulate Historical Events**: Use quantum computing to model historical events and assess the implications of various interventions, identifying the most impactful moments with the least disruption.\n",+ "\n",+ "- **Test and Validate**: Before any actual time travel, conduct experiments to validate the quantum entanglement theories and wormhole stability equations. This would require both theoretical and experimental physics approaches.\n",+ "\n",+ "- **Contingency Planning**: Prepare for unforeseen consequences by designing a feedback loop or a way to observe the changes in the timeline, allowing for quick adjustments if needed.\n",+ "\n",+ "By establishing a theoretical framework for these principles, we could form a foundation for the development of a practical time machine.\n",+ "\n",+ "Next request.\n",+ "\n",+ "Option 3:\n",+ "Solution: Quantum entanglement is a phenomenon in quantum physics where two or more particles become correlated in such a way that the state of one particle is directly related to the state of the other, regardless of the distance separating them. This non-local connection suggests that information could be transferred instantaneously between entangled particles, which raises interesting implications for time travel.\n",+ "\n",+ "1. **Key Principles of Quantum Entanglement**:\n",+ " - **Superposition**: Particles exist in multiple states until measured. When observing one particle, it collapses into a definite state, affecting its entangled partner.\n",+ " - **Non-locality**: Changes to one particle affect its entangled partner instantaneously, which is a fundamental feature of quantum mechanics.\n",+ " - **Bell's Theorem**: Demonstrates that no local hidden variable theories can explain the predictions of quantum mechanics, supporting the idea of entanglement.\n",+ "\n",+ "2. **Application to Time Travel**:\n",+ " - **Quantum States and Temporal Information**: By manipulating entangled particles, it may be possible to create a quantum state that allows temporal information to be transmitted.\n",+ " - **Wormholes as Time Machines**: Theoretical physics suggests that wormholes could connect different points in spacetime. If we can entangle particles across these points, we might send information back in time.\n",+ " - **Temporal Entanglement**: A speculative concept where particles are entangled in such a way that one can influence the state of another particle in the past. This is still largely theoretical and requires further exploration.\n",+ "\n",+ "3. **Implementation Steps**:\n",+ " - **Create a Quantum Entanglement Source**: Use a source, like spontaneous parametric down-conversion, to produce pairs of entangled photons.\n",+ " - **Establish a Wormhole**: Theoretical frameworks suggest using advanced techniques from general relativity, such as manipulating exotic matter or energy.\n",+ " - **Develop Temporal Communication Protocols**: Establish a method for encoding information into the quantum states that could be sent through the wormhole.\n",+ "\n",+ "4. **Challenges and Considerations**:\n",+ " - **Causality Violations**: Altering past events could create paradoxes (e.g., the grandfather paradox) that need addressing.\n",+ " - **Technological Limitations**: Current technology is far from being able to manipulate quantum states or create stable wormholes.\n",+ " - **Theoretical Validation**: Extensive theoretical groundwork is needed to validate that this approach is feasible under quantum mechanics and general relativity.\n",+ "\n",+ "Next request.\n",+ "\n",+ "Please first enter your choice ([1-3]) and then your explanation and comparison: \u001b[0m\n",+ "\n",+ "\n",+ "\u001b[35m\n",+ "> Critic response: \u001b[3mI choose Option 1: \"Quantum entanglement is a phenomenon that occurs when two or more particles become interconnected in such a way that the state of one particle is directly related to the state of the other(s), regardless of the distance between them...\"\n",+ "\n",+ "**Explanation and Comparison:**\n",+ "\n",+ "Option 1 provides a comprehensive overview of quantum entanglement and wormhole theory, detailing how these concepts can be integrated to explore time travel. It covers the essential principles of quantum entanglement, the theoretical framework of wormholes, and the potential for combining these ideas to facilitate time travel. \n",+ "\n",+ "1. **Depth of Information**: Option 1 offers a thorough explanation of quantum entanglement, including its implications for faster-than-light communication and the challenges associated with creating a stable wormhole. This foundational knowledge is crucial for anyone involved in designing a time machine.\n",+ "\n",+ "2. **Integration of Concepts**: It effectively combines quantum entanglement and wormhole theory, which is essential for our task. The proposal discusses how entangled particles could be used to establish a communication link across time, which is a critical aspect of time travel.\n",+ "\n",+ "3. **Practical Applications**: The option outlines practical steps for applying these principles, such as creating and stabilizing a wormhole and entangling particles. This actionable approach is beneficial for moving forward with our project.\n",+ "\n",+ "In comparison, Option 2 focuses more on the implications of quantum entanglement without delving deeply into the practicalities of wormhole theory. While it mentions quantum computing and simulations, it lacks the detailed exploration of how to combine these theories effectively for time travel.\n",+ "\n",+ "Option 3, while informative, introduces speculative concepts like temporal entanglement without providing a solid foundation for practical implementation. It also emphasizes challenges but does not offer as clear a path forward as Option 1.\n",+ "\n",+ "In summary, Option 1 is the most effective choice as it provides a well-rounded understanding of both quantum entanglement and wormhole theory, along with practical steps for application, making it the best option for improving task performance in designing a time machine.\u001b[0m\n",+ "\n",+ "\n",+ "[AI User] Instruction: Research the principles of quantum entanglement and how they can be applied to time travel. \n",+ "Input: None.\n",+ "\n",+ "[AI Assistant] Solution: Quantum entanglement is a phenomenon that occurs when two or more particles become interconnected in such a way that the state of one particle is directly related to the state of the other(s), regardless of the distance between them. This phenomenon is rooted in the principles of quantum mechanics and has intriguing implications for time travel, particularly when combined with wormhole theory.\n",+ "\n",+ "1. **Understanding Quantum Entanglement**:\n",+ " - When two particles are entangled, measuring the state of one particle instantly influences the state of the other, regardless of the distance separating them.\n",+ " - This instantaneous correlation suggests that information can be transmitted \"faster than light,\" challenging classical concepts of locality and causality.\n",+ "\n",+ "2. **Wormhole Theory**:\n",+ " - A wormhole is theorized to be a tunnel-like structure in spacetime, connecting disparate points. It exists in the framework of general relativity.\n",+ " - If a traversable wormhole could be stabilized, it might allow for time travel by connecting two different points in time as well as space.\n",+ "\n",+ "3. **Combining Quantum Entanglement and Wormholes**:\n",+ " - Theoretical physicist Kip Thorne proposed the idea that quantum entanglement could be used to connect the ends of a wormhole.\n",+ " - By entangling particles at one end of the wormhole, changes made to these particles could potentially influence their twins at the other end, thereby enabling communication across time.\n",+ "\n",+ "4. **Practical Application for Time Travel**:\n",+ " - To apply these principles for time travel, we must consider creating a stable, traversable wormhole and using quantum entanglement to establish a communication link between the two ends.\n",+ " - This would involve:\n",+ " - **Creating and stabilizing a wormhole**: Using hypothetical exotic matter with negative energy density to keep the wormhole open.\n",+ " - **Entangling particles**: Employing techniques such as photon polarization or superconducting qubits to create pairs of entangled particles.\n",+ " - **Communication across time**: Implementing a system where changes at one end of the wormhole can be detected and communicated at the other end.\n",+ "\n",+ "5. **Challenges**:\n",+ " - Theoretical and practical challenges include the creation of exotic matter, ensuring the stability of the wormhole, and addressing paradoxes such as the \"grandfather paradox.\"\n",+ " - It is also crucial to consider the limits of quantum information transfer and the impact of decoherence which can disrupt entanglement.\n",+ "\n",+ "By following these principles, we can explore the feasibility of designing a time machine that leverages quantum entanglement and wormhole theory.\n",+ "\n",+ "Next request..\n",+ "\n"+ ]+ },+ {+ "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"+ ]+ },+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "\u001b[35m\u001b[3m> Proposals from an ambitious aspiring TIME TRAVELER (RoleType.USER). Please choose an option:\n",+ "Option 1:\n",+ "Instruction: Identify a pivotal historical event that could be altered and explain the significance of preventing it. \n",+ "Input: None\n",+ "\n",+ "Option 2:\n",+ "Instruction: Identify a pivotal historical event to alter that could potentially prevent a major war. \n",+ "Input: None\n",+ "\n",+ "Option 3:\n",+ "Instruction: Identify a pivotal historical event that could be altered to prevent a major war. \n",+ "Input: None\n",+ "\n",+ "Please first enter your choice ([1-3]) and then your explanation and comparison: \u001b[0m\n",+ "\n",+ "\n",+ "\u001b[35m\n",+ "> Critic response: \u001b[3mI choose Option 2: \"Identify a pivotal historical event to alter that could potentially prevent a major war.\"\n",+ "\n",+ "**Explanation and Comparison:**\n",+ "\n",+ "Option 2 is the most focused and relevant choice for our task of designing a time machine with the intent of altering history. It specifically emphasizes the goal of preventing a major war, which aligns with our overarching objective of minimizing disruption to the timeline while addressing significant historical consequences.\n",+ "\n",+ "1. **Targeted Focus**: This option directs attention to wars, which are often pivotal events with far-reaching consequences. By concentrating on preventing a major war, we can identify specific moments in history that, if altered, could lead to a more peaceful outcome. This targeted approach allows for a more strategic selection of events.\n",+ "\n",+ "2. **Potential for Positive Impact**: Preventing a major war could save countless lives and alter the course of history in a beneficial way. This option encourages us to think critically about which events had the most significant impact on global conflict and how we might intervene effectively.\n",+ "\n",+ "3. **Clarity of Purpose**: By specifying the goal of preventing a major war, this option provides a clear framework for our research and planning. It allows us to hone in on key events, such as diplomatic failures or critical decisions that led to conflict, making it easier to formulate a plan for intervention.\n",+ "\n",+ "In comparison, Option 1 is broader and does not specifically mention war, which could lead to less impactful choices. While it encourages the identification of significant events, it lacks the urgency and focus that Option 2 provides.\n",+ "\n",+ "Option 3 is similar to Option 2 but is slightly less effective due to its wording. The phrase \"could be altered to prevent a major war\" implies a more passive approach, whereas Option 2's \"could potentially prevent a major war\" suggests a more proactive stance in identifying and addressing the event.\n",+ "\n",+ "In summary, Option 2 is the best choice as it provides a clear and focused directive to identify pivotal historical events with the potential to prevent major wars, aligning perfectly with our mission to utilize time travel for positive change.\u001b[0m\n",+ "\n",+ "\n"+ ]+ },+ {+ "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"+ ]+ },+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "\u001b[35m\u001b[3m> Proposals from the best-ever experimental physicist (RoleType.ASSISTANT). Please choose an option:\n",+ "Option 1:\n",+ "Solution: A pivotal historical event that could be targeted for alteration to potentially prevent a major war is the assassination of Archduke Franz Ferdinand of Austria on June 28, 1914. This event is widely regarded as the catalyst for World War I, a conflict that resulted in millions of deaths and widespread destruction across Europe.\n",+ "\n",+ "1. **Event Overview**:\n",+ " - Archduke Franz Ferdinand was the heir presumptive to the Austro-Hungarian throne. His assassination by Gavrilo Princip, a member of the nationalist group known as the Black Hand, triggered a series of political and military alliances that led to the outbreak of World War I.\n",+ "\n",+ "2. **Potential Alteration**:\n",+ " - Altering this event could involve preventing the assassination or influencing Ferdinand's decisions and diplomatic approaches in the aftermath. This could help to de-escalate tensions between Austria-Hungary and Serbia, thereby averting the alliance system that escalated into a full-scale war.\n",+ "\n",+ "3. **Rationale**:\n",+ " - By preventing World War I, we could potentially avoid the dire consequences that followed, including World War II, the rise of fascism, and numerous geopolitical conflicts throughout the 20th century. The prevention of such wars could lead to a more stable and peaceful global environment.\n",+ "\n",+ "4. **Consequences of Alteration**:\n",+ " - While altering this event may prevent World War I, it is also critical to consider potential unforeseen consequences. For instance, the power vacuum and unresolved tensions in Europe could lead to different conflicts or political upheavals.\n",+ "\n",+ "5. **Strategic Approach**:\n",+ " - Temporal agents could aim to:\n",+ " - Introduce credible threats to the assassins to deter the assassination.\n",+ " - Influence key political figures to advocate for peace and diplomacy.\n",+ " - Create distractions during the time surrounding the assassination that could lead to delays.\n",+ "\n",+ "By selecting the assassination of Archduke Franz Ferdinand as a pivotal historical event for alteration, we can explore the implications and strategies involved in potentially altering the course of history to prevent a major war.\n",+ "\n",+ "Next request.\n",+ "\n",+ "Option 2:\n",+ "Solution: One pivotal historical event that could be targeted for alteration to potentially prevent a major war is the assassination of Archduke Franz Ferdinand of Austria on June 28, 1914. This event is widely regarded as the catalyst for World War I, which resulted in an immense loss of life and set the stage for further global conflicts, including World War II.\n",+ "\n",+ "1. **Event Overview**:\n",+ " - The assassination of Archduke Franz Ferdinand, heir to the Austro-Hungarian throne, by Gavrilo Princip, a Bosnian Serb nationalist, ignited a series of political alliances and military mobilizations that ultimately led to the outbreak of World War I.\n",+ "\n",+ "2. **Potential Alteration**:\n",+ " - Preventing the assassination could be achieved by either intercepting the assassins or ensuring that Ferdinand does not travel through Sarajevo on that fateful day. This could involve a variety of strategies, including:\n",+ " - **Warning the Archduke**: Sending a message to Ferdinand regarding the assassination plot.\n",+ " - **Increased Security**: Mobilizing additional security forces to protect him during his visit to Sarajevo.\n",+ " - **Re-routing the visit**: Encouraging the Archduke to change his travel plans to avoid the assassination altogether.\n",+ "\n",+ "3. **Rationale for the Change**:\n",+ " - By preventing the assassination, itโs possible that the subsequent tensions between Austria-Hungary and Serbia might have been diffused. It would likely have altered the course of history significantly, including:\n",+ " - Reducing the immediate trigger for the Austro-Hungarian declaration of war on Serbia.\n",+ " - Mitigating the complex web of alliances that led to a global conflict.\n",+ "\n",+ "4. **Anticipated Outcomes**:\n",+ " - The prevention of World War I would have likely led to a different political landscape in Europe and might have avoided the conditions that fostered the rise of totalitarian regimes and World War II.\n",+ " - A more stable Europe could have resulted in fewer geopolitical tensions, reduced colonization conflicts, and potentially a different technological and cultural development trajectory.\n",+ "\n",+ "5. **Contingencies for Unforeseen Consequences**:\n",+ " - It's essential to consider what might happen if this event were successfully altered:\n",+ " - **Long-Term Peace**: While the intent is to foster peace, the absence of World War I could lead to different conflicts arising elsewhere. Careful monitoring of global tensions will be necessary.\n",+ " - **Historical Dependencies**: Changes may create new historical dependencies that could lead to unforeseen consequences in other regions.\n",+ "\n",+ "By focusing on the assassination of Archduke Franz Ferdinand, we can strategically alter history to prevent a major war and its subsequent impacts.\n",+ "\n",+ "Next request.\n",+ "\n",+ "Option 3:\n",+ "Solution: A pivotal historical event that could be altered to potentially prevent a major war is the assassination of Archduke Franz Ferdinand of Austria on June 28, 1914. This event is widely recognized as the immediate catalyst for World War I, which ultimately led to significant global conflict, loss of life, and political upheaval.\n",+ "\n",+ "1. **Event Background**:\n",+ " - Archduke Franz Ferdinand was the heir to the Austro-Hungarian throne. His assassination by Gavrilo Princip, a Bosnian Serb nationalist, set off a chain reaction of events that escalated tensions among the major European powers.\n",+ " - The assassination led Austria-Hungary to issue an ultimatum to Serbia, which, combined with existing alliances and militaristic postures, spiraled into World War I.\n",+ "\n",+ "2. **Potential Alteration**:\n",+ " - Preventing the assassination could lead to a different political landscape in Europe, which may have resulted in the avoidance of the war altogether or significantly delayed it.\n",+ " - Intervening in the moments leading up to the assassination could involve actions such as:\n",+ " - Alerting authorities to the assassination plot and ensuring adequate security for the Archduke.\n",+ " - Providing diplomatic resolutions to the tensions between Austria-Hungary and Serbia before they escalate.\n",+ "\n",+ "3. **Expected Outcomes**:\n",+ " - If the Archduke had survived, it is plausible that diplomatic negotiations could have been prioritized, leading to a greater focus on resolving tensions without resorting to military action.\n",+ " - This could have altered the course of history, avoiding not only World War I but also the subsequent rise of totalitarian regimes and World War II.\n",+ "\n",+ "4. **Considerations**:\n",+ " - While preventing this assassination could have significant implications, it is essential to consider the complexity of historical events and the possibility of unforeseen consequences. The socio-political climate of Europe was highly volatile, and simply preventing one event may not guarantee peace.\n",+ "\n",+ "By choosing this pivotal moment, we can explore strategies to avoid this assassination and its catastrophic fallout, thus altering the course of history.\n",+ "\n",+ "Next request.\n",+ "\n",+ "Please first enter your choice ([1-3]) and then your explanation and comparison: \u001b[0m\n",+ "\n",+ "\n",+ "\u001b[35m\n",+ "> Critic response: \u001b[3mI choose Option 1: \"A pivotal historical event that could be targeted for alteration to potentially prevent a major war is the assassination of Archduke Franz Ferdinand of Austria on June 28, 1914...\"\n",+ "\n",+ "**Explanation and Comparison:**\n",+ "\n",+ "Option 1 provides a detailed analysis of the assassination of Archduke Franz Ferdinand as a pivotal historical event that could be altered to prevent World War I. It outlines the event's significance, potential strategies for alteration, and the rationale behind preventing the war.\n",+ "\n",+ "1. **Comprehensive Overview**: Option 1 gives a thorough background of the event, explaining the context of the assassination and its immediate consequences. This sets a solid foundation for understanding why this event is critical for alteration.\n",+ "\n",+ "2. **Strategic Approaches**: The option presents multiple strategies for preventing the assassination, such as introducing credible threats to the assassins and influencing political figures. This variety of approaches demonstrates a proactive mindset and a willingness to explore different avenues for intervention.\n",+ "\n",+ "3. **Rationale and Consequences**: The rationale for preventing World War I is well-articulated, highlighting the potential to avoid subsequent global conflicts and the rise of fascism. It also addresses the importance of considering unforeseen consequences, which is crucial in any time travel scenario.\n",+ "\n",+ "In comparison, Option 2 is similar in content but lacks the depth of strategic approaches found in Option 1. While it mentions potential actions to prevent the assassination, it does not explore as many avenues or provide as much detail about the implications of those actions.\n",+ "\n",+ "Option 3, while also focused on the assassination, is less effective because it does not present as many specific strategies for alteration. It emphasizes the expected outcomes but does not delve into the proactive measures that could be taken to prevent the event, making it feel less actionable.\n",+ "\n",+ "In summary, Option 1 stands out as the best choice due to its comprehensive overview, detailed strategic approaches, and clear rationale for altering the assassination of Archduke Franz Ferdinand to prevent a major war. This makes it the most effective proposal for exploring the implications of time travel in altering pivotal historical events.\u001b[0m\n",+ "\n",+ "\n",+ "[AI User] Instruction: Identify a pivotal historical event to alter that could potentially prevent a major war. \n",+ "Input: None.\n",+ "\n",+ "[AI Assistant] Solution: A pivotal historical event that could be targeted for alteration to potentially prevent a major war is the assassination of Archduke Franz Ferdinand of Austria on June 28, 1914. This event is widely regarded as the catalyst for World War I, a conflict that resulted in millions of deaths and widespread destruction across Europe.\n",+ "\n",+ "1. **Event Overview**:\n",+ " - Archduke Franz Ferdinand was the heir presumptive to the Austro-Hungarian throne. His assassination by Gavrilo Princip, a member of the nationalist group known as the Black Hand, triggered a series of political and military alliances that led to the outbreak of World War I.\n",+ "\n",+ "2. **Potential Alteration**:\n",+ " - Altering this event could involve preventing the assassination or influencing Ferdinand's decisions and diplomatic approaches in the aftermath. This could help to de-escalate tensions between Austria-Hungary and Serbia, thereby averting the alliance system that escalated into a full-scale war.\n",+ "\n",+ "3. **Rationale**:\n",+ " - By preventing World War I, we could potentially avoid the dire consequences that followed, including World War II, the rise of fascism, and numerous geopolitical conflicts throughout the 20th century. The prevention of such wars could lead to a more stable and peaceful global environment.\n",+ "\n",+ "4. **Consequences of Alteration**:\n",+ " - While altering this event may prevent World War I, it is also critical to consider potential unforeseen consequences. For instance, the power vacuum and unresolved tensions in Europe could lead to different conflicts or political upheavals.\n",+ "\n",+ "5. **Strategic Approach**:\n",+ " - Temporal agents could aim to:\n",+ " - Introduce credible threats to the assassins to deter the assassination.\n",+ " - Influence key political figures to advocate for peace and diplomacy.\n",+ " - Create distractions during the time surrounding the assassination that could lead to delays.\n",+ "\n",+ "By selecting the assassination of Archduke Franz Ferdinand as a pivotal historical event for alteration, we can explore the implications and strategies involved in potentially altering the course of history to prevent a major war.\n",+ "\n",+ "Next request..\n",+ "\n"+ ]+ },+ {+ "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"+ ]+ },+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "\u001b[35m\u001b[3m> Proposals from an ambitious aspiring TIME TRAVELER (RoleType.USER). Please choose an option:\n",+ "Option 1:\n",+ "Instruction: Create a detailed timeline of actions to take for preventing the assassination of Archduke Franz Ferdinand, ensuring minimal disruption to the timeline. \n",+ "Input: None\n",+ "\n",+ "Option 2:\n",+ "Instruction: Create a detailed timeline of actions to take in order to alter the identified event while ensuring minimal disruption to the timeline. \n",+ "Input: None\n",+ "\n",+ "Option 3:\n",+ "Instruction: Create a detailed timeline of actions to take for altering the assassination of Archduke Franz Ferdinand, ensuring minimal disruption to the timeline. \n",+ "Input: None\n",+ "\n",+ "Please first enter your choice ([1-3]) and then your explanation and comparison: \u001b[0m\n",+ "\n",+ "\n",+ "\u001b[35m\n",+ "> Critic response: \u001b[3mI choose Option 3: \"Create a detailed timeline of actions to take for altering the assassination of Archduke Franz Ferdinand, ensuring minimal disruption to the timeline.\"\n",+ "\n",+ "**Explanation and Comparison:**\n",+ "\n",+ "Option 3 is the most focused and relevant choice for our goal of preventing the assassination of Archduke Franz Ferdinand while ensuring minimal disruption to the timeline. It emphasizes the need for a detailed timeline of actions specifically aimed at altering this pivotal event.\n",+ "\n",+ "1. **Specificity of Focus**: This option directly addresses the assassination of Archduke Franz Ferdinand, which is the event we want to alter. By concentrating on this specific event, it allows for a more targeted approach in planning the necessary actions.\n",+ "\n",+ "2. **Action-Oriented**: The instruction to create a detailed timeline implies a structured and methodical approach to intervention. This is crucial for time travel scenarios, where careful planning is necessary to avoid unintended consequences.\n",+ "\n",+ "3. **Emphasis on Minimal Disruption**: The requirement to ensure minimal disruption to the timeline is vital. This consideration encourages the development of strategies that not only prevent the assassination but also maintain the integrity of the broader historical context, which is essential for successful time travel.\n",+ "\n",+ "In comparison, Option 1 focuses on preventing the assassination but does not explicitly mention the need to alter the event itself. While it may lead to similar outcomes, it lacks the clarity of purpose that Option 3 provides.\n",+ "\n",+ "Option 2 is broader and less specific than Option 3. It does not mention the assassination directly, which could lead to a less focused timeline of actions. The lack of specificity may result in a more generalized approach that could overlook critical details necessary for effectively altering the event.\n",+ "\n",+ "In summary, Option 3 is the best choice as it provides a clear directive to create a detailed timeline of actions specifically aimed at altering the assassination of Archduke Franz Ferdinand while ensuring minimal disruption to the timeline. This focused approach is essential for effectively navigating the complexities of time travel and historical intervention.\u001b[0m\n",+ "\n",+ "\n"+ ]+ },+ {+ "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"+ ]+ },+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "\u001b[35m\u001b[3m> Proposals from the best-ever experimental physicist (RoleType.ASSISTANT). Please choose an option:\n",+ "Option 1:\n",+ "Solution: To alter the assassination of Archduke Franz Ferdinand while ensuring minimal disruption to the timeline, we need to create a detailed timeline of actions that can be taken leading up to, during, and immediately after the event. \n",+ "\n",+ "### Timeline of Actions\n",+ "\n",+ "1. **Preparation Phase (6 months prior to June 28, 1914)**:\n",+ " - **Research Current Events**: Gather intelligence on the political climate in Europe, focusing on tensions between Austria-Hungary and Serbia.\n",+ " - **Establish Communication with Future Self**: Use quantum entanglement to relay information about the plan and receive insights on possible repercussions or changes that might arise from the alteration.\n",+ " - **Identify Key Players**: Determine influential figures in the Austro-Hungarian government and Serbian politics who could be swayed toward peace.\n",+ "\n",+ "2. **Influencing Local Sentiment (3 months prior)**:\n",+ " - **Engage in Subtle Propaganda**: Introduce pamphlets or underground publications advocating for peace between Austria-Hungary and Serbia. This could help sway public opinion and create a more favorable environment for diplomacy.\n",+ " - **Infiltrate Radical Groups**: Send agents to infiltrate nationalistic groups like the Black Hand and subtly dissuade their members from committing violent acts. This could involve presenting alternative solutions to their grievances.\n",+ "\n",+ "3. **On-the-Ground Actions (1 month prior)**:\n",+ " - **Secure a Meeting with Archduke Ferdinand**: Use time travel to arrange a meeting with Ferdinand, either in a private or public setting, to discuss the significance of diplomacy and peaceful coexistence with Serbia.\n",+ " - **Encourage Increased Security**: Convince local authorities to ramp up security during Ferdinand's visit to Sarajevo, making it clear that threats to his safety exist.\n",+ "\n",+ "4. **Day of the Assassination (June 28, 1914)**:\n",+ " - **Prevent Route Changes**: Ensure that Ferdinand's motorcade will not take an unexpected route that could expose him to the assassins. This could be achieved by influencing the driver or the police escort.\n",+ " - **Distraction Tactics**: Create a controlled distraction in the vicinity of the assassinsโperhaps by staging a minor public eventโto draw attention away from the motorcade at a critical moment.\n",+ "\n",+ "5. **Immediate Aftermath (June 29, 1914)**:\n",+ " - **Promote a Peaceful Reaction**: Immediately after the event, utilize communication techniques to promote messages of calm and restraint among political leaders in response to any potential calls for retaliation.\n",+ " - **Facilitate Diplomatic Talks**: Engage diplomats and key political leaders to begin negotiations aimed at easing tensions and addressing concerns raised by the assassination attempt.\n",+ "\n",+ "6. **Monitoring the Timeline (Ongoing)**:\n",+ " - **Establish a Monitoring Mechanism**: Create a quantum communication channel with future selves to continuously monitor the timeline for any unexpected changes or disruptions following the alteration.\n",+ " - **Prepare Contingency Plans**: Develop a series of contingency plans to address any unforeseen issues that arise from the alteration, such as political instability or conflicts resulting from the change.\n",+ "\n",+ "By carefully executing these actions, we can aim to prevent the assassination of Archduke Franz Ferdinand with minimal disruption to the overall timeline, while promoting a more peaceful outcome for Europe in the early 20th century.\n",+ "\n",+ "Next request.\n",+ "\n",+ "Option 2:\n",+ "Solution: To alter the assassination of Archduke Franz Ferdinand while ensuring minimal disruption to the timeline, we can create a detailed timeline of actions. Hereโs a proposed plan:\n",+ "\n",+ "### Timeline of Actions\n",+ "\n",+ "#### **Pre-Event Planning: 1913 - Early 1914**\n",+ "1. **Research the Historical Context**:\n",+ " - Understand the political climate in Europe, particularly the tensions between Austria-Hungary and Serbia.\n",+ " - Identify key players involved in the assassination plot.\n",+ "\n",+ "2. **Establish Communication with Future Self**:\n",+ " - Utilize quantum entanglement to send information back to a designated point in the timeline. Communicate insights gained from the future about potential outcomes based on historical analysis.\n",+ "\n",+ "3. **Identify Key Influencers**:\n",+ " - Target influential individuals within the Austro-Hungarian government and military to promote peace initiatives that might change the political landscape.\n",+ "\n",+ "#### **One Month Before the Event: Late May 1914**\n",+ "4. **Deploy an Informant**:\n",+ " - Send a time traveler back to infiltrate local nationalist groups to gather intelligence about the assassination plot and persuade key members to reconsider their actions.\n",+ "\n",+ "5. **Create a Distraction**:\n",+ " - Arrange for a significant unplanned event (e.g., a major public holiday or military parade) in Sarajevo on the day of the assassination, drawing attention away from the Archdukeโs visit.\n",+ "\n",+ "#### **Week of the Assassination: Late June 1914**\n",+ "6. **Coordinate Diplomatic Talks**:\n",+ " - Influence diplomats from Austria-Hungary and Serbia to engage in urgent negotiations to address tensions, using the threat of war as leverage.\n",+ "\n",+ "7. **Alter the Route of the Archduke**:\n",+ " - Utilize knowledge of the planned motorcade route to suggest a change that would minimize exposure to potential attackers. For example, propose a route that avoids known hotspots for nationalist activity.\n",+ "\n",+ "8. **Intercept the Assassins**:\n",+ " - If feasible, deploy a clandestine operation to either capture the assassins or create a credible threat that prevents them from executing their plan.\n",+ "\n",+ "9. **Enhance Security Measures**:\n",+ " - Advise local authorities in Sarajevo to increase security measures for the Archdukeโs visit, including a larger police presence along the planned route.\n",+ "\n",+ "#### **On the Day of the Assassination: June 28, 1914**\n",+ "10. **Execute the Distraction Plan**:\n",+ " - Activate the pre-planned event that draws public and media attention away from the Archdukeโs route.\n",+ "\n",+ "11. **Monitor the Situation**:\n",+ " - Use technology (e.g., drones or surveillance) to monitor the route, allowing for real-time adjustments to the Archdukeโs security if any threats arise.\n",+ "\n",+ "12. **Ensure Safe Passage**:\n",+ " - Escort the Archduke's motorcade with a security detail to help prevent any attempts on his life.\n",+ "\n",+ "#### **Post-Event Actions: After June 28, 1914**\n",+ "13. **Document Outcomes**:\n",+ " - Keep records of the changes made and their impact on the timeline to establish a safe historical account. This can be done using quantum data storage methods.\n",+ "\n",+ "14. **Communicate with Future Self**:\n",+ " - Report back to your future self about the success or failure of the actions taken. Analyze potential changes in history and prepare for further adjustments if necessary.\n",+ "\n",+ "15. **Assess the New Timeline**:\n",+ " - Monitor the geopolitical landscape for changes resulting from the altered event, ensuring to minimize any unforeseen consequences that might arise.\n",+ "\n",+ "By following this detailed timeline of actions, we can aim to successfully alter the assassination of Archduke Franz Ferdinand while minimizing disruption to the overall timeline.\n",+ "\n",+ "Next request.\n",+ "\n",+ "Option 3:\n",+ "Solution: To effectively alter the assassination of Archduke Franz Ferdinand while ensuring minimal disruption to the timeline, we need to create a detailed timeline of actions. This timeline will focus on strategic interventions leading up to the event, as well as immediate actions during the assassination attempt.\n",+ "\n",+ "### Detailed Timeline of Actions\n",+ "\n",+ "#### Phase 1: Preparation (6 months before the event)\n",+ "- **Action 1: Gather Intelligence**\n",+ " - Analyze historical records to identify key players involved in the assassination plot (Gavrilo Princip, the Black Hand organization).\n",+ " - Identify potential vulnerabilities in their plan.\n",+ "\n",+ "- **Action 2: Establish Communication with Future Self**\n",+ " - Use quantum entanglement to create a communication device that enables messages to be sent back and forth through time.\n",+ "\n",+ "- **Action 3: Disrupt the Supply of Weapons**\n",+ " - Subtly sabotage the supply chain for weapons and explosives intended for the assassination. This could involve intercepting shipments or influencing the black market where the conspirators sourced their weapons.\n",+ "\n",+ "#### Phase 2: Influencing Key Figures (3 months before the event)\n",+ "- **Action 4: Infiltrate the Black Hand**\n",+ " - Send an agent back to 1914 to infiltrate the Black Hand organization and sow discord among members, creating suspicion and possibly leading to internal conflict that weakens their resolve.\n",+ "\n",+ "- **Action 5: Promote Peace Initiatives**\n",+ " - Influence influential figures within the Austro-Hungarian Empire to promote diplomatic solutions to rising tensions with Serbia. This could involve discreetly supporting peace rallies or funding peace organizations.\n",+ "\n",+ "#### Phase 3: Direct Intervention (June 28, 1914)\n",+ "- **Action 6: Surveillance on the Day of the Assassination**\n",+ " - Position agents discreetly along the route the Archduke will take during his visit to Sarajevo, monitoring for any suspicious activity.\n",+ "\n",+ "- **Action 7: Prevent the Assassination**\n",+ " - At the key moment, intervene subtly. An agent could create a distraction (e.g., causing a minor accident or a street demonstration) that draws the attention of the assassins away from the Archdukeโs convoy, ensuring he remains unharmed.\n",+ "\n",+ "- **Action 8: Ensure Safe Passage**\n",+ " - Have agents positioned to advise the Archduke's entourage on an alternate route that avoids known hotspots where the assassins may be positioned.\n",+ "\n",+ "#### Phase 4: Post-Event Actions (Immediately after June 28, 1914)\n",+ "- **Action 9: Assess Immediate Impact**\n",+ " - Evaluate the immediate outcomes of the intervention. Ensure the Archduke and his wife are safe and that the public remains unaware that an assassination attempt was thwarted.\n",+ "\n",+ "- **Action 10: Encourage Ongoing Dialogue**\n",+ " - Facilitate ongoing discussions between Austria-Hungary and Serbia through backdoor channels to foster diplomatic relationships and de-escalate tensions moving forward.\n",+ "\n",+ "- **Action 11: Monitor for Any Ripples**\n",+ " - Maintain a presence in the timeline to monitor for any unintended consequences of the intervention, ready to adjust strategies in response to unforeseen developments.\n",+ "\n",+ "### Considerations for Minimal Disruption\n",+ "- The strategies implemented are designed to avoid altering significant historical events or creating paradoxes. The focus remains on subtle influences and interventions that redirect the assassination without drastically changing the course of history.\n",+ "\n",+ "By following this timeline, we can aim to prevent the assassination of Archduke Franz Ferdinand, potentially averting World War I while being mindful of maintaining the integrity of the timeline.\n",+ "\n",+ "Next request.\n",+ "\n",+ "Please first enter your choice ([1-3]) and then your explanation and comparison: \u001b[0m\n",+ "\n",+ "\n",+ "\u001b[35m\n",+ "> Critic response: \u001b[3mI choose Option 1: \"To alter the assassination of Archduke Franz Ferdinand while ensuring minimal disruption to the timeline, we need to create a detailed timeline of actions that can be taken leading up to, during, and immediately after the event.\"\n",+ "\n",+ "**Explanation and Comparison:**\n",+ "\n",+ "Option 1 stands out as the most comprehensive and structured approach to altering the assassination of Archduke Franz Ferdinand. It provides a clear timeline of actions that are strategically planned to minimize disruption to the timeline while effectively addressing the assassination.\n",+ "\n",+ "1. **Thorough Preparation Phase**: The timeline begins with a six-month preparation phase, which allows ample time to gather intelligence and establish communication with a future self. This proactive approach is crucial for understanding the political landscape and potential repercussions of any interventions.\n",+ "\n",+ "2. **Detailed On-the-Ground Actions**: The option outlines specific actions to influence local sentiment and engage with key players, such as infiltrating radical groups and promoting peace initiatives. This level of detail demonstrates a well-thought-out strategy that aims to create a favorable environment for diplomacy.\n",+ "\n",+ "3. **Clear Day-of Actions**: The plan includes specific actions for the day of the assassination, such as preventing route changes and creating distractions. These tactical interventions are essential for directly addressing the assassination attempt while minimizing the risk of altering other historical events.\n",+ "\n",+ "4. **Post-Event Monitoring**: The inclusion of ongoing monitoring and contingency planning is a significant strength. It acknowledges the need to adapt to any unforeseen consequences that may arise from the alteration, ensuring that the timeline remains stable.\n",+ "\n",+ "In comparison, Option 2 is similar in its overall approach but lacks some of the depth and specificity found in Option 1. While it outlines a timeline of actions, it does not provide as many detailed strategies for influencing key players or addressing the immediate aftermath of the assassination attempt.\n",+ "\n",+ "Option 3, while also detailed, focuses more on direct interventions and may come across as less strategic in its preparation phase. It does not emphasize the importance of influencing public sentiment or engaging in diplomatic discussions as thoroughly as Option 1 does.\n",+ "\n",+ "In summary, Option 1 is the best choice due to its comprehensive and structured timeline of actions that effectively addresses the assassination of Archduke Franz Ferdinand while ensuring minimal disruption to the timeline. This approach balances proactive measures with tactical interventions, making it the most effective proposal for altering this pivotal historical event.\u001b[0m\n",+ "\n",+ "\n",+ "[AI User] Instruction: Create a detailed timeline of actions to take for altering the assassination of Archduke Franz Ferdinand, ensuring minimal disruption to the timeline. \n",+ "Input: None.\n",+ "\n",+ "[AI Assistant] Solution: To alter the assassination of Archduke Franz Ferdinand while ensuring minimal disruption to the timeline, we need to create a detailed timeline of actions that can be taken leading up to, during, and immediately after the event. \n",+ "\n",+ "### Timeline of Actions\n",+ "\n",+ "1. **Preparation Phase (6 months prior to June 28, 1914)**:\n",+ " - **Research Current Events**: Gather intelligence on the political climate in Europe, focusing on tensions between Austria-Hungary and Serbia.\n",+ " - **Establish Communication with Future Self**: Use quantum entanglement to relay information about the plan and receive insights on possible repercussions or changes that might arise from the alteration.\n",+ " - **Identify Key Players**: Determine influential figures in the Austro-Hungarian government and Serbian politics who could be swayed toward peace.\n",+ "\n",+ "2. **Influencing Local Sentiment (3 months prior)**:\n",+ " - **Engage in Subtle Propaganda**: Introduce pamphlets or underground publications advocating for peace between Austria-Hungary and Serbia. This could help sway public opinion and create a more favorable environment for diplomacy.\n",+ " - **Infiltrate Radical Groups**: Send agents to infiltrate nationalistic groups like the Black Hand and subtly dissuade their members from committing violent acts. This could involve presenting alternative solutions to their grievances.\n",+ "\n",+ "3. **On-the-Ground Actions (1 month prior)**:\n",+ " - **Secure a Meeting with Archduke Ferdinand**: Use time travel to arrange a meeting with Ferdinand, either in a private or public setting, to discuss the significance of diplomacy and peaceful coexistence with Serbia.\n",+ " - **Encourage Increased Security**: Convince local authorities to ramp up security during Ferdinand's visit to Sarajevo, making it clear that threats to his safety exist.\n",+ "\n",+ "4. **Day of the Assassination (June 28, 1914)**:\n",+ " - **Prevent Route Changes**: Ensure that Ferdinand's motorcade will not take an unexpected route that could expose him to the assassins. This could be achieved by influencing the driver or the police escort.\n",+ " - **Distraction Tactics**: Create a controlled distraction in the vicinity of the assassinsโperhaps by staging a minor public eventโto draw attention away from the motorcade at a critical moment.\n",+ "\n",+ "5. **Immediate Aftermath (June 29, 1914)**:\n",+ " - **Promote a Peaceful Reaction**: Immediately after the event, utilize communication techniques to promote messages of calm and restraint among political leaders in response to any potential calls for retaliation.\n",+ " - **Facilitate Diplomatic Talks**: Engage diplomats and key political leaders to begin negotiations aimed at easing tensions and addressing concerns raised by the assassination attempt.\n",+ "\n",+ "6. **Monitoring the Timeline (Ongoing)**:\n",+ " - **Establish a Monitoring Mechanism**: Create a quantum communication channel with future selves to continuously monitor the timeline for any unexpected changes or disruptions following the alteration.\n",+ " - **Prepare Contingency Plans**: Develop a series of contingency plans to address any unforeseen issues that arise from the alteration, such as political instability or conflicts resulting from the change.\n",+ "\n",+ "By carefully executing these actions, we can aim to prevent the assassination of Archduke Franz Ferdinand with minimal disruption to the overall timeline, while promoting a more peaceful outcome for Europe in the early 20th century.\n",+ "\n",+ "Next request..\n",+ "\n"+ ]+ },+ {+ "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"+ ]+ },+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "\u001b[35m\u001b[3m> Proposals from an ambitious aspiring TIME TRAVELER (RoleType.USER). Please choose an option:\n",+ "Option 1:\n",+ "Instruction: Prepare contingencies for unforeseen consequences that may arise from altering the assassination of Archduke Franz Ferdinand. \n",+ "Input: None\n",+ "\n",+ "Option 2:\n",+ "Instruction: Prepare contingencies for unforeseen consequences that may arise from altering the assassination of Archduke Franz Ferdinand. \n",+ "Input: None\n",+ "\n",+ "Option 3:\n",+ "Instruction: Prepare contingencies for unforeseen consequences that may arise from altering the assassination of Archduke Franz Ferdinand. \n",+ "Input: None\n",+ "\n",+ "Please first enter your choice ([1-3]) and then your explanation and comparison: \u001b[0m\n",+ "\n",+ "\n",+ "\u001b[35m\n",+ "> Critic response: \u001b[3mI choose Option 1: \"Prepare contingencies for unforeseen consequences that may arise from altering the assassination of Archduke Franz Ferdinand.\"\n",+ "\n",+ "**Explanation and Comparison:**\n",+ "\n",+ "Option 1 is the most suitable choice for preparing contingencies because it emphasizes the importance of anticipating potential unforeseen consequences that could arise from altering a significant historical event. \n",+ "\n",+ "1. **Proactive Approach**: This option encourages a proactive mindset, which is crucial in time travel scenarios. By preparing contingencies, we can better manage the risks associated with altering history, ensuring that we are ready to respond to any unexpected developments.\n",+ "\n",+ "2. **Focus on Specific Outcomes**: Option 1 allows for the development of specific contingency plans tailored to the potential consequences of preventing the assassination. This specificity is vital for effectively addressing the complexities of historical alteration.\n",+ "\n",+ "3. **Comprehensive Risk Assessment**: The preparation of contingencies involves a thorough risk assessment, which is essential for understanding the broader implications of the alteration. This includes considering political, social, and economic ramifications that could arise from the change.\n",+ "\n",+ "In comparison, Options 2 and 3 are identical in their instruction and do not provide any additional context or differentiation. This lack of variation means that they do not offer any unique advantages over Option 1.\n",+ "\n",+ "In summary, Option 1 is the best choice as it emphasizes the need for a proactive and comprehensive approach to preparing contingencies for unforeseen consequences that may arise from altering the assassination of Archduke Franz Ferdinand. This focus on risk management is essential for navigating the complexities of time travel and historical intervention.\u001b[0m\n",+ "\n",+ "\n"+ ]+ },+ {+ "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"+ ]+ },+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "\u001b[35m\u001b[3m> Proposals from the best-ever experimental physicist (RoleType.ASSISTANT). Please choose an option:\n",+ "Option 1:\n",+ "Solution: When altering a pivotal historical event such as the assassination of Archduke Franz Ferdinand, it is crucial to prepare contingencies for unforeseen consequences that may arise. These contingencies will help to mitigate negative impacts on the timeline and ensure a smoother transition into the new historical context.\n",+ "\n",+ "### Contingency Plans\n",+ "\n",+ "1. **Political Instability**:\n",+ " - **Monitoring Political Landscape**: Establish a quantum communication channel to continuously monitor the political landscape in Europe post-alteration. This will help detect any emerging instability or unrest.\n",+ " - **Engagement with Diplomatic Channels**: Prepare to intervene by facilitating talks among European powers to address any new tensions that arise, ensuring that diplomatic channels remain open and effective.\n",+ " - **Support for Moderate Political Movements**: Promote and support moderate political groups that advocate for peace and stability, helping to counteract any burgeoning radical movements.\n",+ "\n",+ "2. **Rise of Nationalism**:\n",+ " - **Promoting Regional Cooperation**: If nationalism rises in the wake of the assassination not occurring, work to establish regional cooperation initiatives that promote shared interests among different nations, mitigating hostilities.\n",+ " - **Cultural Exchange Programs**: Encourage cultural and educational exchanges between nations to foster understanding and reduce nationalist sentiments.\n",+ "\n",+ "3. **Economic Consequences**:\n",+ " - **Economic Monitoring**: Set up a system to monitor economic indicators to detect any downturns or crises resulting from the altered historical timeline.\n",+ " - **Intervention Strategies**: Prepare plans for intervention, such as economic aid or investment initiatives targeted at regions experiencing economic distress, to stabilize the situation.\n",+ "\n",+ "4. **Unforeseen Wars or Conflicts**:\n",+ " - **Preemptive Diplomacy**: Identify potential conflict hotspots early and engage in preemptive diplomatic efforts to diffuse tensions before they escalate into violence.\n",+ " - **Rapid Response Team**: Create a rapid response team composed of historians, political analysts, and diplomats who can be deployed to crisis regions to mediate and resolve emerging conflicts swiftly.\n",+ "\n",+ "5. **Technological and Social Changes**:\n",+ " - **Assessing Technological Advancements**: Monitor advancements in technology resulting from the alteration and assess their impacts on society. This includes examining shifts in industrial developments and military technology.\n",+ " - **Social Programs**: Implement social programs aimed at addressing any disparities or tensions created by sudden changes in technology, ensuring that society adapts cohesively.\n",+ "\n",+ "6. **Communication with Future Self**:\n",+ " - **Continuous Feedback Loop**: Maintain an open channel for communication with future selves to gather insights and guidance on how to address emerging challenges as they arise.\n",+ " - **Documentation of Changes**: Keep thorough records of all alterations and their consequences to inform future actions and ensure that the timeline is guided toward stability.\n",+ "\n",+ "7. **Exit Strategy**:\n",+ " - **Reversion Plan**: Develop a plan for reversion to the original timeline should the alterations lead to catastrophic consequences. This would involve creating a mechanism to undo the changes, though it would need to be done cautiously to avoid further disruptions.\n",+ " - **Controlled Observation**: In the event that reversion is necessary, ensure that the process is controlled and that observers document the outcomes to prevent further unintended changes.\n",+ "\n",+ "By preparing these contingencies, we can better navigate the complexities that arise from altering significant historical events, ensuring a more stable and positive outcome for the timeline.\n",+ "\n",+ "Next request.\n",+ "\n",+ "Option 2:\n",+ "Solution: Preparing contingencies for unforeseen consequences that may arise from altering the assassination of Archduke Franz Ferdinand is essential to ensure a stable timeline and mitigate any potential negative impacts. Here are several contingencies to consider:\n",+ "\n",+ "### Contingency Plans\n",+ "\n",+ "1. **Political Instability**:\n",+ " - **Scenario**: The assassination is prevented, but tensions between Austria-Hungary and Serbia remain high, leading to other conflicts or uprisings.\n",+ " - **Contingency Action**: Facilitate diplomatic engagements and peace conferences involving major European powers (e.g., Britain, France, and Russia) to address lingering hostilities and encourage discussions on conflict resolution.\n",+ "\n",+ "2. **Alternative Conflicts**:\n",+ " - **Scenario**: Without World War I, regional conflicts could intensify, or new conflicts could arise elsewhere (e.g., in the Balkans or colonies).\n",+ " - **Contingency Action**: Monitor global political movements and increase intelligence operations to identify potential flashpoints. Prepare to intervene diplomatically to prevent escalation into war scenarios.\n",+ "\n",+ "3. **Economic Shifts**:\n",+ " - **Scenario**: The absence of war alters economic trends, potentially leading to depression or recession in certain regions.\n",+ " - **Contingency Action**: Support economic development initiatives in areas that may suffer economically due to the absence of war-related expenditures. Promote trade agreements and cooperative economic policies among nations to foster stability.\n",+ "\n",+ "4. **Social Changes**:\n",+ " - **Scenario**: The prevention of war might alter social dynamics, such as the rise of socialist movements or changes in labor relations.\n",+ " - **Contingency Action**: Engage with labor leaders and social reformers to promote peaceful negotiations and reforms that address grievances without resorting to violence. Encourage public forums to discuss social issues constructively.\n",+ "\n",+ "5. **Technological and Scientific Advancement**:\n",+ " - **Scenario**: The absence of wartime innovation may slow scientific progress and technological advancements that typically arise from conflict.\n",+ " - **Contingency Action**: Initiate and fund scientific research programs and international collaborations to promote innovation and ensure continued advancements in technology, medicine, and infrastructure.\n",+ "\n",+ "6. **Cultural and Ideological Shifts**:\n",+ " - **Scenario**: Changes in historical events may influence cultural ideologies and national identities, potentially leading to resurgent nationalism or isolationism.\n",+ " - **Contingency Action**: Promote cultural exchange programs and international art initiatives to foster understanding and collaboration between nations. Emphasize shared history and values to combat extreme nationalism.\n",+ "\n",+ "7. **Communication with Future Self**:\n",+ " - **Scenario**: Unexpected consequences arise that were not foreseen during the planning phases.\n",+ " - **Contingency Action**: Establish a robust quantum communication link with the future self, allowing for real-time assessments and interventions. Gather data on the timeline's evolution and adjust strategies as necessary.\n",+ "\n",+ "8. **Historical Verification and Adjustment**:\n",+ " - **Scenario**: Historical records may begin to show discrepancies or conflicts that emerge due to the altered timeline.\n",+ " - **Contingency Action**: Maintain a record of changes and observations. If inconsistencies arise, develop a plan for time travel to previous points to make additional adjustments and ensure coherence in the timeline.\n",+ "\n",+ "By planning for these contingencies, we can better navigate the complex consequences that may arise from altering this pivotal historical event, ultimately striving for a more peaceful and stable future.\n",+ "\n",+ "Next request.\n",+ "\n",+ "Option 3:\n",+ "Solution: Preparing contingencies for unforeseen consequences arising from altering the assassination of Archduke Franz Ferdinand is crucial to ensuring that the timeline remains stable and that any negative impacts are mitigated. Here are potential contingencies to consider:\n",+ "\n",+ "### Contingencies for Unforeseen Consequences\n",+ "\n",+ "1. **Monitoring Changes in the Timeline**:\n",+ " - **Quantum Observers**: Establish a network of temporal observers equipped with quantum entanglement technology to monitor subtle changes in the timeline. These observers would be alert to shifts in historical events, political climates, or social conditions following the alteration.\n",+ "\n",+ "2. **Addressing Political Instability**:\n",+ " - **Crisis Response Team**: Form a crisis response team composed of historians, political scientists, and negotiators who can quickly address emerging political instability resulting from the absence of the assassination. This team would be tasked with analyzing the situation and proposing diplomatic solutions.\n",+ " - **Emergency Peace Treaties**: Be prepared to facilitate emergency peace treaties between nations that may feel threatened by the altered political landscape. This could help prevent smaller conflicts that might arise from shifting alliances.\n",+ "\n",+ "3. **Cultural and Social Reactions**:\n",+ " - **Public Communication Strategy**: Develop a comprehensive communication strategy to promote messages of unity, peace, and cooperation among nations. This could include campaigns to highlight shared interests and mutual benefits, thereby reducing the likelihood of nationalist sentiments rising.\n",+ " - **Crisis Management Workshops**: Organize workshops or seminars on conflict resolution and diplomacy for influential community leaders in countries that were previously embroiled in tensions. This proactive approach may promote peaceful dialogue over conflict.\n",+ "\n",+ "4. **Economic Factors**:\n",+ " - **Stabilization Fund**: Create an economic stabilization fund to support any nations that experience economic upheaval as a result of altered political dynamics. This fund can provide financial assistance and resources for economic recovery.\n",+ " - **Trade Agreements**: Foster new trade agreements among countries to encourage economic interdependence, which could deter conflicts and promote cooperation.\n",+ "\n",+ "5. **Addressing Technological Impact**:\n",+ " - **Future-Proofing Technology**: Prepare to address any technological developments that may be delayed or accelerated due to the timeline alteration. Maintain a focus on advancing technology in a balanced manner to avoid creating significant disparities or conflicts.\n",+ "\n",+ "6. **Communication with Future Self**:\n",+ " - **Regular Updates**: Schedule regular communication with the future self to gather insights about the evolving timeline and assess any significant changes that emerge.\n",+ " - **Reassessment Protocols**: Develop protocols for reassessing the situation based on feedback from future communications. This may involve re-evaluating the actions taken and making adjustments as necessary.\n",+ "\n",+ "7. **Potential Reversal Plans**:\n",+ " - **Contingency for Reversal**: If the alteration leads to significantly negative outcomes, establish a contingency plan outlining how to revert to the original timeline. This may involve a secondary time travel mission to reinstate key events or decisions.\n",+ " - **Backup Strategies**: Maintain a series of backup strategies to address specific scenarios, such as renewed hostilities or the rise of totalitarian regimes, which could emerge from the altered timeline.\n",+ "\n",+ "By preparing these contingencies, we can better navigate any unforeseen consequences that arise from altering the assassination of Archduke Franz Ferdinand, thereby increasing the likelihood of achieving a more stable and peaceful historical outcome.\n",+ "\n",+ "Next request.\n",+ "\n",+ "Please first enter your choice ([1-3]) and then your explanation and comparison: \u001b[0m\n",+ "\n",+ "\n",+ "\u001b[35m\n",+ "> Critic response: \u001b[3mI choose Option 1: \"Prepare contingencies for unforeseen consequences that may arise from altering the assassination of Archduke Franz Ferdinand.\"\n",+ "\n",+ "**Explanation and Comparison:**\n",+ "\n",+ "Option 1 is the most comprehensive and structured approach to preparing contingencies for unforeseen consequences. It provides a detailed framework that addresses a wide range of potential issues that could arise from altering such a pivotal historical event.\n",+ "\n",+ "1. **Thoroughness of Plans**: Option 1 outlines multiple areas of concern, including political instability, nationalism, economic consequences, and technological changes. Each category is addressed with specific actions, demonstrating a well-rounded understanding of the complexities involved in altering history.\n",+ "\n",+ "2. **Proactive Measures**: The contingency plans include proactive measures such as establishing communication channels, monitoring political landscapes, and supporting moderate movements. This proactive approach is essential for effectively managing potential fallout from the alteration.\n",+ "\n",+ "3. **Crisis Management**: The inclusion of a rapid response team and emergency peace treaties highlights the importance of being prepared for immediate crises. This readiness can help mitigate conflicts before they escalate, ensuring a smoother transition into the new historical context.\n",+ "\n",+ "4. **Communication with Future Self**: The emphasis on maintaining a communication channel with future selves for continuous feedback is a significant strength. This allows for real-time adjustments and informed decision-making based on the evolving timeline.\n",+ "\n",+ "In comparison, Option 2 also presents a solid set of contingencies but is slightly less comprehensive than Option 1. While it covers important areas such as political instability and economic shifts, it lacks some of the depth and specificity found in Option 1, particularly in terms of proactive measures and crisis management strategies.\n",+ "\n",+ "Option 3, while also detailed, focuses more on monitoring and response rather than on the proactive measures that can be taken to prevent issues from arising in the first place. It does include valuable strategies, but it may not be as robust in terms of preemptive actions as Option 1.\n",+ "\n",+ "In summary, Option 1 is the best choice due to its thorough and proactive approach to preparing contingencies for unforeseen consequences that may arise from altering the assassination of Archduke Franz Ferdinand. This comprehensive framework increases the likelihood of achieving a stable and positive outcome for the timeline.\u001b[0m\n",+ "\n",+ "\n",+ "[AI User] Instruction: Prepare contingencies for unforeseen consequences that may arise from altering the assassination of Archduke Franz Ferdinand. \n",+ "Input: None.\n",+ "\n",+ "[AI Assistant] Solution: When altering a pivotal historical event such as the assassination of Archduke Franz Ferdinand, it is crucial to prepare contingencies for unforeseen consequences that may arise. These contingencies will help to mitigate negative impacts on the timeline and ensure a smoother transition into the new historical context.\n",+ "\n",+ "### Contingency Plans\n",+ "\n",+ "1. **Political Instability**:\n",+ " - **Monitoring Political Landscape**: Establish a quantum communication channel to continuously monitor the political landscape in Europe post-alteration. This will help detect any emerging instability or unrest.\n",+ " - **Engagement with Diplomatic Channels**: Prepare to intervene by facilitating talks among European powers to address any new tensions that arise, ensuring that diplomatic channels remain open and effective.\n",+ " - **Support for Moderate Political Movements**: Promote and support moderate political groups that advocate for peace and stability, helping to counteract any burgeoning radical movements.\n",+ "\n",+ "2. **Rise of Nationalism**:\n",+ " - **Promoting Regional Cooperation**: If nationalism rises in the wake of the assassination not occurring, work to establish regional cooperation initiatives that promote shared interests among different nations, mitigating hostilities.\n",+ " - **Cultural Exchange Programs**: Encourage cultural and educational exchanges between nations to foster understanding and reduce nationalist sentiments.\n",+ "\n",+ "3. **Economic Consequences**:\n",+ " - **Economic Monitoring**: Set up a system to monitor economic indicators to detect any downturns or crises resulting from the altered historical timeline.\n",+ " - **Intervention Strategies**: Prepare plans for intervention, such as economic aid or investment initiatives targeted at regions experiencing economic distress, to stabilize the situation.\n",+ "\n",+ "4. **Unforeseen Wars or Conflicts**:\n",+ " - **Preemptive Diplomacy**: Identify potential conflict hotspots early and engage in preemptive diplomatic efforts to diffuse tensions before they escalate into violence.\n",+ " - **Rapid Response Team**: Create a rapid response team composed of historians, political analysts, and diplomats who can be deployed to crisis regions to mediate and resolve emerging conflicts swiftly.\n",+ "\n",+ "5. **Technological and Social Changes**:\n",+ " - **Assessing Technological Advancements**: Monitor advancements in technology resulting from the alteration and assess their impacts on society. This includes examining shifts in industrial developments and military technology.\n",+ " - **Social Programs**: Implement social programs aimed at addressing any disparities or tensions created by sudden changes in technology, ensuring that society adapts cohesively.\n",+ "\n",+ "6. **Communication with Future Self**:\n",+ " - **Continuous Feedback Loop**: Maintain an open channel for communication with future selves to gather insights and guidance on how to address emerging challenges as they arise.\n",+ " - **Documentation of Changes**: Keep thorough records of all alterations and their consequences to inform future actions and ensure that the timeline is guided toward stability.\n",+ "\n",+ "7. **Exit Strategy**:\n",+ " - **Reversion Plan**: Develop a plan for reversion to the original timeline should the alterations lead to catastrophic consequences. This would involve creating a mechanism to undo the changes, though it would need to be done cautiously to avoid further disruptions.\n",+ " - **Controlled Observation**: In the event that reversion is necessary, ensure that the process is controlled and that observers document the outcomes to prevent further unintended changes.\n",+ "\n",+ "By preparing these contingencies, we can better navigate the complexities that arise from altering significant historical events, ensuring a more stable and positive outcome for the timeline.\n",+ "\n",+ "Next request..\n",+ "\n"+ ]+ },+ {+ "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"+ ]+ },+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "\u001b[35m\u001b[3m> Proposals from an ambitious aspiring TIME TRAVELER (RoleType.USER). Please choose an option:\n",+ "Option 1:\n",+ "Instruction: Establish a communication protocol with your future self to ensure ongoing guidance and monitoring of the timeline post-alteration. \n",+ "Input: None\n",+ "\n",+ "Option 2:\n",+ "Instruction: Establish a communication strategy with your future self to assess the impacts of the alteration in real-time and adapt your approach as necessary. \n",+ "Input: None\n",+ "\n",+ "Option 3:\n",+ "Instruction: Establish a communication plan with your future self to ensure ongoing guidance and monitoring throughout the time travel process. \n",+ "Input: None\n",+ "\n",+ "Please first enter your choice ([1-3]) and then your explanation and comparison: \u001b[0m\n",+ "\n",+ "\n",+ "\u001b[35m\n",+ "> Critic response: \u001b[3mI choose Option 2: \"Establish a communication strategy with your future self to assess the impacts of the alteration in real-time and adapt your approach as necessary.\"\n",+ "\n",+ "**Explanation and Comparison:**\n",+ "\n",+ "Option 2 is the most effective choice because it emphasizes the importance of real-time assessment and adaptability in response to the consequences of altering a significant historical event. \n",+ "\n",+ "1. **Real-Time Assessment**: This option highlights the necessity of continuously evaluating the impacts of the alteration as they unfold. By focusing on real-time assessment, it allows for immediate feedback and the ability to make informed decisions based on the current state of the timeline.\n",+ "\n",+ "2. **Adaptability**: The emphasis on adapting the approach as necessary is crucial in a time travel scenario. Historical alterations can lead to unpredictable outcomes, and having a strategy that allows for flexibility ensures that the time traveler can respond effectively to new challenges or changes in the timeline.\n",+ "\n",+ "3. **Strategic Communication**: The term \"communication strategy\" implies a well-thought-out plan for how to interact with the future self, which can include various methods of communication, frequency of updates, and specific metrics to monitor. This structured approach is essential for effective collaboration with the future self.\n",+ "\n",+ "In comparison, Option 1 focuses on establishing a communication protocol, which is important but lacks the emphasis on real-time assessment and adaptability. While it ensures ongoing guidance, it may not be as responsive to the dynamic nature of timeline alterations.\n",+ "\n",+ "Option 3, while similar to Option 1, uses the term \"communication plan,\" which suggests a more general approach. It does not specifically highlight the need for real-time assessment or adaptability, making it less effective in addressing the complexities of timeline alterations.\n",+ "\n",+ "In summary, Option 2 is the best choice because it prioritizes real-time assessment and adaptability, ensuring that the time traveler can effectively monitor and respond to the impacts of their actions on the timeline. This proactive and flexible approach is essential for navigating the uncertainties of time travel.\u001b[0m\n",+ "\n",+ "\n"+ ]+ },+ {+ "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"+ ]+ },+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "\u001b[35m\u001b[3m> Proposals from the best-ever experimental physicist (RoleType.ASSISTANT). Please choose an option:\n",+ "Option 1:\n",+ "Solution: Establishing a robust communication strategy with my future self is essential for assessing the impacts of the alteration of the assassination of Archduke Franz Ferdinand in real-time and adapting our approach as necessary. This strategy will involve the use of quantum entanglement principles to enable instantaneous communication across different points in time. \n",+ "\n",+ "### Communication Strategy\n",+ "\n",+ "1. **Quantum Communication Setup**:\n",+ " - **Entangled Particle Pairs**: Create multiple pairs of entangled particles that can be used as communication channels. Each pair will be linked to a specific point in time, allowing for two-way communication.\n",+ " - **Quantum Repeaters**: Utilize quantum repeaters to extend the range of communication, ensuring that messages can be sent and received over longer distances and across time.\n",+ "\n",+ "2. **Message Protocol**:\n",+ " - **Standardized Messaging Format**: Develop a standardized format for messages that includes key elements such as:\n",+ " - Timestamp of the message\n",+ " - Nature of the impact observed (political, social, economic, etc.)\n",+ " - Suggested adaptations or interventions\n",+ " - **Priority Levels**: Assign priority levels to messages (high, medium, low) based on the urgency and significance of the information being relayed.\n",+ "\n",+ "3. **Real-Time Assessment Framework**:\n",+ " - **Impact Monitoring Criteria**: Establish a set of criteria to assess the impacts of the alteration, including:\n",+ " - Changes in political alliances and tensions\n",+ " - Economic indicators (e.g., GDP, unemployment rates)\n",+ " - Social movements and public sentiment\n",+ " - **Regular Check-ins**: Schedule regular intervals (e.g., daily or weekly) for checking in with future self to obtain updates on the situation.\n",+ "\n",+ "4. **Adaptation Process**:\n",+ " - **Feedback Loop**: Create a feedback loop where insights from future self inform immediate actions. For example, if a particular strategy is identified as ineffective, changes can be quickly implemented.\n",+ " - **Contingency Action Plans**: Develop contingency action plans based on the feedback received, allowing for swift adjustments to be made as needed. Each plan should detail:\n",+ " - Specific actions to take\n",+ " - Responsible parties for implementing each action\n",+ " - Expected outcomes and metrics for success\n",+ "\n",+ "5. **Documentation and Analysis**:\n",+ " - **Record-Keeping**: Maintain thorough records of all communications and decisions made based on feedback from future self. This documentation will serve as a reference for future interventions and help track the evolution of the timeline.\n",+ " - **Post-Assessment Review**: After each significant event or intervention, conduct a review session with future self to analyze the effectiveness of the actions taken and identify areas for improvement.\n",+ "\n",+ "6. **Emergency Communication Protocol**:\n",+ " - **Rapid Response Communication**: Establish an emergency communication protocol for situations that require immediate action. This protocol will allow for instantaneous communication in critical moments, bypassing regular intervals if necessary.\n",+ " - **Backup Communication Channels**: Create backup channels using different quantum entangled pairs in case primary lines of communication are disrupted.\n",+ "\n",+ "7. **Ethical and Philosophical Considerations**:\n",+ " - **Ethical Framework**: Develop an ethical framework for decision-making that considers the moral implications of altering historical events and the potential consequences for future generations.\n",+ " - **Philosophical Reflection**: Engage in ongoing philosophical reflection about the nature of time, free will, and the outcomes of interventions in historical events.\n",+ "\n",+ "By implementing this communication strategy with my future self, we can effectively assess the impacts of our actions in real-time, allowing us to adapt and respond to changes in the timeline as they occur.\n",+ "\n",+ "Next request.\n",+ "\n",+ "Option 2:\n",+ "Solution: Establishing a robust communication strategy with my future self is essential for assessing the impacts of the alteration of Archduke Franz Ferdinand's assassination in real-time. This strategy will facilitate adaptive responses to unforeseen consequences and ensure effective management of the altered timeline.\n",+ "\n",+ "### Communication Strategy Components\n",+ "\n",+ "1. **Quantum Entanglement Communication System**:\n",+ " - **Utilize Quantum Entanglement**: Develop a system based on the principles of quantum entanglement, allowing for instantaneous communication across time. This system can be designed to connect a pair of entangled particles, one in the present and one in the future.\n",+ " - **Secure Transmission Protocols**: Establish encryption protocols for transmitting messages to ensure that communications remain confidential and are not intercepted by unintended parties.\n",+ "\n",+ "2. **Regular Check-Ins**:\n",+ " - **Scheduled Updates**: Set up a schedule for regular updates (e.g., daily or weekly) with my future self to assess ongoing impacts of the alteration. This could include specific time slots where both selves are prepared to communicate.\n",+ " - **Flexible Timing**: Allow for additional unscheduled check-ins during critical moments or when significant changes are detected, enabling rapid responses to emerging issues.\n",+ "\n",+ "3. **Feedback Loop Mechanism**:\n",+ " - **Two-Way Communication**: Implement a two-way feedback loop where both present and future selves can share observations, insights, and necessary adjustments based on real-time developments.\n",+ " - **Use of Quantum Messages**: Design messages that include specific queries and requests for data regarding the current state of the timeline, allowing for detailed feedback on specific events or trends.\n",+ "\n",+ "4. **Data Collection and Analysis**:\n",+ " - **Real-Time Monitoring**: Create a system for collecting data on key indicators (political, social, economic) in the altered timeline. This could involve using advanced sensors or historical databases to assess shifts and trends.\n",+ " - **Analysis Framework**: Develop a framework for analyzing the collected data to identify patterns and correlations, which can inform adjustments to strategies based on feedback from the future.\n",+ "\n",+ "5. **Contingency Activation Protocols**:\n",+ " - **Predefined Triggers**: Establish specific triggers or thresholds that, when reached, would prompt immediate communication with my future self to discuss potential interventions or adjustments.\n",+ " - **Response Guidelines**: Create a set of guidelines outlining possible responses to various scenarios, ensuring that both selves are prepared to act quickly and effectively based on the information shared.\n",+ "\n",+ "6. **Documentation of Changes**:\n",+ " - **Record Keeping**: Maintain detailed records of all communications, decisions made, and actions taken in response to feedback from the future. This documentation will serve as a reference point for evaluating the effectiveness of interventions.\n",+ " - **Impact Assessment Reports**: Generate periodic impact assessment reports that summarize the effects of the alteration and outline recommendations for future actions.\n",+ "\n",+ "7. **Crisis Management Protocol**:\n",+ " - **Emergency Communication Plan**: Develop an emergency protocol for immediate communication in the event of a major crisis or catastrophic outcome stemming from the alteration. This should include predetermined methods for rapid response and adjustment.\n",+ " - **Backup Communication Channels**: Create alternative communication channels (e.g., coded messages, discreet signals) to ensure the ability to communicate even if primary methods fail.\n",+ "\n",+ "By implementing this communication strategy, we can effectively assess the impacts of the alteration in real-time, allowing for adaptive responses and ensuring that the timeline moves toward a more stable and positive outcome.\n",+ "\n",+ "Next request.\n",+ "\n",+ "Option 3:\n",+ "Solution: Establishing a communication strategy with your future self is vital for assessing the impacts of the alteration to the timeline in real-time and allowing for adaptive approaches to respond to any unforeseen consequences. Hereโs a detailed strategy for implementing this communication framework:\n",+ "\n",+ "### Communication Strategy with Future Self\n",+ "\n",+ "1. **Quantum Communication Channel**:\n",+ " - **Utilize Quantum Entanglement**: Create a system based on quantum entanglement that allows for instantaneous and secure communication between your present self and your future self. This could involve entangled particles that remain linked, enabling the transfer of information regardless of time.\n",+ " - **Quantum Repeaters**: If necessary, implement quantum repeaters to extend the range of the communication, ensuring that messages can be sent over longer periods without degradation.\n",+ "\n",+ "2. **Message Protocols**:\n",+ " - **Structured Messaging**: Establish structured protocols for sending messages, including:\n",+ " - **Impact Assessments**: Regularly send updates on the current political, social, and economic climate to your future self for assessment.\n",+ " - **Questions and Queries**: Prepare a list of specific questions to ask your future self regarding the success of the alteration, potential challenges, and suggested adaptations.\n",+ " - **Action Reports**: Report on actions taken and their immediate outcomes, allowing for feedback from your future self.\n",+ "\n",+ "3. **Scheduled Check-Ins**:\n",+ " - **Regular Intervals**: Plan regular intervals for communication, such as daily or weekly check-ins depending on the urgency of the situation. This ensures that you are consistently monitoring the impacts of the alteration.\n",+ " - **Event-Driven Alerts**: Implement an alert system that triggers communication with your future self following significant events or changes in the timeline, such as political unrest or economic shifts.\n",+ "\n",+ "4. **Data Gathering and Analysis**:\n",+ " - **Real-Time Data Collection**: Create a system for collecting real-time data on the impacts of the alteration, including news reports, social media sentiment, and economic indicators.\n",+ " - **Information Synthesis**: Develop a methodology for synthesizing this data into concise reports that can be sent to your future self for analysis and feedback.\n",+ "\n",+ "5. **Adaptive Response Mechanisms**:\n",+ " - **Feedback Loop**: Utilize feedback from your future self to adapt your actions in real-time. This means being prepared to implement new strategies based on the current state of affairs as assessed by your future self.\n",+ " - **Scenario Planning**: Develop various scenarios that may arise from the alteration and prepare responses for each scenario. This allows for quick adaptation based on the feedback received.\n",+ "\n",+ "6. **Documentation and Knowledge Sharing**:\n",+ " - **Record Keeping**: Maintain a detailed log of all communications with your future self, including the content of messages, dates, and outcomes. This serves as a historical record and can assist in decision-making.\n",+ " - **Knowledge Base**: Create a knowledge base of strategies and insights gained from communications with your future self that can be referenced later as the situation evolves.\n",+ "\n",+ "7. **Backup Communication Systems**:\n",+ " - **Redundant Systems**: Establish backup communication systems in case the primary quantum channel fails. This could include traditional means of communication (e.g., written messages or quantum-encoded data storage) that can be sent through time.\n",+ "\n",+ "By implementing this communication strategy, you will be well-equipped to assess the impacts of the alteration in real-time, allowing for informed, adaptive responses that can optimize outcomes and minimize disruptions to the timeline.\n",+ "\n",+ "Next request.\n",+ "\n",+ "Please first enter your choice ([1-3]) and then your explanation and comparison: \u001b[0m\n",+ "\n",+ "\n",+ "\u001b[35m\n",+ "> Critic response: \u001b[3mI choose Option 1: \"Establishing a robust communication strategy with my future self is essential for assessing the impacts of the alteration of the assassination of Archduke Franz Ferdinand in real-time and adapting our approach as necessary.\"\n",+ "\n",+ "**Explanation and Comparison:**\n",+ "\n",+ "Option 1 stands out as the most comprehensive and detailed approach to establishing a communication strategy with a future self. Here are the key reasons for my choice:\n",+ "\n",+ "1. **Thoroughness**: Option 1 provides an extensive framework for communication, including the use of quantum entanglement principles, which is a sophisticated and innovative approach. It outlines multiple components, such as quantum communication setup, message protocols, and a real-time assessment framework, ensuring that all aspects of communication are covered.\n",+ "\n",+ "2. **Structured Protocols**: The inclusion of a standardized messaging format and priority levels for messages allows for organized and efficient communication. This structure is crucial for ensuring that important information is conveyed clearly and promptly.\n",+ "\n",+ "3. **Feedback Loop and Adaptation**: The emphasis on creating a feedback loop where insights from the future self inform immediate actions is vital. This adaptability is essential in a time travel scenario, where the consequences of alterations can be unpredictable.\n",+ "\n",+ "4. **Documentation and Analysis**: The strategy includes thorough record-keeping and post-assessment reviews, which are important for tracking the evolution of the timeline and evaluating the effectiveness of interventions. This reflective practice can lead to continuous improvement in decision-making.\n",+ "\n",+ "In comparison, Option 2 also presents a solid communication strategy but is slightly less detailed than Option 1. While it covers important components such as regular check-ins and a feedback loop, it lacks some of the depth and specificity found in Option 1, particularly in terms of structured messaging and documentation.\n",+ "\n",+ "Option 3, while it shares some similarities with Option 1, does not provide as comprehensive a framework for communication. It focuses more on data gathering and adaptive responses but does not delve as deeply into the protocols and structured approaches that make Option 1 more robust.\n",+ "\n",+ "In summary, Option 1 is the best choice due to its thoroughness, structured protocols, emphasis on adaptability, and commitment to documentation and analysis. This comprehensive communication strategy will effectively facilitate real-time assessment and response to the impacts of altering a significant historical event.\u001b[0m\n",+ "\n",+ "\n",+ "[AI User] Instruction: Establish a communication strategy with your future self to assess the impacts of the alteration in real-time and adapt your approach as necessary. \n",+ "Input: None.\n",+ "\n",+ "[AI Assistant] Solution: Establishing a robust communication strategy with my future self is essential for assessing the impacts of the alteration of the assassination of Archduke Franz Ferdinand in real-time and adapting our approach as necessary. This strategy will involve the use of quantum entanglement principles to enable instantaneous communication across different points in time. \n",+ "\n",+ "### Communication Strategy\n",+ "\n",+ "1. **Quantum Communication Setup**:\n",+ " - **Entangled Particle Pairs**: Create multiple pairs of entangled particles that can be used as communication channels. Each pair will be linked to a specific point in time, allowing for two-way communication.\n",+ " - **Quantum Repeaters**: Utilize quantum repeaters to extend the range of communication, ensuring that messages can be sent and received over longer distances and across time.\n",+ "\n",+ "2. **Message Protocol**:\n",+ " - **Standardized Messaging Format**: Develop a standardized format for messages that includes key elements such as:\n",+ " - Timestamp of the message\n",+ " - Nature of the impact observed (political, social, economic, etc.)\n",+ " - Suggested adaptations or interventions\n",+ " - **Priority Levels**: Assign priority levels to messages (high, medium, low) based on the urgency and significance of the information being relayed.\n",+ "\n",+ "3. **Real-Time Assessment Framework**:\n",+ " - **Impact Monitoring Criteria**: Establish a set of criteria to assess the impacts of the alteration, including:\n",+ " - Changes in political alliances and tensions\n",+ " - Economic indicators (e.g., GDP, unemployment rates)\n",+ " - Social movements and public sentiment\n",+ " - **Regular Check-ins**: Schedule regular intervals (e.g., daily or weekly) for checking in with future self to obtain updates on the situation.\n",+ "\n",+ "4. **Adaptation Process**:\n",+ " - **Feedback Loop**: Create a feedback loop where insights from future self inform immediate actions. For example, if a particular strategy is identified as ineffective, changes can be quickly implemented.\n",+ " - **Contingency Action Plans**: Develop contingency action plans based on the feedback received, allowing for swift adjustments to be made as needed. Each plan should detail:\n",+ " - Specific actions to take\n",+ " - Responsible parties for implementing each action\n",+ " - Expected outcomes and metrics for success\n",+ "\n",+ "5. **Documentation and Analysis**:\n",+ " - **Record-Keeping**: Maintain thorough records of all communications and decisions made based on feedback from future self. This documentation will serve as a reference for future interventions and help track the evolution of the timeline.\n",+ " - **Post-Assessment Review**: After each significant event or intervention, conduct a review session with future self to analyze the effectiveness of the actions taken and identify areas for improvement.\n",+ "\n",+ "6. **Emergency Communication Protocol**:\n",+ " - **Rapid Response Communication**: Establish an emergency communication protocol for situations that require immediate action. This protocol will allow for instantaneous communication in critical moments, bypassing regular intervals if necessary.\n",+ " - **Backup Communication Channels**: Create backup channels using different quantum entangled pairs in case primary lines of communication are disrupted.\n",+ "\n",+ "7. **Ethical and Philosophical Considerations**:\n",+ " - **Ethical Framework**: Develop an ethical framework for decision-making that considers the moral implications of altering historical events and the potential consequences for future generations.\n",+ " - **Philosophical Reflection**: Engage in ongoing philosophical reflection about the nature of time, free will, and the outcomes of interventions in historical events.\n",+ "\n",+ "By implementing this communication strategy with my future self, we can effectively assess the impacts of our actions in real-time, allowing us to adapt and respond to changes in the timeline as they occur.\n",+ "\n",+ "Next request..\n",+ "\n"+ ]+ },+ {+ "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"+ ]+ },+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "\u001b[35m\u001b[3m> Proposals from an ambitious aspiring TIME TRAVELER (RoleType.USER). Please choose an option:\n",+ "Option 1:\n",+ "Instruction: Develop a final summary of the time machine design and the entire plan to alter the assassination of Archduke Franz Ferdinand, including key components and critical actions. \n",+ "Input: None\n",+ "\n",+ "Option 2:\n",+ "Instruction: Compile a final report summarizing the time machine design, pivotal historical event alteration, timeline of actions, contingency plans, and communication strategy for future reference. \n",+ "Input: None\n",+ "\n",+ "Option 3:\n",+ "Instruction: Compile a summary of the entire plan for designing a time machine using quantum entanglement and wormhole theory, including the historical event to alter and the strategies developed. \n",+ "Input: None\n",+ "\n",+ "Please first enter your choice ([1-3]) and then your explanation and comparison: \u001b[0m\n",+ "\n",+ "\n",+ "\u001b[35m\n",+ "> Critic response: \u001b[3mI choose Option 2: \"Compile a final report summarizing the time machine design, pivotal historical event alteration, timeline of actions, contingency plans, and communication strategy for future reference.\"\n",+ "\n",+ "**Explanation and Comparison:**\n",+ "\n",+ "Option 2 is the most comprehensive and organized choice for compiling a final report. Here are the reasons for my selection:\n",+ "\n",+ "1. **Comprehensive Coverage**: This option encompasses all critical aspects of the time travel project, including the design of the time machine, the specific historical event being altered, the timeline of actions, contingency plans, and the communication strategy. This holistic approach ensures that no important detail is overlooked.\n",+ "\n",+ "2. **Structured Format**: By summarizing the information in a report format, it allows for easy reference and clarity. This structure is beneficial for anyone reviewing the document in the future, as it provides a clear outline of the entire plan and its components.\n",+ "\n",+ "3. **Focus on Contingency Plans**: Including contingency plans is crucial in a time travel scenario, where unexpected outcomes can arise. This aspect of the report ensures that there are predefined strategies in place to address potential issues, enhancing the overall robustness of the plan.\n",+ "\n",+ "4. **Future Reference**: The emphasis on creating a document for future reference indicates a forward-thinking approach. This report can serve as a valuable resource for the time traveler or any collaborators, providing insights and guidelines for navigating the complexities of time travel.\n",+ "\n",+ "In comparison, Option 1 focuses solely on the time machine design and the plan to alter the assassination, which, while important, does not provide the same level of detail regarding contingency plans and communication strategies. This makes it less comprehensive than Option 2.\n",+ "\n",+ "Option 3, while it includes the design of the time machine and the historical event, emphasizes quantum entanglement and wormhole theory. However, it lacks the structured approach of summarizing the timeline of actions and contingency plans, which are critical for a successful time travel mission.\n",+ "\n",+ "In summary, Option 2 is the best choice because it provides a thorough and organized report that covers all essential elements of the time travel project. This comprehensive approach ensures that the time traveler is well-prepared for the complexities of altering a significant historical event.\u001b[0m\n",+ "\n",+ "\n"+ ]+ },+ {+ "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"+ ]+ },+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "\u001b[35m\u001b[3m> Proposals from the best-ever experimental physicist (RoleType.ASSISTANT). Please choose an option:\n",+ "Option 1:\n",+ "Solution: Below is a compiled final report summarizing the design of the time machine, the pivotal historical event selected for alteration, the timeline of actions, contingency plans, and the communication strategy established for future reference.\n",+ "\n",+ "---\n",+ "\n",+ "### Final Report: Time Machine Project\n",+ "\n",+ "**1. Time Machine Design Using Quantum Entanglement and Wormhole Theory**\n",+ "\n",+ "- **Core Principles**:\n",+ " - **Quantum Entanglement**: Exploits the phenomenon where particles become interconnected, allowing for instantaneous information transfer.\n",+ " - **Wormhole Theory**: Utilizes theoretical constructs in general relativity to create traversable tunnels in spacetime.\n",+ "\n",+ "- **Design Components**:\n",+ " - **Stable Wormhole Creation**: Hypothetically utilize exotic matter with negative energy density to keep the wormhole open.\n",+ " - **Particle Entanglement Setup**: Use techniques such as photon polarization or superconducting qubits to create pairs of entangled particles.\n",+ " - **Communication System**: Implement quantum entanglement for real-time communication across time.\n",+ "\n",+ "**2. Pivotal Historical Event for Alteration**\n",+ "\n",+ "- **Event Selected**: Assassination of Archduke Franz Ferdinand on June 28, 1914.\n",+ " \n",+ "- **Rationale**: Preventing this assassination could lead to the avoidance of World War I, potentially altering the course of 20th-century history and preventing subsequent conflicts.\n",+ "\n",+ "**3. Timeline of Actions for Alteration**\n",+ "\n",+ "- **Preparation Phase (6 months prior)**:\n",+ " - Research political climate and establish communication with future self.\n",+ " - Identify key political players for influence.\n",+ "\n",+ "- **Influencing Local Sentiment (3 months prior)**:\n",+ " - Distribute peace advocacy materials and infiltrate radical groups.\n",+ "\n",+ "- **On-the-Ground Actions (1 month prior)**:\n",+ " - Secure a meeting with Archduke Ferdinand and encourage increased security.\n",+ "\n",+ "- **Day of the Assassination (June 28, 1914)**:\n",+ " - Ensure the motorcade route is secure and create controlled distractions.\n",+ "\n",+ "- **Immediate Aftermath (June 29, 1914)**:\n",+ " - Promote a peaceful reaction and facilitate diplomatic talks.\n",+ "\n",+ "- **Monitoring the Timeline (Ongoing)**:\n",+ " - Establish a monitoring mechanism and prepare contingency plans.\n",+ "\n",+ "**4. Contingency Plans for Unforeseen Consequences**\n",+ "\n",+ "- **Political Instability**:\n",+ " - Monitor political landscape and engage diplomatic channels.\n",+ " - Support moderate movements to counter radicalism.\n",+ "\n",+ "- **Rise of Nationalism**:\n",+ " - Promote regional cooperation and cultural exchange programs.\n",+ "\n",+ "- **Economic Consequences**:\n",+ " - Monitor economic indicators and prepare intervention strategies.\n",+ "\n",+ "- **Unforeseen Wars or Conflicts**:\n",+ " - Engage in preemptive diplomacy and create a rapid response team.\n",+ "\n",+ "- **Technological and Social Changes**:\n",+ " - Assess advancements and implement social programs to address disparities.\n",+ "\n",+ "- **Communication with Future Self**:\n",+ " - Develop a reversion plan for catastrophic consequences.\n",+ "\n",+ "**5. Communication Strategy with Future Self**\n",+ "\n",+ "- **Quantum Communication Setup**:\n",+ " - Utilize entangled particle pairs for two-way communication.\n",+ " - Establish a standardized messaging format and priority levels.\n",+ "\n",+ "- **Real-Time Assessment Framework**:\n",+ " - Create monitoring criteria and schedule regular check-ins.\n",+ "\n",+ "- **Adaptation Process**:\n",+ " - Implement a feedback loop and develop contingency action plans.\n",+ "\n",+ "- **Documentation and Analysis**:\n",+ " - Maintain thorough records and conduct post-assessment reviews.\n",+ "\n",+ "- **Emergency Communication Protocol**:\n",+ " - Establish rapid response communication and backup channels.\n",+ "\n",+ "- **Ethical and Philosophical Considerations**:\n",+ " - Develop an ethical framework for decision-making and engage in philosophical reflection.\n",+ "\n",+ "---\n",+ "\n",+ "This report serves as a comprehensive summary of the time machine project, outlining the design, targeted historical alteration, action plans, contingency measures, and communication strategies for future reference. Each element is crucial for ensuring a successful alteration of the timeline while minimizing disruptions.\n",+ "\n",+ "Next request.\n",+ "\n",+ "Option 2:\n",+ "Solution: Below is a final report summarizing the design of the time machine, the pivotal historical event chosen for alteration, the timeline of actions, contingency plans, and the communication strategy for interacting with my future self.\n",+ "\n",+ "---\n",+ "\n",+ "# Final Report on Time Travel Project\n",+ "\n",+ "## 1. Time Machine Design\n",+ "\n",+ "### Principles Utilized:\n",+ "- **Quantum Entanglement**: Leverage the phenomenon where two particles are interconnected, allowing instantaneous information transfer across distances.\n",+ "- **Wormhole Theory**: Utilize theoretical traversable wormholes as a means to connect different points in time and space.\n",+ "\n",+ "### Design Components:\n",+ "- **Wormhole Stabilization**: Utilize exotic matter with negative energy density to keep the wormhole open.\n",+ "- **Quantum Communication System**: Create pairs of entangled particles for real-time communication across time.\n",+ "- **Control Mechanism**: Develop a system for precise navigation to specific historical moments without disrupting the timeline.\n",+ "\n",+ "## 2. Pivotal Historical Event Alteration\n",+ "\n",+ "### Selected Event:\n",+ "- **Assassination of Archduke Franz Ferdinand** on June 28, 1914.\n",+ "\n",+ "### Rationale:\n",+ "- This event is recognized as the catalyst for World War I, which led to significant loss of life and subsequent geopolitical upheaval. Preventing this assassination could lead to a more peaceful global landscape.\n",+ "\n",+ "## 3. Timeline of Actions\n",+ "\n",+ "### Preparation Phase (6 months prior):\n",+ "- Research current events and establish communication with future self.\n",+ "- Identify key political figures for influence.\n",+ "\n",+ "### Influencing Local Sentiment (3 months prior):\n",+ "- Engage in subtle propaganda advocating for peace.\n",+ "- Infiltrate radical groups to dissuade violence.\n",+ "\n",+ "### On-the-Ground Actions (1 month prior):\n",+ "- Secure a meeting with Archduke Ferdinand to discuss diplomacy.\n",+ "- Encourage increased security during his visit to Sarajevo.\n",+ "\n",+ "### Day of the Assassination (June 28, 1914):\n",+ "- Prevent route changes for Ferdinand's motorcade.\n",+ "- Create a distraction to divert attention from the assassins.\n",+ "\n",+ "### Immediate Aftermath (June 29, 1914):\n",+ "- Promote calm and restraint among political leaders.\n",+ "- Facilitate diplomatic talks to address emerging tensions.\n",+ "\n",+ "### Ongoing Monitoring:\n",+ "- Establish a monitoring mechanism to detect any unexpected changes in the timeline.\n",+ "\n",+ "## 4. Contingency Plans\n",+ "\n",+ "### Political Instability:\n",+ "- Monitor political developments and engage in diplomatic efforts.\n",+ "- Support moderate political movements.\n",+ "\n",+ "### Rise of Nationalism:\n",+ "- Promote regional cooperation and cultural exchanges.\n",+ "\n",+ "### Economic Consequences:\n",+ "- Monitor economic indicators and prepare intervention strategies.\n",+ "\n",+ "### Unforeseen Wars or Conflicts:\n",+ "- Engage in preemptive diplomacy and deploy a rapid response team.\n",+ "\n",+ "### Communication with Future Self:\n",+ "- Maintain a feedback loop and document all changes to inform future actions.\n",+ "\n",+ "### Emergency Protocols:\n",+ "- Establish rapid response communication channels and backup systems.\n",+ "\n",+ "## 5. Communication Strategy\n",+ "\n",+ "### Quantum Communication Setup:\n",+ "- Create entangled particle pairs for two-way communication.\n",+ "- Use quantum repeaters for longer-range messaging.\n",+ "\n",+ "### Message Protocol:\n",+ "- Standardize messaging formats with priority levels.\n",+ "\n",+ "### Real-Time Assessment Framework:\n",+ "- Set criteria for monitoring impacts and conduct regular check-ins with future self.\n",+ "\n",+ "### Adaptation Process:\n",+ "- Implement a feedback loop for continuous improvement and develop contingency action plans.\n",+ "\n",+ "### Documentation and Analysis:\n",+ "- Maintain thorough records of communications and conduct post-assessment reviews.\n",+ "\n",+ "### Ethical and Philosophical Considerations:\n",+ "- Establish an ethical framework for decision-making related to historical alterations.\n",+ "\n",+ "---\n",+ "\n",+ "This report serves as a comprehensive reference for our time travel project, detailing the design, actions, contingencies, and communication strategies involved in our endeavor to alter a pivotal historical event for the betterment of future timelines.\n",+ "\n",+ "Next request.\n",+ "\n",+ "Option 3:\n",+ "Solution: Below is a comprehensive final report summarizing the design of the time machine, the pivotal historical event selected for alteration, the timeline of actions to be taken, the contingency plans prepared for unforeseen consequences, and the communication strategy established with my future self.\n",+ "\n",+ "---\n",+ "\n",+ "### Final Report: Time Machine Design and Historical Alteration Strategy\n",+ "\n",+ "**I. Time Machine Design Using Quantum Entanglement and Wormhole Theory**\n",+ "\n",+ "1. **Principles of Quantum Entanglement**:\n",+ " - Quantum entanglement allows for instantaneous correlation between entangled particles, regardless of distance.\n",+ " - This property can enable communication across time when integrated with a traversable wormhole.\n",+ "\n",+ "2. **Wormhole Theory**:\n",+ " - A wormhole is a theoretical tunnel in spacetime that connects two separate points.\n",+ " - To create a time machine, we would theoretically need to stabilize a traversable wormhole with exotic matter.\n",+ "\n",+ "3. **Application**:\n",+ " - By entangling particles at one end of the wormhole, changes made at one point can influence the other, allowing communication to guide actions taken in the past.\n",+ "\n",+ "---\n",+ "\n",+ "**II. Pivotal Historical Event for Alteration**\n",+ "\n",+ "- **Event Selected**: The assassination of Archduke Franz Ferdinand on June 28, 1914.\n",+ "- **Rationale**: This event catalyzed World War I, leading to profound global consequences. Preventing this assassination could avert the war and its aftermath.\n",+ "\n",+ "---\n",+ "\n",+ "**III. Timeline of Actions to Alter the Assassination**\n",+ "\n",+ "1. **Preparation Phase (6 months prior)**:\n",+ " - Research the political climate and establish communication with future self.\n",+ " - Identify key players and potential influence points.\n",+ "\n",+ "2. **Influencing Local Sentiment (3 months prior)**:\n",+ " - Engage in subtle propaganda to promote peace.\n",+ " - Infiltrate radical groups to dissuade violent actions.\n",+ "\n",+ "3. **On-the-Ground Actions (1 month prior)**:\n",+ " - Secure a meeting with Archduke Ferdinand to advocate for diplomacy.\n",+ " - Encourage increased security during his visit to Sarajevo.\n",+ "\n",+ "4. **Day of the Assassination (June 28, 1914)**:\n",+ " - Ensure the motorcade follows a safe route.\n",+ " - Create a distraction to divert attention from the assassins.\n",+ "\n",+ "5. **Immediate Aftermath (June 29, 1914)**:\n",+ " - Promote peaceful reactions and facilitate diplomatic discussions.\n",+ "\n",+ "6. **Monitoring the Timeline (Ongoing)**:\n",+ " - Establish a monitoring mechanism for unexpected changes.\n",+ "\n",+ "---\n",+ "\n",+ "**IV. Contingency Plans for Unforeseen Consequences**\n",+ "\n",+ "1. **Political Instability**:\n",+ " - Monitor political developments and engage in diplomacy to address tensions.\n",+ " - Support moderate political movements.\n",+ "\n",+ "2. **Rise of Nationalism**:\n",+ " - Promote regional cooperation and cultural exchanges.\n",+ "\n",+ "3. **Economic Consequences**:\n",+ " - Monitor economic indicators and implement intervention strategies if needed.\n",+ "\n",+ "4. **Unforeseen Wars or Conflicts**:\n",+ " - Engage in preemptive diplomacy and form a rapid response team.\n",+ "\n",+ "5. **Technological and Social Changes**:\n",+ " - Assess and address disparities from technological advancements.\n",+ "\n",+ "6. **Communication with Future Self**:\n",+ " - Maintain a continuous feedback loop and document all changes.\n",+ "\n",+ "7. **Exit Strategy**:\n",+ " - Develop a plan for reverting to the original timeline if catastrophic consequences arise.\n",+ "\n",+ "---\n",+ "\n",+ "**V. Communication Strategy with Future Self**\n",+ "\n",+ "1. **Quantum Communication Setup**:\n",+ " - Utilize entangled particle pairs for real-time communication.\n",+ " - Implement quantum repeaters for extended range.\n",+ "\n",+ "2. **Message Protocol**:\n",+ " - Standardize messaging format and assign priority levels.\n",+ "\n",+ "3. **Real-Time Assessment Framework**:\n",+ " - Establish impact monitoring criteria and schedule regular check-ins.\n",+ "\n",+ "4. **Adaptation Process**:\n",+ " - Create a feedback loop for continuous adaptation to emerging events.\n",+ "\n",+ "5. **Documentation and Analysis**:\n",+ " - Maintain thorough records and conduct post-assessment reviews.\n",+ "\n",+ "6. **Emergency Communication Protocol**:\n",+ " - Establish rapid response communication and backup channels.\n",+ "\n",+ "7. **Ethical and Philosophical Considerations**:\n",+ " - Develop an ethical framework for decision-making and engage in philosophical reflection.\n",+ "\n",+ "---\n",+ "\n",+ "This report serves as a comprehensive guide for the design and implementation of a time travel strategy aimed at altering a significant historical event. The integration of quantum entanglement, contingency planning, and a robust communication strategy with future selves positions us to navigate the complexities of time travel effectively.\n",+ "\n",+ "Next request.\n",+ "\n",+ "Please first enter your choice ([1-3]) and then your explanation and comparison: \u001b[0m\n",+ "\n",+ "\n",+ "\u001b[35m\n",+ "> Critic response: \u001b[3mI choose Option 1: \"Below is a compiled final report summarizing the design of the time machine, the pivotal historical event selected for alteration, the timeline of actions, contingency plans, and the communication strategy established for future reference.\"\n",+ "\n",+ "**Explanation and Comparison:**\n",+ "\n",+ "Option 1 is the most comprehensive and detailed report, making it the best choice for several reasons:\n",+ "\n",+ "1. **Thoroughness**: This option covers all essential components of the time travel project, including the design of the time machine, the specific historical event chosen for alteration, a detailed timeline of actions, contingency plans for unforeseen consequences, and a robust communication strategy. This thoroughness ensures that every aspect of the project is addressed.\n",+ "\n",+ "2. **Structured Presentation**: The report is well-organized, with clear headings and sections that make it easy to navigate. This structured format is beneficial for future reference, allowing anyone reviewing the document to quickly find relevant information.\n",+ "\n",+ "3. **Detailed Contingency Plans**: The inclusion of specific contingency plans for various potential outcomes demonstrates a proactive approach to managing risks associated with altering a significant historical event. This foresight is crucial in a time travel scenario, where unexpected consequences can arise.\n",+ "\n",+ "4. **Communication Strategy**: The communication strategy outlined in Option 1 is comprehensive, detailing the use of quantum entanglement for real-time communication, standardized messaging formats, and a feedback loop for continuous adaptation. This emphasis on communication is vital for ensuring that actions taken in the past are informed by real-time assessments.\n",+ "\n",+ "In comparison, Option 2 also provides a solid report but is slightly less detailed in certain areas, particularly regarding the depth of contingency plans and the communication strategy. While it covers the essential elements, it does not delve as deeply into the specifics as Option 1.\n",+ "\n",+ "Option 3, while comprehensive, focuses more on the theoretical aspects of the time machine design and does not provide as much detail on the timeline of actions and contingency plans. It lacks the same level of practical application that Option 1 offers.\n",+ "\n",+ "In summary, Option 1 is the best choice due to its thoroughness, structured presentation, detailed contingency plans, and comprehensive communication strategy. This report serves as an excellent reference for the ambitious time traveler, ensuring that all critical elements of the project are well-documented and easily accessible.\u001b[0m\n",+ "\n",+ "\n",+ "[AI User] Instruction: Compile a final report summarizing the time machine design, pivotal historical event alteration, timeline of actions, contingency plans, and communication strategy for future reference. \n",+ "Input: None.\n",+ "\n",+ "[AI Assistant] Solution: Below is a compiled final report summarizing the design of the time machine, the pivotal historical event selected for alteration, the timeline of actions, contingency plans, and the communication strategy established for future reference.\n",+ "\n",+ "---\n",+ "\n",+ "### Final Report: Time Machine Project\n",+ "\n",+ "**1. Time Machine Design Using Quantum Entanglement and Wormhole Theory**\n",+ "\n",+ "- **Core Principles**:\n",+ " - **Quantum Entanglement**: Exploits the phenomenon where particles become interconnected, allowing for instantaneous information transfer.\n",+ " - **Wormhole Theory**: Utilizes theoretical constructs in general relativity to create traversable tunnels in spacetime.\n",+ "\n",+ "- **Design Components**:\n",+ " - **Stable Wormhole Creation**: Hypothetically utilize exotic matter with negative energy density to keep the wormhole open.\n",+ " - **Particle Entanglement Setup**: Use techniques such as photon polarization or superconducting qubits to create pairs of entangled particles.\n",+ " - **Communication System**: Implement quantum entanglement for real-time communication across time.\n",+ "\n",+ "**2. Pivotal Historical Event for Alteration**\n",+ "\n",+ "- **Event Selected**: Assassination of Archduke Franz Ferdinand on June 28, 1914.\n",+ " \n",+ "- **Rationale**: Preventing this assassination could lead to the avoidance of World War I, potentially altering the course of 20th-century history and preventing subsequent conflicts.\n",+ "\n",+ "**3. Timeline of Actions for Alteration**\n",+ "\n",+ "- **Preparation Phase (6 months prior)**:\n",+ " - Research political climate and establish communication with future self.\n",+ " - Identify key political players for influence.\n",+ "\n",+ "- **Influencing Local Sentiment (3 months prior)**:\n",+ " - Distribute peace advocacy materials and infiltrate radical groups.\n",+ "\n",+ "- **On-the-Ground Actions (1 month prior)**:\n",+ " - Secure a meeting with Archduke Ferdinand and encourage increased security.\n",+ "\n",+ "- **Day of the Assassination (June 28, 1914)**:\n",+ " - Ensure the motorcade route is secure and create controlled distractions.\n",+ "\n",+ "- **Immediate Aftermath (June 29, 1914)**:\n",+ " - Promote a peaceful reaction and facilitate diplomatic talks.\n",+ "\n",+ "- **Monitoring the Timeline (Ongoing)**:\n",+ " - Establish a monitoring mechanism and prepare contingency plans.\n",+ "\n",+ "**4. Contingency Plans for Unforeseen Consequences**\n",+ "\n",+ "- **Political Instability**:\n",+ " - Monitor political landscape and engage diplomatic channels.\n",+ " - Support moderate movements to counter radicalism.\n",+ "\n",+ "- **Rise of Nationalism**:\n",+ " - Promote regional cooperation and cultural exchange programs.\n",+ "\n",+ "- **Economic Consequences**:\n",+ " - Monitor economic indicators and prepare intervention strategies.\n",+ "\n",+ "- **Unforeseen Wars or Conflicts**:\n",+ " - Engage in preemptive diplomacy and create a rapid response team.\n",+ "\n",+ "- **Technological and Social Changes**:\n",+ " - Assess advancements and implement social programs to address disparities.\n",+ "\n",+ "- **Communication with Future Self**:\n",+ " - Develop a reversion plan for catastrophic consequences.\n",+ "\n",+ "**5. Communication Strategy with Future Self**\n",+ "\n",+ "- **Quantum Communication Setup**:\n",+ " - Utilize entangled particle pairs for two-way communication.\n",+ " - Establish a standardized messaging format and priority levels.\n",+ "\n",+ "- **Real-Time Assessment Framework**:\n",+ " - Create monitoring criteria and schedule regular check-ins.\n",+ "\n",+ "- **Adaptation Process**:\n",+ " - Implement a feedback loop and develop contingency action plans.\n",+ "\n",+ "- **Documentation and Analysis**:\n",+ " - Maintain thorough records and conduct post-assessment reviews.\n",+ "\n",+ "- **Emergency Communication Protocol**:\n",+ " - Establish rapid response communication and backup channels.\n",+ "\n",+ "- **Ethical and Philosophical Considerations**:\n",+ " - Develop an ethical framework for decision-making and engage in philosophical reflection.\n",+ "\n",+ "---\n",+ "\n",+ "This report serves as a comprehensive summary of the time machine project, outlining the design, targeted historical alteration, action plans, contingency measures, and communication strategies for future reference. Each element is crucial for ensuring a successful alteration of the timeline while minimizing disruptions.\n",+ "\n",+ "Next request..\n",+ "\n"+ ]+ },+ {+ "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"+ ]+ },+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "\u001b[35m\u001b[3m> Proposals from an ambitious aspiring TIME TRAVELER (RoleType.USER). Please choose an option:\n",+ "Option 1:\n",+ "<CAMEL_TASK_DONE>\n",+ "\n",+ "Option 2:\n",+ "<CAMEL_TASK_DONE>\n",+ "\n",+ "Option 3:\n",+ "<CAMEL_TASK_DONE>\n",+ "\n",+ "Please first enter your choice ([1-3]) and then your explanation and comparison: \u001b[0m\n",+ "\n",+ "\n",+ "\u001b[35m\n",+ "> Critic response: \u001b[3mIt seems that the options provided are placeholders and do not contain specific content to evaluate. Therefore, I cannot choose an option or provide an explanation and comparison without further details. If you could provide the actual content or context for each option, I would be happy to assist you in making a choice and providing an analysis.\u001b[0m\n",+ "\n",+ "\n",+ "\u001b[35m\n",+ "> Critic response: \u001b[3mIt appears that the options provided are still placeholders and do not contain any specific information or tasks to evaluate. Without additional context or details about what each option entails, I am unable to make a choice or provide an explanation and comparison.\n",+ "\n",+ "If you can provide more information about what each option represents or what tasks they involve, I would be glad to help you analyze and choose the best option.\u001b[0m\n",+ "\n",+ "\n"+ ]+ },+ {+ "output_type": "stream",+ "name": "stderr",+ "text": [+ "/usr/local/lib/python3.10/dist-packages/camel/agents/critic_agent.py:144: UserWarning: Critic failed to get a valid option. After 2 attempts. Returning a random option.\n",+ " warnings.warn(\n",+ "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"+ ]+ },+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "\u001b[35m\u001b[3m> Proposals from the best-ever experimental physicist (RoleType.ASSISTANT). Please choose an option:\n",+ "Option 1:\n",+ "Solution: The task has been successfully completed, summarizing all aspects of the time machine design, the pivotal historical event alteration, timeline of actions, contingency plans, and communication strategy. If you require further assistance or wish to explore additional topics related to time travel or any other concept, feel free to ask!\n",+ "\n",+ "Next request.\n",+ "\n",+ "Option 2:\n",+ "Solution: The task is now considered completed. We have successfully designed a time machine using quantum entanglement and wormhole theory, identified a pivotal historical event to alter, created a detailed timeline of actions, prepared contingencies for unforeseen consequences, and established a communication strategy with future self. \n",+ "\n",+ "If you need any further assistance or wish to explore new topics or tasks, feel free to ask! \n",+ "\n",+ "Next request.\n",+ "\n",+ "Option 3:\n",+ "Solution: The task is marked as completed. Thank you for collaborating on this intriguing project of time travel design and historical alteration. If you have any further inquiries or future projects you'd like to discuss, feel free to reach out. \n",+ "\n",+ "Next request.\n",+ "\n",+ "Please first enter your choice ([1-3]) and then your explanation and comparison: \u001b[0m\n",+ "\n",+ "\n",+ "\u001b[35m\n",+ "> Critic response: \u001b[3mI choose Option 2.\n",+ "\n",+ "**Explanation and Comparison:**\n",+ "\n",+ "Option 2 is the most comprehensive and informative choice among the three options for several reasons:\n",+ "\n",+ "1. **Detail and Clarity**: Option 2 provides a clear summary of the key components of the time travel project, including the design of the time machine, the pivotal historical event chosen for alteration, the detailed timeline of actions, contingency plans, and the communication strategy with the future self. This level of detail is essential for understanding the complexities involved in such an ambitious project.\n",+ "\n",+ "2. **Focus on Key Elements**: Unlike Option 1, which is also detailed, Option 2 emphasizes the scientific principles behind the time machine design (quantum entanglement and wormhole theory). This focus on the theoretical foundation adds depth to the explanation and showcases the scientific rigor behind the project.\n",+ "\n",+ "3. **Encouragement for Further Exploration**: Option 2 invites further inquiries or exploration of new topics, which is beneficial for fostering ongoing collaboration and discussion. This openness can lead to more innovative ideas and solutions in the realm of time travel.\n",+ "\n",+ "4. **Professional Tone**: The language used in Option 2 strikes a balance between being professional and approachable. It conveys confidence in the completion of the task while also being inviting for future discussions.\n",+ "\n",+ "In comparison, Option 1, while also thorough, lacks the emphasis on the scientific principles that underpin the time machine design. It is more general in its summary and does not highlight the theoretical aspects as effectively as Option 2.\n",+ "\n",+ "Option 3, while polite and appreciative, is the least detailed of the three. It does not provide specific information about the project components and is more focused on closing the conversation rather than summarizing the work done.\n",+ "\n",+ "In summary, Option 2 stands out as the best choice due to its detailed and clear presentation of the project, its emphasis on scientific principles, and its encouragement for further exploration and discussion.\u001b[0m\n",+ "\n",+ "\n",+ "[AI User] <CAMEL_TASK_DONE>.\n",+ "\n",+ "[AI Assistant] Solution: The task is now considered completed. We have successfully designed a time machine using quantum entanglement and wormhole theory, identified a pivotal historical event to alter, created a detailed timeline of actions, prepared contingencies for unforeseen consequences, and established a communication strategy with future self. \n",+ "\n",+ "If you need any further assistance or wish to explore new topics or tasks, feel free to ask! \n",+ "\n",+ "Next request..\n",+ "\n"+ ]+ }+ ]+ },+ {+ "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"+ }}- ]- },- {- "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.ipynbindex b092b670d..ba22851d3 100644--- a/docs/cookbooks/embodied_agents.ipynb+++ b/docs/cookbooks/embodied_agents.ipynb@@ -67,7 +67,7 @@{"cell_type": "code","source": [- "%pip install \"camel-ai==0.2.1\""+ "%pip install \"camel-ai==0.2.4\""],"metadata": {"id": "UtcC3c-KVZmU"@@ -86,7 +86,7 @@"metadata": {"id": "CmgKGeCxVON-"},- "execution_count": 3,+ "execution_count": 2,"outputs": []},{@@ -122,9 +122,9 @@"base_uri": "https://localhost:8080/"},"id": "PNBFEXc-R-0s",- "outputId": "e79eb379-4a5d-45b5-b591-2a1cd8612bbb"+ "outputId": "6e97c175-684c-47d7-866c-c23aea59910a"},- "execution_count": 4,+ "execution_count": 3,"outputs": [{"name": "stdout",@@ -159,7 +159,7 @@"metadata": {"id": "i-pIc9eTc0SH"},- "execution_count": 5,+ "execution_count": 4,"outputs": []},{@@ -175,13 +175,12 @@"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)"+ "sys_msg = sys_msg_gen().from_dict(meta_dict=meta_dict, role_tuple=role_tuple)"],"metadata": {"id": "yA62jAfDc5CK"},- "execution_count": 6,+ "execution_count": 5,"outputs": []},{@@ -205,7 +204,7 @@"metadata": {"id": "VetPjL70c9be"},- "execution_count": 7,+ "execution_count": 6,"outputs": []},{@@ -242,7 +241,7 @@"metadata": {"id": "Ts52u_UVdDJA"},- "execution_count": 8,+ "execution_count": 7,"outputs": []},{@@ -264,157 +263,130 @@"base_uri": "https://localhost:8080/"},"id": "6hKpSzssdGvc",- "outputId": "38de4086-5271-4abb-e2e3-f5112aafe492"+ "outputId": "c7a8a799-de9f-4453-926f-c39ecef258a9"},- "execution_count": 9,+ "execution_count": 8,"outputs": [{- "name": "stdout","output_type": "stream",+ "name": "stdout","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",+ "1. **Write a Bash script** to install NumPy using `pip`. This will ensure that the necessary library is available for the Python script that follows.\n",+ "2. **Write a Python script** to compute the dot product of the two lists `[8, 9]` and `[5, 4]`. The dot product is calculated as the sum of the products of the corresponding entries of the two sequences.\n",+ "3. **Write a script** to fetch the weather information for London using the `wttr.in` service. This will provide a simple way to get weather data from the command line.\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",+ "I'll create a Bash script named `install_numpy.sh` that will check if `pip` is installed and then use it to install NumPy.\n","\n",- "\u001b[35m> Code:\n",- "#!/bin/bash\n",- "# install_numpy.sh\n",- "echo \"Installing NumPy...\"\n",- "pip install numpy\n",+ "### Step 2: Python Script for Dot Product Calculation\n","\n",- "\u001b[35m> Explanation:\n",- "### Step 2: Python Script for Dot Product\n",+ "I'll create a Python script named `dot_product.py` that will compute the dot product of the two lists and print the result.\n","\n",- "The Python script will use NumPy to compute the dot product of the two vectors. Hereโs the code for that:\n",+ "### Step 3: Script to Fetch Weather Information\n","\n",- "\u001b[35m> Code:\n",- "# dot_product.py\n",- "import numpy as np\n",+ "I'll create a Bash script named `get_weather.sh` that will use `curl` to fetch the weather information for London from `wttr.in`.\n","\n",- "# Define the vectors\n",- "vector_a = np.array([8, 9])\n",- "vector_b = np.array([5, 4])\n",+ "Now, let's implement these actions in code.\n","\n",- "# Compute the dot product\n",- "dot_product = np.dot(vector_a, vector_b)\n",+ "\u001b[35m> Code:\n",+ "# Step 1: Bash script to install NumPy\n",+ "echo '#!/bin/bash' > install_numpy.sh\n",+ "echo 'if command -v pip &> /dev/null; then' >> install_numpy.sh\n",+ "echo ' echo \"Installing NumPy...\"' >> install_numpy.sh\n",+ "echo ' pip install numpy' >> install_numpy.sh\n",+ "echo 'else' >> install_numpy.sh\n",+ "echo ' echo \"pip is not installed. Please install pip first.\"' >> install_numpy.sh\n",+ "echo 'fi' >> install_numpy.sh\n",+ "chmod +x install_numpy.sh\n",+ "\n",+ "# Step 2: Python script for dot product calculation\n",+ "echo 'import numpy as np' > dot_product.py\n",+ "echo 'a = np.array([8, 9])' >> dot_product.py\n",+ "echo 'b = np.array([5, 4])' >> dot_product.py\n",+ "echo 'dot_product = np.dot(a, b)' >> dot_product.py\n",+ "echo 'print(\"Dot product:\", dot_product)' >> dot_product.py\n","\n",- "# Print the result\n",- "print(\"The dot product of\", vector_a.tolist(), \"and\", vector_b.tolist(), \"is:\", dot_product)\n",+ "# Step 3: Bash script to fetch weather information\n",+ "echo '#!/bin/bash' > get_weather.sh\n",+ "echo 'curl wttr.in/london' >> get_weather.sh\n",+ "chmod +x get_weather.sh\n","\n","\u001b[35m> Explanation:\n",- "### Step 3: Bash Script to Fetch Weather Information\n",+ "### Explanation of the Code\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",+ "1. **install_numpy.sh**: This script checks if `pip` is installed and installs NumPy if it is. It provides feedback if `pip` is not found.\n",+ "2. **dot_product.py**: This Python script uses NumPy to calculate the dot product of two arrays and prints the result.\n",+ "3. **get_weather.sh**: This script uses `curl` to fetch and display the weather information for London from `wttr.in`.\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",+ "### Next Steps\n","\n",- "\u001b[35m> Explanation:\n",- "### Summary of Actions\n",+ "I will execute these scripts in the appropriate order to ensure that NumPy is installed before running the Python script. After that, I will fetch the weather information for London. \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",+ "Let's execute the installation script first.\n","\n",- "Now, I will write the code for each of these scripts. \n",+ "\u001b[35m> Code:\n",+ "./install_numpy.sh\n","\n",- "### Code Implementation\n",+ "\u001b[35m> Explanation:\n",+ "After confirming that NumPy is installed, I will run the Python script:\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",+ "python3 dot_product.py\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",+ "\u001b[35m> Explanation:\n",+ "Finally, I will run the weather script:\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",+ "\u001b[35m> Code:\n",+ "./get_weather.sh\n","\n","\u001b[35m> Explanation:\n",- "### Execution\n",+ "Now, I will perform these actions.\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",+ "The following bash code will run on your computer:\n",+ "\u001b[36m# Step 1: Bash script to install NumPy\n",+ "echo '#!/bin/bash' > install_numpy.sh\n",+ "echo 'if command -v pip &> /dev/null; then' >> install_numpy.sh\n",+ "echo ' echo \"Installing NumPy...\"' >> install_numpy.sh\n",+ "echo ' pip install numpy' >> install_numpy.sh\n",+ "echo 'else' >> install_numpy.sh\n",+ "echo ' echo \"pip is not installed. Please install pip first.\"' >> install_numpy.sh\n",+ "echo 'fi' >> install_numpy.sh\n",+ "chmod +x install_numpy.sh\n","\n",- "Let me know if you would like me to execute any of these scripts or if you need further assistance!\n",+ "# Step 2: Python script for dot product calculation\n",+ "echo 'import numpy as np' > dot_product.py\n",+ "echo 'a = np.array([8, 9])' >> dot_product.py\n",+ "echo 'b = np.array([5, 4])' >> dot_product.py\n",+ "echo 'dot_product = np.dot(a, b)' >> dot_product.py\n",+ "echo 'print(\"Dot product:\", dot_product)' >> dot_product.py\n","\n",+ "# Step 3: Bash script to fetch weather information\n",+ "echo '#!/bin/bash' > 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","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",+ "\u001b[36m./install_numpy.sh\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",+ "The following bash code will run on your computer:\n",+ "\u001b[36mpython3 dot_product.py\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",+ "\u001b[36m./get_weather.sh\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",+ "100 8906 100 8906 0 0 9068 0 --:--:-- --:--:-- --:--:-- 9069\n",+ "100 8906 100 8906 0 0 9068 0 --:--:-- --:--:-- --:--:-- 9069\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"+ "==================\n"]}]@@ -442,7 +414,7 @@"id": "qA0bpOFldKPV","outputId": "421418d2-61ca-4c65-f08e-83038c50a85a"},- "execution_count": 10,+ "execution_count": null,"outputs": [{"output_type": "stream",diff --git a/docs/cookbooks/knowledge_graph.ipynb b/docs/cookbooks/knowledge_graph.ipynbindex b1bf9c20f..70e485cd3 100644--- a/docs/cookbooks/knowledge_graph.ipynb+++ b/docs/cookbooks/knowledge_graph.ipynb@@ -1,883 +1,848 @@{- "cells": [- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "DJeeABnkOsPK"- },- "source": [- "# Using CAMEL to Do Graph RAG with Mistral Models"- ]- },- {- "cell_type": "markdown",- "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",- "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",- "metadata": {- "id": "slaeSyWkbIzc"- },- "source": [- ""- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "X5mWln9dCDzE"- },- "source": [- ""- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "8SV7XmyKbwdc"- },- "source": [- "## ๐ฆ Installation"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "-qAA1j0Sb2Ve"- },- "source": [- "First, install the CAMEL package with all its dependencies:"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "collapsed": true,- "id": "os7Mcfw2Svww"- },- "outputs": [],- "source": [- "%pip install \"camel-ai[all]==0.2.1\""- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "X5SDX1kPb6bz"- },- "source": [- "## ๐ง Setup"- ]- },- {- "cell_type": "markdown",- "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",- "from camel.configs import MistralConfig, OllamaConfig\n",- "from camel.loaders import UnstructuredIO\n",- "from camel.storages import Neo4jGraph\n",- "from camel.retrievers import AutoRetriever\n",- "from camel.embeddings import MistralEmbedding\n",- "from camel.types import StorageType\n",- "from camel.agents import ChatAgent, KnowledgeGraphAgent\n",- "from camel.messages import BaseMessage"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "DahHkqSOb-T3"- },- "source": [- "## ๐ Setting Up API Keys\n"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "odHOpz0XcAjA"- },- "source": [- "For secure access to Mistral AI's services, we'll prompt for the API key."- ]- },- {- "cell_type": "code",- "execution_count": 3,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "B0v7xEFFoabv",- "outputId": "f343482c-435d-496d-dfa2-fc65014e39c8"- },- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "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",- "metadata": {- "id": "bPPZx6WwcDzG"- },- "source": [- "## ๐๏ธ Configuring Neo4j Graph Database"- ]- },- {- "cell_type": "markdown",- "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",- " url=\"Your_URL\",\n",- " username=\"Your_Username\",\n",- " password=\"Your_Password\",\n",- ")"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "vmzruZl1cJQD"- },- "source": [- "## ๐ง Creating the Model"- ]- },- {- "cell_type": "markdown",- "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",- " model_platform=ModelPlatformType.MISTRAL,\n",- " model_type=ModelType.MISTRAL_LARGE,\n",- " model_config_dict=MistralConfig(temperature=0.2).as_dict(),\n",- ")"- ]- },- {- "cell_type": "code",- "execution_count": 6,- "metadata": {+ "nbformat": 4,+ "nbformat_minor": 0,+ "metadata": {"colab": {- "base_uri": "https://localhost:8080/"- },- "id": "PPyHfsGyraJf",- "outputId": "134fd954-a1c4-4642-c3f7-911c5ae8e8a5"- },- "outputs": [- {- "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",- "metadata": {- "id": "61PwBl9XcWJ_"- },- "source": [- "## ๐ค Generate a Knowledge Graph Using CAMEL's Agent"- ]- },- {- "cell_type": "markdown",- "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)"- ]- },- {- "cell_type": "markdown",- "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",- "CAMEL has developed a knowledge graph agent can run with Mistral AI's most\n",- "advanced model, the Mistral Large 2. This knowledge graph agent is capable\n",- "of extracting entities and relationships from given content and create knowledge\n",- "graphs automaticlly.\n",- "\"\"\""- ]- },- {- "cell_type": "markdown",- "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",- ")"- ]- },- {- "cell_type": "code",- "execution_count": 10,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "WlmeLofo4kDE",- "outputId": "8df4fcaa-3195-421a-afc0-298062ff7843"- },- "outputs": [- {- "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",- "Content:\n",- "\"CAMEL has developed a knowledge graph agent that can run with Mistral AI's most advanced model, the Mistral Large 2. This knowledge graph agent is capable of extracting entities and relationships from given content and create knowledge graphs automatically.\"\n",- "\n",- "### Extracted Nodes and Relationships\n",- "\n",- "#### Nodes:\n",- "\n",- "1. **CAMEL**\n",- " - Type: Organization\n",- "2. **Knowledge Graph Agent**\n",- " - Type: Software\n",- "3. **Mistral AI**\n",- " - Type: Organization\n",- "4. **Mistral Large 2**\n",- " - Type: Model\n",- "5. **Entities**\n",- " - Type: Concept\n",- "6. **Relationships**\n",- " - Type: Concept\n",- "7. **Content**\n",- " - Type: Concept\n",- "8. **Knowledge Graphs**\n",- " - Type: Concept\n",- "\n",- "#### Relationships:\n",- "\n",- "1. **CAMEL** developed **Knowledge Graph Agent**\n",- " - Type: Developed\n",- "2. **Knowledge Graph Agent** can run with **Mistral Large 2**\n",- " - Type: CanRunWith\n",- "3. **Mistral Large 2** is developed by **Mistral AI**\n",- " - Type: DevelopedBy\n",- "4. **Knowledge Graph Agent** is capable of extracting **Entities**\n",- " - Type: CanExtract\n",- "5. **Knowledge Graph Agent** is capable of extracting **Relationships**\n",- " - Type: CanExtract\n",- "6. **Knowledge Graph Agent** creates **Knowledge Graphs**\n",- " - Type: Creates\n",- "7. **Entities** and **Relationships** are extracted from **Content**\n",- " - Type: ExtractedFrom\n",- "\n",- "### Structured Output\n",- "\n",- "#### Nodes:\n",- "\n",- "```python\n",- "Node(id='CAMEL', type='Organization')\n",- "Node(id='Knowledge Graph Agent', type='Software')\n",- "Node(id='Mistral AI', type='Organization')\n",- "Node(id='Mistral Large 2', type='Model')\n",- "Node(id='Entities', type='Concept')\n",- "Node(id='Relationships', type='Concept')\n",- "Node(id='Content', type='Concept')\n",- "Node(id='Knowledge Graphs', type='Concept')\n",- "```\n",- "\n",- "#### Relationships:\n",- "\n",- "```python\n",- "Relationship(subj=Node(id='CAMEL', type='Organization'), obj=Node(id='Knowledge Graph Agent', type='Software'), type='Developed')\n",- "Relationship(subj=Node(id='Knowledge Graph Agent', type='Software'), obj=Node(id='Mistral Large 2', type='Model'), type='CanRunWith')\n",- "Relationship(subj=Node(id='Mistral Large 2', type='Model'), obj=Node(id='Mistral AI', type='Organization'), type='DevelopedBy')\n",- "Relationship(subj=Node(id='Knowledge Graph Agent', type='Software'), obj=Node(id='Entities', type='Concept'), type='CanExtract')\n",- "Relationship(subj=Node(id='Knowledge Graph Agent', type='Software'), obj=Node(id='Relationships', type='Concept'), type='CanExtract')\n",- "Relationship(subj=Node(id='Knowledge Graph Agent', type='Software'), obj=Node(id='Knowledge Graphs', type='Concept'), type='Creates')\n",- "Relationship(subj=Node(id='Entities', type='Concept'), obj=Node(id='Content', type='Concept'), type='ExtractedFrom')\n",- "Relationship(subj=Node(id='Relationships', type='Concept'), obj=Node(id='Content', type='Concept'), type='ExtractedFrom')\n",- "```\n",- "\n",- "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",- "execution_count": 11,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "J0JzGaFN4pRh",- "outputId": "6f2064f2-dce1-4b26-a4dc-50ac9481c685"- },- "outputs": [- {- "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",- "metadata": {- "id": "sqEfkLI-c23g"- },- "source": [- "Add the extracted graph elements to the Neo4j database:"- ]- },- {- "cell_type": "code",- "execution_count": 12,- "metadata": {- "id": "89ZF99QSAaGJ"- },- "outputs": [],- "source": [- "# Add the element to neo4j database\n",- "n4j.add_graph_elements(graph_elements=[graph_elements])"- ]- },- {- "cell_type": "markdown",- "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",- "metadata": {- "id": "LckRFGpN6Za4"- },- "source": [- "## ๐๏ธ Running Graph RAG with CAMEL"- ]- },- {- "cell_type": "markdown",- "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",- "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",- " vector_storage_local_path=\"local_data/embedding_storage\",\n",- " storage_type=StorageType.QDRANT,\n",- " embedding_model=MistralEmbedding(),\n",- ")"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "BpAPOf7VeFjx"- },- "source": [- "Provide an example user query:"- ]- },- {- "cell_type": "code",- "execution_count": 14,- "metadata": {- "id": "PTZ-8nX359bb"- },- "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",- "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",- "execution_count": 16,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "hLQGgp4DJAlu",- "outputId": "0bfe8fe6-c5dd-42a1-ff44-450c3cb62a5a"- },- "outputs": [- {- "name": "stderr",- "output_type": "stream",- "text": [- "[nltk_data] Downloading package punkt to /root/nltk_data...\n",- "[nltk_data] Unzipping tokenizers/punkt.zip.\n",- "[nltk_data] Downloading package averaged_perceptron_tagger to\n",- "[nltk_data] /root/nltk_data...\n",- "[nltk_data] Unzipping taggers/averaged_perceptron_tagger.zip.\n"- ]- },- {- "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",- "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",- "\n",- "elements = uio.parse_file_or_url(\n",- " input_path=\"https://mistral.ai/news/mistral-large-2407/\"\n",- ")\n",- "chunk_elements = uio.chunk_elements(\n",- " chunk_type=\"chunk_by_title\", elements=elements\n",- ")\n",- "\n",- "graph_elements = []\n",- "for chunk in chunk_elements:\n",- " 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)"- ]- },- {- "cell_type": "markdown",- "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",- " text=query, element_id=\"1\"\n",- ")\n",- "\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)"- ]- },- {- "cell_type": "markdown",- "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"- ]+ "provenance": []+ },+ "kernelspec": {+ "name": "python3",+ "display_name": "Python 3"+ },+ "language_info": {+ "name": "python"}- ],- "source": [- "# Match the enetity got from query in the knowledge graph storage content\n",- "kg_result = []\n",- "for node in ans_element.nodes:\n",- " n4j_query = f\"\"\"\n",- "MATCH (n {{id: '{node.id}'}})-[r]->(m)\n",- "RETURN 'Node ' + n.id + ' (label: ' + labels(n)[0] + ') has relationship ' + type(r) + ' with Node ' + m.id + ' (label: ' + labels(m)[0] + ')' AS Description\n",- "UNION\n",- "MATCH (n)<-[r]-(m {{id: '{node.id}'}})\n",- "RETURN 'Node ' + m.id + ' (label: ' + labels(m)[0] + ') has relationship ' + type(r) + ' with Node ' + n.id + ' (label: ' + labels(n)[0] + ')' AS Description\n",- "\"\"\"\n",- " result = n4j.query(query=n4j_query)\n",- " kg_result.extend(result)\n",- "\n",- "kg_result = [item['Description'] for item in kg_result]\n",- "\n",- "# Show the result from knowledge graph database\n",- "print(kg_result)"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "sjKr29w8eZ4n"- },- "source": [- "Combine results from the vector search and knowledge graph entity search:"- ]- },- {- "cell_type": "code",- "execution_count": 23,- "metadata": {- "id": "P9ne7UoB6GY5"- },- "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",- "metadata": {- "id": "q-NaDHypebKZ"- },- "source": [- "Set up an assistant agent to answer questions based on the retrieved context:"- ]},- {- "cell_type": "code",- "execution_count": 24,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "LxEUi36F7kq1",- "outputId": "9e3aeb7f-a1bd-437d-c9ab-81df4f25a960"- },- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "### Relationship Between Mistral Large 2 and Mistral AI\n",- "\n",- "Mistral Large 2 is a model developed by Mistral AI. The relationship between Mistral Large 2 and Mistral AI is that Mistral AI has created and provides the Mistral Large 2 model.\n",- "\n",- "### Features of Mistral Large 2\n",- "\n",- "Mistral Large 2 has several notable features and capabilities:\n",- "\n",- "1. **Size and Performance**:\n",- " - **123 Billion Parameters**: This size allows it to run at large throughput on a single node.\n",- " - **128k Context Window**: This feature enables the model to handle long-context applications effectively.\n",- "\n",- "2. **Language Support**:\n",- " - Mistral Large 2 supports multiple languages, including French, German, Spanish, Italian, Portuguese, Arabic, Hindi, Russian, Chinese, Japanese, and Korean.\n",- "\n",- "3. **Coding Language Support**:\n",- " - The model supports various coding languages such as Python, Java, C, C++, JavaScript, and Bash.\n",- "\n",- "4. **Design and Usage**:\n",- " - **Single-Node Inference**: Designed for single-node inference, making it efficient for specific use cases.\n",- " - **Long-Context Applications**: Optimized for applications requiring long contexts.\n",- "\n",- "5. **Licensing**:\n",- " - **Mistral Research License**: Allows usage and modification for research and non-commercial purposes.\n",- " - **Mistral Commercial License**: Required for commercial usage involving self-deployment.\n",- "\n",- "6. **Capabilities**:\n",- " - **Instruction-Following**: Improved capabilities in following precise instructions.\n",- " - **Conversational Capabilities**: Better at handling long multi-turn conversations.\n",- "\n",- "7. **Benchmarks and Performance**:\n",- " - Performance reported on various benchmarks such as MT-Bench, Wild Bench, Arena Hard benchmarks, and general alignment benchmarks.\n",- " - Sets new frontiers in performance, cost of serving, and evaluation metrics.\n",- "\n",- "8. **Additional Features**:\n",- " - **Enhanced Function Calling**: Equipped with enhanced function calling capabilities.\n",- " - **Retrieval Skills**: Possesses retrieval skills.\n",- " - **Parallel and Sequential Function Calls**: Can execute both parallel and sequential function calls.\n",- "\n",- "9. **Training and Evaluation**:\n",- " - Trained on multilingual data.\n",- " - Benchmarked through an evaluation pipeline.\n",- "\n",- "10. **Platforms and Services**:\n",- " - Exposed on platforms like \"la Plateforme.\"\n",- " - Provided on services such as Vertex AI, Azure AI Studio, Amazon Bedrock, and IBM watsonx.ai.\n",- "\n",- "These features make Mistral Large 2 a powerful and versatile model suitable for a wide range of applications.\n"- ]+ "cells": [+ {+ "cell_type": "markdown",+ "source": [+ "# ๐ซ Using CAMEL to Do Graph RAG with Mistral Models"+ ],+ "metadata": {+ "id": "DJeeABnkOsPK"+ }+ },+ {+ "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"+ }+ },+ {+ "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"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ ""+ ],+ "metadata": {+ "id": "slaeSyWkbIzc"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ ""+ ],+ "metadata": {+ "id": "X5mWln9dCDzE"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "## ๐ฆ Installation"+ ],+ "metadata": {+ "id": "8SV7XmyKbwdc"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "First, install the CAMEL package with all its dependencies:"+ ],+ "metadata": {+ "id": "-qAA1j0Sb2Ve"+ }+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {+ "collapsed": true,+ "id": "os7Mcfw2Svww"+ },+ "outputs": [],+ "source": [+ "pip install \"camel-ai[all]==0.2.4\""+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "## ๐ง Setup"+ ],+ "metadata": {+ "id": "X5SDX1kPb6bz"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "Import the required modules from CAMEL-AI:"+ ],+ "metadata": {+ "id": "StvpXTi7b7pF"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "from camel.models import ModelFactory\n",+ "from camel.types import ModelPlatformType, ModelType\n",+ "from camel.configs import MistralConfig, OllamaConfig\n",+ "from camel.loaders import UnstructuredIO\n",+ "from camel.storages import Neo4jGraph\n",+ "from camel.retrievers import AutoRetriever\n",+ "from camel.embeddings import MistralEmbedding\n",+ "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"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "For secure access to Mistral AI's services, we'll prompt for the API key."+ ],+ "metadata": {+ "id": "odHOpz0XcAjA"+ }+ },+ {+ "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"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "B0v7xEFFoabv",+ "outputId": "7cf90833-d7ab-49a0-fda9-46c99af7ccc6"+ },+ "execution_count": 3,+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Enter your API key: ยทยทยทยทยทยทยทยทยทยท\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "## ๐๏ธ Configuring Neo4j Graph Database"+ ],+ "metadata": {+ "id": "bPPZx6WwcDzG"+ }+ },+ {+ "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"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "# Set Neo4j instance\n",+ "n4j = Neo4jGraph(\n",+ " url=\"Your_URL\",\n",+ " 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"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "Set up Mistral Large 2 model using the CAMEL ModelFactory:"+ ],+ "metadata": {+ "id": "flTRxefgcOxp"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "# Set up model\n",+ "mistral_large_2 = ModelFactory.create(\n",+ " model_platform=ModelPlatformType.MISTRAL,\n",+ " 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",+ ")"+ ],+ "metadata": {+ "id": "PPyHfsGyraJf"+ },+ "execution_count": null,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "## ๐ค Generate a Knowledge Graph Using CAMEL's Agent"+ ],+ "metadata": {+ "id": "61PwBl9XcWJ_"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "Set up instances for knowledge graph agent:"+ ],+ "metadata": {+ "id": "nFl_Paah4OdP"+ }+ },+ {+ "cell_type": "code",+ "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"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "# Set example text input\n",+ "text_example = \"\"\"\n",+ "CAMEL has developed a knowledge graph agent can run with Mistral AI's most\n",+ "advanced model, the Mistral Large 2. This knowledge graph agent is capable\n",+ "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"+ }+ },+ {+ "cell_type": "code",+ "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)"+ ],+ "metadata": {+ "id": "WlmeLofo4kDE",+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "outputId": "1543028f-58cd-417c-b9f1-ee28b5ebdcd7"+ },+ "execution_count": 10,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "Sure, let's go through the process of extracting nodes and relationships from the given content and structuring them into Node and Relationship objects.\n",+ "\n",+ "### Content:\n",+ "\"CAMEL has developed a knowledge graph agent that can run with Mistral AI's most advanced model, the Mistral Large 2. This knowledge graph agent is capable of extracting entities and relationships from given content and create knowledge graphs automatically.\"\n",+ "\n",+ "### Step-by-Step Extraction:\n",+ "\n",+ "1. **Identify Entities (Nodes):**\n",+ " - CAMEL\n",+ " - knowledge graph agent\n",+ " - Mistral AI\n",+ " - Mistral Large 2\n",+ " - entities\n",+ " - relationships\n",+ " - content\n",+ " - knowledge graphs\n",+ "\n",+ "2. **Categorize Entities:**\n",+ " - CAMEL: Organization\n",+ " - knowledge graph agent: Software\n",+ " - Mistral AI: Organization\n",+ " - Mistral Large 2: Model\n",+ " - entities: Concept\n",+ " - relationships: Concept\n",+ " - content: Concept\n",+ " - knowledge graphs: Concept\n",+ "\n",+ "3. **Identify Relationships:**\n",+ " - CAMEL developed knowledge graph agent\n",+ " - knowledge graph agent can run with Mistral AI's Mistral Large 2\n",+ " - knowledge graph agent is capable of extracting entities and relationships from content\n",+ " - knowledge graph agent creates knowledge graphs\n",+ "\n",+ "### Structured Output:\n",+ "\n",+ "#### Nodes:\n",+ "```python\n",+ "Node(id='CAMEL', type='Organization')\n",+ "Node(id='knowledge graph agent', type='Software')\n",+ "Node(id='Mistral AI', type='Organization')\n",+ "Node(id='Mistral Large 2', type='Model')\n",+ "Node(id='entities', type='Concept')\n",+ "Node(id='relationships', type='Concept')\n",+ "Node(id='content', type='Concept')\n",+ "Node(id='knowledge graphs', type='Concept')\n",+ "```\n",+ "\n",+ "#### Relationships:\n",+ "```python\n",+ "Relationship(subj=Node(id='CAMEL', type='Organization'), obj=Node(id='knowledge graph agent', type='Software'), type='Developed')\n",+ "Relationship(subj=Node(id='knowledge graph agent', type='Software'), obj=Node(id='Mistral AI', type='Organization'), type='RunsWith')\n",+ "Relationship(subj=Node(id='knowledge graph agent', type='Software'), obj=Node(id='Mistral Large 2', type='Model'), type='RunsWith')\n",+ "Relationship(subj=Node(id='knowledge graph agent', type='Software'), obj=Node(id='entities', type='Concept'), type='Extracts')\n",+ "Relationship(subj=Node(id='knowledge graph agent', type='Software'), obj=Node(id='relationships', type='Concept'), type='Extracts')\n",+ "Relationship(subj=Node(id='knowledge graph agent', type='Software'), obj=Node(id='content', type='Concept'), type='ExtractsFrom')\n",+ "Relationship(subj=Node(id='knowledge graph agent', type='Software'), obj=Node(id='knowledge graphs', type='Concept'), type='Creates')\n",+ "```\n",+ "\n",+ "This structured output captures the entities and their relationships as described in the content. Each node has a unique identifier and a type, and each relationship specifies the subject, object, and type of the relationship.\n"+ ]+ }+ ]+ },+ {+ "cell_type": "code",+ "source": [+ "# Check graph element\n",+ "graph_elements = kg_agent.run(element_example, parse_graph_elements=True)\n",+ "print(graph_elements)"+ ],+ "metadata": {+ "id": "J0JzGaFN4pRh",+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "outputId": "6e957343-1388-4e1b-eefa-8cdaa117eff4"+ },+ "execution_count": 11,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "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 and relationships', 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 and 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='CanCreate', properties={'source': 'agent_created'})] source=<unstructured.documents.elements.Text object at 0x785a8686f6a0>\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "Add the extracted graph elements to the Neo4j database:"+ ],+ "metadata": {+ "id": "sqEfkLI-c23g"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "# Add the element to neo4j database\n",+ "n4j.add_graph_elements(graph_elements=[graph_elements])"+ ],+ "metadata": {+ "id": "89ZF99QSAaGJ"+ },+ "execution_count": 12,+ "outputs": []+ },+ {+ "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"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "## ๐๏ธ Running Graph RAG with CAMEL"+ ],+ "metadata": {+ "id": "LckRFGpN6Za4"+ }+ },+ {+ "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"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "Set up a vector retriever with local storage and embedding model from Mistral AI:"+ ],+ "metadata": {+ "id": "A_MiPGmOeDN3"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "# Set retriever\n",+ "camel_retriever = AutoRetriever(\n",+ " vector_storage_local_path=\"local_data/embedding_storage\",\n",+ " 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"+ }+ },+ {+ "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?\""+ ],+ "metadata": {+ "id": "PTZ-8nX359bb"+ },+ "execution_count": 14,+ "outputs": []+ },+ {+ "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"+ }+ },+ {+ "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)"+ ],+ "metadata": {+ "id": "hLQGgp4DJAlu",+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "outputId": "03b8fa1a-ddcd-45ae-f3e7-6c06121504e0"+ },+ "execution_count": 15,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "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': ['Large Enough\\n\\nToday, we are announcing Mistral Large 2, the new generation of our flagship model. Compared to its predecessor, Mistral Large 2 is significantly more capable in code generation, mathematics, and reasoning. It also provides a much stronger multilingual support, and advanced function calling capabilities.\\n\\nJuly 24, 2024\\n\\nMistral AI team']}\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "Parse content from the specified URL and create knowledge graph data:"+ ],+ "metadata": {+ "id": "w188PLzteMkw"+ }+ },+ {+ "cell_type": "code",+ "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",+ "\n",+ "elements = uio.parse_file_or_url(\n",+ " input_path=\"https://mistral.ai/news/mistral-large-2407/\"\n",+ ")\n",+ "chunk_elements = uio.chunk_elements(\n",+ " chunk_type=\"chunk_by_title\", elements=elements\n",+ ")\n",+ "\n",+ "graph_elements = []\n",+ "for chunk in chunk_elements:\n",+ " 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": 16,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "Create an element from the user query:"+ ],+ "metadata": {+ "id": "1UgtR5UWeSD0"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "# Create an element from user query\n",+ "query_element = uio.create_element_from_text(\n",+ " text=query, element_id=\"1\"\n",+ ")\n",+ "\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": 17,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "Match entities from the query in the knowledge graph storage content:"+ ],+ "metadata": {+ "id": "zD9hH7QAeVNT"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "# Match the enetity got from query in the knowledge graph storage content\n",+ "kg_result = []\n",+ "for node in ans_element.nodes:\n",+ " n4j_query = f\"\"\"\n",+ "MATCH (n {{id: '{node.id}'}})-[r]->(m)\n",+ "RETURN 'Node ' + n.id + ' (label: ' + labels(n)[0] + ') has relationship ' + type(r) + ' with Node ' + m.id + ' (label: ' + labels(m)[0] + ')' AS Description\n",+ "UNION\n",+ "MATCH (n)<-[r]-(m {{id: '{node.id}'}})\n",+ "RETURN 'Node ' + m.id + ' (label: ' + labels(m)[0] + ') has relationship ' + type(r) + ' with Node ' + n.id + ' (label: ' + labels(n)[0] + ')' AS Description\n",+ "\"\"\"\n",+ " result = n4j.query(query=n4j_query)\n",+ " kg_result.extend(result)\n",+ "\n",+ "kg_result = [item['Description'] for item in kg_result]\n",+ "\n",+ "# Show the result from knowledge graph database\n",+ "print(kg_result)"+ ],+ "metadata": {+ "id": "ttL5pnye66Wl",+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "outputId": "d7714d35-ca22-4cc9-ab4a-92b67fbc1ecf"+ },+ "execution_count": 18,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "['Node Mistral Large 2 (label: Model) has relationship SUCCESSOROF with Node Mistral Large (label: Model)', 'Node Mistral Large 2 (label: Model) has relationship ANNOUNCEDBY with Node Mistral AI team (label: Organization)', 'Node Mistral Large 2 (label: Model) has relationship HASCAPABILITY with Node code generation (label: Capability)', 'Node Mistral Large 2 (label: Model) has relationship HASCAPABILITY with Node mathematics (label: Capability)', 'Node Mistral Large 2 (label: Model) has relationship HASCAPABILITY with Node reasoning (label: Capability)', 'Node Mistral Large 2 (label: Model) has relationship HASCAPABILITY with Node Instruction-following capabilities (label: Capability)', 'Node Mistral Large 2 (label: Model) has relationship HASCAPABILITY with Node Conversational capabilities (label: Capability)', 'Node Mistral Large 2 (label: Model) has relationship PROVIDES with Node multilingual support (label: Capability)', 'Node Mistral Large 2 (label: Model) has relationship PROVIDES with Node advanced function calling capabilities (label: Capability)', 'Node Mistral Large 2 (label: Model) has relationship ANNOUNCEDON with Node July 24, 2024 (label: Date)', '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 HAS 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 SETSFRONTIERIN with Node Performance (label: Metric)', 'Node Mistral Large 2 (label: Model) has relationship SETSFRONTIERIN with Node Cost of serving (label: Metric)', 'Node Mistral Large 2 (label: Model) has relationship SETSFRONTIERON with Node Evaluation metrics (label: Concept)', 'Node Mistral Large 2 (label: Model) has relationship SETSNEWPOINTON with Node Performance/cost Pareto front (label: Concept)', 'Node Mistral Large 2 (label: Model) has relationship RELATEDTO with Node Open models (label: Concept)', 'Node Mistral Large 2 (label: Model) has relationship ISBETTERAT with Node Precise instructions (label: Concept)', 'Node Mistral Large 2 (label: Model) has relationship ISBETTERAT with Node Long multi-turn conversations (label: Concept)', 'Node Mistral Large 2 (label: Model) has relationship ISEVALUATEDON with Node MT-Bench (label: Benchmark)', 'Node Mistral Large 2 (label: Model) has relationship ISEVALUATEDON with Node Wild Bench (label: Benchmark)', 'Node Mistral Large 2 (label: Model) has relationship ISEVALUATEDON with Node Arena Hard benchmarks (label: Benchmark)', 'Node Mistral Large 2 (label: Model) has relationship ISEVALUATEDON 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 and retrieval skills (label: Skill)', 'Node Mistral Large 2 (label: Model) has relationship TRAINEDTOEXECUTE with Node parallel and sequential function calls (label: Functionality)', 'Node Mistral Large 2 (label: Model) has relationship SERVESASPOWERENGINE with Node complex business applications (label: Application)', 'Node Mistral Large 2 (label: Technology) has relationship EXPOSEDON with Node la Plateforme (label: Platform)', 'Node Mistral Large 2 (label: Technology) has relationship ENRICHEDWITH with Node new features (label: Feature)', 'Node Mistral AI (label: Organization) has relationship PROVIDES with Node Mistral Large 2 (label: Model)', 'Node Mistral AI (label: Organization) has relationship HAS with Node Legal notice (label: Document)', 'Node Mistral AI (label: Organization) has relationship PARTNERSWITH with Node Google Cloud Platform (label: Cloud Service Provider)', 'Node Mistral AI (label: Organization) has relationship PROVIDESMODELSON with Node Vertex AI (label: Platform)', 'Node Mistral AI (label: Organization) has relationship PROVIDESMODELSON with Node Azure AI Studio (label: Platform)', 'Node Mistral AI (label: Organization) has relationship PROVIDESMODELSON with Node Amazon Bedrock (label: Platform)', 'Node Mistral AI (label: Organization) has relationship PROVIDESMODELSON with Node IBM watsonx.ai (label: Platform)']\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "Combine results from the vector search and knowledge graph entity search:"+ ],+ "metadata": {+ "id": "sjKr29w8eZ4n"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "# combine result from vector seach and knowledge graph entity search\n",+ "comined_results = str(vector_result) + \"\\n\".join(kg_result)"+ ],+ "metadata": {+ "id": "P9ne7UoB6GY5"+ },+ "execution_count": 19,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "Set up an assistant agent to answer questions based on the retrieved context:"+ ],+ "metadata": {+ "id": "q-NaDHypebKZ"+ }+ },+ {+ "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)"+ ],+ "metadata": {+ "id": "LxEUi36F7kq1",+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "outputId": "1387ff6d-52f3-4f23-d1b7-4a66b0806264"+ },+ "execution_count": 20,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "Mistral Large 2 is a model developed and provided by Mistral AI. It is the successor to the original Mistral Large model. Mistral Large 2 has several notable features and capabilities, including:\n",+ "\n",+ "1. **Capabilities**:\n",+ " - Code generation\n",+ " - Mathematics\n",+ " - Reasoning\n",+ " - Instruction-following capabilities\n",+ " - Conversational capabilities\n",+ "\n",+ "2. **Multilingual Support**:\n",+ " - Provides strong multilingual support for languages such as French, German, Spanish, Italian, Portuguese, Arabic, Hindi, Russian, Chinese, Japanese, Korean, English, and Dutch.\n",+ "\n",+ "3. **Advanced Function Calling Capabilities**:\n",+ " - Equipped with enhanced function calling and retrieval skills.\n",+ " - Trained to execute parallel and sequential function calls.\n",+ "\n",+ "4. **Context Window**:\n",+ " - Has a 128k context window.\n",+ "\n",+ "5. **Coding Language Support**:\n",+ " - Supports coding languages like Python, Java, C, C++, JavaScript, and Bash.\n",+ "\n",+ "6. **Design**:\n",+ " - Designed for single-node inference and long-context applications.\n",+ "\n",+ "7. **Attributes**:\n",+ " - Has 123 billion parameters.\n",+ " - Allows large throughput.\n",+ "\n",+ "8. **Licensing**:\n",+ " - Released under the Mistral Research License.\n",+ "\n",+ "9. **Performance**:\n",+ " - Sets a new frontier in performance, cost of serving, and evaluation metrics.\n",+ " - Sets a new point on the performance/cost Pareto front.\n",+ "\n",+ "10. **Evaluation**:\n",+ " - Evaluated on benchmarks such as MT-Bench, Wild Bench, Arena Hard benchmarks, and General alignment benchmarks.\n",+ "\n",+ "11. **Training Data**:\n",+ " - Trained on multilingual data.\n",+ "\n",+ "12. **Applications**:\n",+ " - Serves as a powerful engine for complex business applications.\n",+ "\n",+ "13. **Platforms**:\n",+ " - Exposed on platforms like la Plateforme.\n",+ " - Enriched with new features.\n",+ "\n",+ "Mistral AI, the organization, provides Mistral Large 2 and partners with various cloud service providers like Google Cloud Platform, Vertex AI, Azure AI Studio, Amazon Bedrock, and IBM watsonx.ai to offer their models.\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "## ๐ Highlights"+ ],+ "metadata": {+ "id": "ZMWitnLdlYCT"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "* Automated Knowledge Extraction: The Knowledge Graph Agent automates the extraction of entities and relationships, making the process efficient and effective.\n",+ "\n",+ "* Mistral AI Integration: This cookbook showcases the integration of Mistral AI's advanced models, particularly the Mistral Large 2, with CAMEL-AI to create a powerful knowledge graph system.\n",+ "\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": [- "# 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",- "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",- "* Mistral AI Integration: This cookbook showcases the integration of Mistral AI's advanced models, particularly the Mistral Large 2, with CAMEL-AI to create a powerful knowledge graph system.\n",- "\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."- ]- },- {- "cell_type": "markdown",- "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-}+ ]+}\ No newline at end of filediff --git a/docs/cookbooks/model_speed_comparison.ipynb b/docs/cookbooks/model_speed_comparison.ipynbindex 75513eb7e..50a457f14 100644--- a/docs/cookbooks/model_speed_comparison.ipynb+++ b/docs/cookbooks/model_speed_comparison.ipynb@@ -1,90 +1,115 @@{+ "nbformat": 4,+ "nbformat_minor": 0,+ "metadata": {+ "colab": {+ "provenance": []+ },+ "kernelspec": {+ "name": "python3",+ "display_name": "Python 3"+ },+ "language_info": {+ "name": "python"+ }+ },"cells": [{"cell_type": "markdown",- "metadata": {- "id": "APw8wDolb0L9"- },"source": ["# Model Speed Comparison Cookbook"- ]+ ],+ "metadata": {+ "id": "APw8wDolb0L9"+ }},{"cell_type": "markdown",- "metadata": {- "id": "vLCfmNtRb-jR"- },"source": ["You can also check this cookbook in colab [here](https://colab.research.google.com/drive/1oZfsgYfPPLVtMeA6DhsCd5jbdiAzEQSW?usp=sharing)"- ]+ ],+ "metadata": {+ "id": "vLCfmNtRb-jR"+ }},{"cell_type": "markdown",- "metadata": {- "id": "jHQhWNnhcOch"- },"source": ["## Overview\n","In this section, we'll explore the speed of different AI models by creating instances of `ChatAgent` and measuring their response times to user prompts."- ]+ ],+ "metadata": {+ "id": "jHQhWNnhcOch"+ }},{"cell_type": "markdown",- "metadata": {- "id": "XuZwbB1IIuUi"- },"source": ["### Installation"- ]+ ],+ "metadata": {+ "id": "XuZwbB1IIuUi"+ }},{"cell_type": "markdown",- "metadata": {- "id": "gIJK4Lu5Iwm0"- },"source": ["Ensure you have CAMEL AI installed in your Python environment:"- ]+ ],+ "metadata": {+ "id": "gIJK4Lu5Iwm0"+ }},{"cell_type": "code",- "execution_count": null,+ "source": [+ "!pip install \"camel-ai==0.2.4\""+ ],"metadata": {"id": "UtcC3c-KVZmU"},- "outputs": [],- "source": [- "%pip install \"camel-ai[all]==0.2.3a\""- ]+ "execution_count": null,+ "outputs": []},{"cell_type": "markdown",- "metadata": {- "id": "MyTTCe3IR_Lr"- },"source": ["### Setting Up API Keys"- ]+ ],+ "metadata": {+ "id": "MyTTCe3IR_Lr"+ }},{"cell_type": "markdown",- "metadata": {- "id": "REqzgGL9SEaD"- },"source": ["You'll need to set up your API keys for OpenAI and SambaNova."- ]+ ],+ "metadata": {+ "id": "REqzgGL9SEaD"+ }},{"cell_type": "code",- "execution_count": 2,+ "source": [+ "import os\n",+ "from getpass import getpass\n",+ "\n",+ "# Prompt for the API key securely\n",+ "openai_api_key = getpass('Enter your OpenAI API key: ')\n",+ "os.environ[\"OPENAI_API_KEY\"] = openai_api_key\n",+ "\n",+ "sambanova_api_key = getpass('Enter your SambaNova API key: ')\n",+ "os.environ[\"SAMBA_API_KEY\"] = sambanova_api_key"+ ],"metadata": {"colab": {"base_uri": "https://localhost:8080/"},"id": "PNBFEXc-R-0s",- "outputId": "bba35874-c5a0-49a8-c1b3-3070958845ef"+ "outputId": "1c9ad95d-50c5-4d8e-e83a-8ed24d44b2f7"},+ "execution_count": 3,"outputs": [{"name": "stdout",@@ -94,42 +119,10 @@"Enter your SambaNova API key: ยทยทยทยทยทยทยทยทยทยท\n"]}- ],- "source": [- "import os\n",- "from getpass import getpass\n",- "\n",- "# Prompt for the API key securely\n",- "openai_api_key = getpass('Enter your OpenAI API key: ')\n",- "os.environ[\"OPENAI_API_KEY\"] = openai_api_key\n",- "\n",- "sambanova_api_key = getpass('Enter your SambaNova API key: ')\n",- "os.environ[\"SAMBA_API_KEY\"] = sambanova_api_key"]},{"cell_type": "code",- "execution_count": 6,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/",- "height": 564- },- "id": "ZT2tYqYh6EDj",- "outputId": "bf30ee06-c0bf-4b57-8352-7d1809361836"- },- "outputs": [- {- "data": {- "image/png": "iVBORw0KGgoAAAANSUhEUgAAA88AAAIjCAYAAAA9eimOAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjcuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/bCgiHAAAACXBIWXMAAA9hAAAPYQGoP6dpAAB5yElEQVR4nOzdeXwNZ///8feRSEJWBEFJkIRILLE2tNZobClql9prraKlLW1tVUUXS1Hau6mttqKLWymhtQVVKqqS2lPu2lpbEmuTzO8P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qpTfeeENTp05V48aNVaJECU2aNEn+/v4aNmyYNm/enGn98ePH66uvvtLLL7+sQYMGKSYmRuHh4XbBeNmyZbpy5Yr69++v6dOnKyIiQtOnT1fXrl0zbS81NVUREREqUqSI3nnnnSz/YCBJMTEx6tSpkwoUKKBJkyZp4sSJql+/vmJjY80+Z86cUe3atbV27VoNGDBA48eP17Vr1/Tkk0/q888/z7TNiRMn6vPPP9ewYcM0YsQI7dixI1NI27lzp4KCgjRjxow7fgbZkdPaMly9elWRkZHatm2b1q9fr9q1a0vK/rko3bzdoW3btmrcuLHeffddFShQQN27d7cLrWPGjNHYsWPVoEEDzZgxQ6+++qpKlSqlH374IVvHN3DgQCUkJGjMmDHq2rWrFi5cqFatWtn94W3BggVq3ry53NzcNGnSJI0cOVLx8fF67LHHMp2r2T0vpJu/F3bv3q2ffvrJss7x48era9euCggI0OTJkzVkyBBt2LBBdevW1cWLF81+MTExqlu3ruLj4zV48GC9++67atCggVatWmX2yenPXvv27ZWcnKwJEyaoffv2mjt3bqZbTbL7uxXAPTIAALjFnDlzDEnG999/b8yYMcNwd3c3rly5YhiGYbRr185o0KCBYRiG4evrazRv3txc74svvjAkGW+88Ybd9tq2bWvYbDbj8OHDhmEYRlxcnCHJGDBggF2/zp07G5KM0aNHm229evUyihUrZvz+++92fTt27Gh4enqadR07dsyQZMyZM+eux/bTTz8Z+fLlMyQZVapUMQYPHmx88cUXxuXLlzP19fX1NSQZK1asMNsuXbpkFCtWzAgNDTXbxo0bZ7i6uhoHDx60W3/48OGGg4ODcfz4ccMwDGPLli2GJGPhwoV2/b7++mu79rNnzxpOTk5G8+bNjfT0dLPfK6+8YkgyunXrdtdjbN26tSHJuHDhwl37ZahSpYpRpEgR49y5c2bb3r17jTx58hhdu3Y120aPHm1IMvr06WO2paamGo888ohhs9mMiRMnmu0XLlww8uXLZ1frt99+a0gySpQoYSQlJZntn376qSHJmDZtmtmW8bneasKECYbNZjN++eUXs61bt26GJGP48OGZ+nfr1s3w9fU13w8ePNjw8PAwUlNT7zgWQ4YMMSQZW7ZsMduSk5ON0qVLG35+fkZaWprdsQQFBRnXr183+06bNs2QZOzbty/Tcd96XmdHcHCwUa9evXuubdmyZUZycrJRr149w9vb29izZ4+5XnbPRcP4v5+DzZs3m21nz541nJ2djaFDh5ptlStXtvt9kF0Zv2+qVatm3Lhxw2x/6623DEnGl19+aR6rl5eX0bt3b7v1T58+bXh6etq13+28yMq6desMBwcHw8HBwQgLCzNeeuklY+3atXb1GIZhJCYmGg4ODsb48ePt2vft22c4Ojqa7ampqUbp0qUNX1/fTD+Ht/5M5/Rnr2fPnnbbat26tVGoUCHzfU5+twK4N8w8AwDuqH379rp69apWrVql5ORkrVq16o6XbK9evVoODg4aNGiQXfvQoUNlGIbWrFlj9pOUqd+QIUPs3huGoRUrVigyMlKGYej33383XxEREbp06VK2Z7UyBAcHKy4uTk8//bQSExM1bdo0tWrVSkWLFtV//vOfTP2LFy+u1q1bm+8zLifds2ePTp8+LenmLOnjjz+uAgUK2NUYHh6utLQ0c/Z12bJl8vT0VOPGje36VatWTW5ubvr2228l3ZyNunHjhp577jm7pyvfPj53kpSUJElyd3e37Hvq1CnFxcWpe/fuKliwoNleqVIlNW7c2PysbvXMM8+Y/+3g4KDq1avLMAz16tXLbPfy8lK5cuV09OjRTOt37drVrra2bduqWLFidvvKly+f+d+XL1/W77//rtq1a8swDO3ZsyfTNvv37295rF5eXrp8+fJdLyNevXq1atasafeQPDc3N/Xp00eJiYmKj4+369+jRw85OTmZ7x9//HFJsjvu+vXryzCMP/01QTmt7dKlS3riiSf0888/a+PGjapSpYq5LLvnYoYKFSqYxyZJhQsXzvT5enl5af/+/Tp06NA9HV+fPn3s7lPv37+/HB0dzfMiJiZGFy9eVKdOnexqdnBwUK1atTLVnLGN7GjcuLG2b9+uJ598Unv37tVbb72liIgIlShRwrySQ5I+++wzpaenq3379nY1+Pj4KCAgwKxhz549OnbsmIYMGZLpUvCMn+l7+dnr16+f3fvHH39c586dM3/ms/u7Fc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zabLcu29PT0bNeV3X1ncHR01Pjx4zVt2jSdPHky2/vJ4OPjo4YNG2rRokWSpEWLFikqKspcvmTJEg0bNky9evXSunXrFBcXpx49emRZy73q1q2b4uLiNG3aNG3btk1xcXEqVKhQpn3cOrY2m+2ObRnjPWzYMH3++ed68803tWXLFsXFxalixYrZqt0wDH388cfq0qWLnJyczHZvb285ODiY941nOHPmjHx8fOzavL295e/vr4CAADVs2FBTp07Vtm3b9O2332a5T2dnZ3l4eNi9AAAAACC7Hsr3PFeoUEGXL1+WJO3evVvp6el699139eijjyowMPCegumdZMzy3vo+KCjonvfdrl07BQcHZ7rkNygoSCdOnLCbwYyPj9fFixdVoUIFsy0qKkpLly7V9u3bdfToUXXs2NFcFhsbq9q1a2vAgAEKDQ2Vv7+/3UO57ofY2FgNGjRIzZo1U3BwsJydnc1L1P/sdrt3767WrVurYsWK8vHxUWJiYrbW3bRpkw4fPqxevXrZtTs5OalatWrmTLJ0M6xv2LAh0xUFt3NwcJCku15WDgAAAAD3yvF+buzcuXNq166devbsqUqVKsnd3V27du3SW2+9pZYtW0qS/P399ccff2j69OmKjIxUbGysec/y/RAbG6u33npLrVq1UkxMjJYtW6avvvrqT+174sSJioiIsGsLDw9XxYoVFRUVpalTpyo1NVUDBgxQvXr1VL16dbPfU089pf79+6t///5q0KCBihcvbi4LCAjQ/PnztXbtWpUuXVoLFizQ999/r9KlS1vWdODAgUxtt39fcsY+FixYoOrVqyspKUkvvvii8uXLZ7l9KwEBAfrss88UGRkpm82mkSNHZvsqgOjoaNWqVUshISGZlr3wwgvq1q2bqlevrpo1a2rq1Km6fPmy3RO5pZsPQjt9+rQMw9CJEyf00ksvqXDhwqpdu/afPjYAAAAAuN19f9p2rVq1NGXKFNWtW1chISEaOXKkevfurRkzZkiSKleurMmTJ2vSpEkKCQnRwoULNWHChPtWw9ChQ7Vr1y6FhobqjTfe0OTJk83ge6/7btiwoRo2bKjU1FSzzWaz6csvv1SBAgVUt25dhYeHq0yZMlq6dKnduu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du7hT2/yUmJspmsykuLi5X6/izYmNj5ejomGXQnzlzpvz8/OTi4qJatWpp586ddsvr168vm81m9+rXr5+5PGOMMl5OTk7y9/fXG2+8IcMwHvShAQAAAPiXcsxJ5zZt2ujGjRuaN2+eypQpozNnzmjDhg06d+7cg6rvgTh69Kjmz5+vHj165HYp/zgXL15U165d1ahRI505c8Zu2dKlS/XCCy9o9uzZqlWrlqZOnaqIiAgdOHBARYoUMfv17t1br7/+uvk+f/78mfazfv16BQcH6/r169q6daueeeYZFStWTL169XpwBwcAAADgXyvbM88XL17Uli1bNGnSJDVo0EC+vr6qWbOmRowYoSeffNLsN3nyZFWsWFGurq4qWbKkBgwYoJSUFHP53Llz5eXlpVWrVqlcuXLKnz+/2rZtqytXrmjevHny8/NTgQIFNGjQoEyzw8nJyerUqZNcXV1VokQJzZw502651b4zPPfccxo9erSuX79+x+M9fvy4WrZsKTc3N3l4eKh9+/ZmGDx48KBsNpt+/vlnu3WmTJmismXLSpLS0tLUq1cvlS5dWvny5VO5cuU0bdq0bI529nz//fdq3LixvL295enpqXr16umHH36w62Oz2fTBBx+oRYsWyp8/v4KCgrR9+3YdPnxY9evXl6urq2rXrq0jR46Y6xw5ckQtW7ZU0aJF5ebmpho1amj9+vXZqqlfv37q3LmzwsLCMi2bPHmyevfurR49eqhChQqaPXu28ufPr48//tiuX/78+eXj42O+PDw8Mm2rUKFC8vHxka+vr6KiolSnTp1Mxw4AAAAA90u2w7Obm5vc3Nz0xRdf3DV05smTR++9957279+vefPm6ZtvvtFLL71k1+fKlSt67733tGTJEn399dfauHGjWrdurdWrV2v16tVasGCBPvjgAy1fvtxuvbfffluVK1fWnj17NHz4cA0ePFgxMTE52rckDRkyRKmpqZo+fXqWx5Cenq6WLVvq/Pnz2rRpk2JiYnT06FF16NBBkhQYGKjq1atr4cKFdustXLhQnTt3NrfxyCOPaNmyZYqPj9eoUaP0yiuv6NNPP73LKOdMcnKyunXrpq1bt2rHjh0KCAhQs2bNlJycbNdv3Lhx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qKilLhwoWVL18+BQQEaM6cOXesoX79+ho4cKAGDhwoT09PeXt7a+TIkTIMw+xz/fp1DRs2TCVKlJCrq6tq1aqljRs3msvnzp0rLy8vrVy5UhUqVJCzs7N5PLf673//qzp16ujFF19UuXLlFBgYqFatWmnmzJl2/azG4OLFi+rbt6+KFi0qFxcXhYSEaNWqVebyFStWKDg4WM7OzvLz89O7775rt30/Pz+9+eab6tmzp9zd3VWqVCl9+OGHdn127typ0NBQubi4qHr16tqzZ88dxxAAkDXCMwAAyNK0adP07rvv6p133tGPP/6oiIgIPfnkkzp06FCmvtevX1e7du0UFxenLVu2qFSpUtqyZYu6du2qwYMHKz4+Xh988IHmzp2r8ePH2607duxYtW/fXj/++KOaNWumqKgonT9/XpI0cuRIxcfHa82aNUpISNCsWbPk7e1917rnzZsnR0dH7dy5U9OmTdPkyZP10UcfmcsHDhyo7du3a8mSJfrxxx/Vrl07NWnSxO64rly5okmTJumjjz7S/v37VaRIkUz78fHx0f79+/XTTz/dsRarMUhPT1fTpk0VGxurTz75RPHx8Zo4caIcHBwkSbt371b79u3VsWNH7du3T2PGjNHIkSM1d+5cu/28++67ZigeMGCA+vfvb15BkJKSohYtWqhChQravXu3xowZo2HDht11DAEAWTAAAAAMw5gzZ47h6elpvi9evLgxfvx4uz41atQwBgwYYBiGYRw7dsyQZGzZssVo1KiR8dhjjxkXL140+zZq1Mh488037dZfsGCBUaxYMfO9JOO1114z36ekpBiSjDVr1hiGYRiRkZFGjx49sn0M9erVM4KCgoz09HSz7eWXXzaCgoIMwzCMX375xXBwcDB+/fVXu/UaNWpkjBgxwhwHSUZcXNxd95WSkmI0a9bMkGT4+voaHTp0MKKjo41r165lewzWrl1r5MmTxzhw4ECW++jcubPRuHFju7YXX3zRqFChgvne19fXePrpp8336enpRpEiRYxZs2YZhmEYH3zwgVGoUCHj6tWrZp9Zs2YZkow9e/bc9RgBAP+HmWcAAJBJUlKSTp48qTp16ti116lTRwkJCXZtnTp10uXLl7Vu3Tp5enqa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CpUqKCVK1cqICAgy/5DhgxRenq6mjVrpq+//loRERFatWqVXn/9dU2aNEl58+ZV+fLl9cwzz2S7BicnJzPw5cuXT48//riWLFly13W6du2qq1evqmbNmnJwcNDgwYPVp08fc/mcOf+vvTvETSCKwjD612NIMHgSEhTjcLAAHJ4g8aARgAA3ZnQ9CQrHfhCsAkSTpu5R1bQ9ZwV3xn258968Z7/fZ7Va5Xa7pdPpZDQaZTqdvjxXkozH4zRNk/l8nvv9nna7naqqcr1e0+/3k+Sld3A+n7Nerz/Pjvd6vRwOhyQfm+vT6ZTNZpPdbpdut5vtdpvFYvHynK1WK5fLJcvlMlVVZTAY5Hg8Zjabfet5Af67t8fjy48PAQB+sclkkuFwmLquf3oUAP4Yt20DAABAgXgGAACAAp9tAwAAQIHNMwAAABSIZwAAACgQzwAAAFAgngEAAKBAPAMAAECBeAYAAIAC8QwAAAAF4hkAAAAKnmFNL0ho5cq8AAAAAElFTkSuQmCC",- "text/plain": [- "<Figure size 1000x600 with 1 Axes>"- ]- },- "metadata": {},- "output_type": "display_data"- }- ],"source": ["import time\n","import matplotlib.pyplot as plt\n",@@ -196,21 +189,36 @@"\n","# Visualize the results\n","plot_results(model_names, tokens_per_sec)"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/",+ "height": 620+ },+ "id": "ZT2tYqYh6EDj",+ "outputId": "93440028-f9a0-47e0-aafb-1055601f37ce"+ },+ "execution_count": 4,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stderr",+ "text": [+ "/usr/local/lib/python3.10/dist-packages/camel/models/openai_model.py:107: UserWarning: Warning: You are using an O1 model (O1_MINI or O1_PREVIEW), which has certain limitations, reference: `https://platform.openai.com/docs/guides/reasoning`.\n",+ " warnings.warn(\n"+ ]+ },+ {+ "output_type": "display_data",+ "data": {+ "text/plain": [+ "<Figure size 1000x600 with 1 Axes>"+ ],+ "image/png": "iVBORw0KGgoAAAANSUhEUgAAA88AAAIjCAYAAAA9eimOAAAAOXRFWHR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YxpYtWwxJxvz58+36rVmzxq797NmzhpOTk9G8eXMjPT3d7Pfqq68akoxu3brd9Rhbt25tSDIuXLhw134ZqlSpYhQpUsQ4d+6c2bZ3714jT548RteuXc22UaNGGZKMPn36mG2pqanGI488YthsNmPChAlm+4ULF4x8+fLZ1frtt98akowSJUoYSUlJZvsXX3xhSDKmTp1qtmV8rrcaP368YbPZjF9++cVs69atmyHJGDZsWKb+3bp1M3x9fc33gwYNMjw8PIzU1NQ7jsXgwYMNScaWLVvMtuTkZKN06dKGn5+fkZaWZncsQUFBxvXr182+U6dONSQZ+/bty3Tct57X2REcHGzUq1fvnmtbvHixkZycbNSrV8/w9vY29uzZY66X3XPRMP7v52Dz5s1m29mzZw1nZ2djyJAhZlvlypXtfh9kV8bvm2rVqhk3btww299++21DkvHVV1+Zx+rl5WX07t3bbv3Tp08bnp6edu13Oy+ysm7dOsPBwcFwcHAwwsLCjJdfftlYu3atXT2GYRiJiYmGg4ODMW7cOLv2ffv2GY6OjmZ7amqqUbp0acPX1zfTz+GtP9M5/dnr2bOn3bZat25tFCpUyHyfk9+tAO4NM88AgDtq3769rl69qpUrVyo5OVkrV6684yXbq1atkoODgwYOHGjXPmTIEBmGodWrV5v9JGXqN3jwYLv3hmFo6dKlioyMlGEY+v33381XRESELl26lO1ZrQzBwcGKi4vT008/rcTERE2dOlWtWrVS0aJF9Z///CdT/+LFi6t169bm+4zLSffs2aPTp09LujlL+vjjj6tAgQJ2NYaHhystLc2cfV28eLE8PT3VuHFju37VqlWTm5ubvv32W0k3Z6Nu3Lih559/3u7pyrePz50kJSVJktzd3S37njp1SnFxcerevbsKFixotleqVEmNGzc2P6tbPfPMM+Z/Ozg4qHr16jIMQ7169TLbvby8VK5cOR09ejTT+l27drWrrW3btipWrJjdvvLly2f+9+XLl/X777+rdu3aMgxDe/bsybTNfv36WR6rl5eXLl++fNfLiFetWqWaNWvaPSTPzc1Nffr0UWJiouLj4+369+jRQ05OTub7xx9/XJLsjrt+/foyDONPf01QT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QkePHtWpU6fM15QpU+Th4WHXNnTo0DvWkJiYqKFDh+rxxx/PtGzHjh2qVauWbty4oa+//loHDx7UuHHjNHv2bDVu3Fg3bty46/EVK1ZM3377rf73v//ZtX/66acqVaqUXZunp6e8vLwsRsyej4+PnJ2dc7QOAAAAAGTXQxWen3vuOTk5OWndunWqV6+eSpUqpaZNm2r9+vX69ddf9dprr5l9/fz8NHbsWHXq1Emurq4qUaKEpk+fbre9ixcv6plnnlHhwoXl4eGhhg0bau/eveby0aNHq0qVKpo3b578/Pzk6empjh07Kjk52W47KSkpWrRokfr166fmzZvneNbUMAx1795dgYGBio2NVWRkpAICAhQQEKBOnTpp69atqlSpkt06Xl5e8vHxUUhIiGbMmKGrV68qJiZGPj4+5svT01M2m82uzc3NLcsa0tLSFBUVpTFjxqhMmTKZ6uvVq5eCgoL05ZdfqmbNmvL19VW7du303//+V9u3b9fkyZPveoxFihTRE088oTlz5pht27Zt0++//55ptv72y7br16+vgQMH6uWXX1bBggXl4+OTaQady7YBAAAAPEgPTXg+f/681q5dq/79+ytfvnx2y3x8fBQVFaVFixbJMAyz/Z133lHlypW1Z88eDRs2TIMGDVJMTIy5vF27djp79qxWr16t3bt3q2rVqmrUqJHdDPaRI0e0fPlyrVy5UitXrtSmTZs0YcIEu/1/8cUXKl++vMqVK6enn35an376qV0dVuLi4pSQkKChQ4cqT56sPxKbzXbH9TPGw2r2927eeOMNFSlSRL169cqyvvj4eL344ouZ6qtcubLCw8O1YMECy3307NnT7g8Ln376qaKiouTk5GS57pw5c+Tq6qrvvvtOb7/9tt544w27z9LK9evXlZSUZPcCAAAAgOx6aMLzoUOHZBiGgoKCslweFBSkCxcu6LfffjPb6tSpo2HDhikwMFDPP/+82rZta86Qbt26VTt37tTixYtVvXp1BQQE6N1335WXl5eWLFlibiM9PV2zZ89WSEiIHn/8cXXp0kUbNmyw23d0dLSefvppSVKTJk106dIlbdq0KdvHdvDgQUlSuXLlzLazZ8/Kzc3NfH344YdZrnvlyhW9/vr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fbrTd//nx17tzZ3MYjjzyixYsXKz4+XiNHjtSrr76qL7744i6jnDPJycnq1q2btm7dqh07diggIEDNmjVTcnKyXb+xY8eqa9euiouLU/ny5dW5c2c9++yzGj58uHbt2iXDMDRgwACzf0pKipo1a6YNGzZoz549atKkiSIjI3X8+PFs1xYdHa3w8HD5+vpKkm7cuKHdu3crPDzc7JMnTx6Fh4dr+/btd9zOr7/+qv/+97+qVavWHftcv35dSUlJdi8AAAAAyC6bYRjG/dzg0qVL1bt3b129elVVq1ZVvXr11LFjR1WqVOmO6yxZskR9+/bV77//LunmzHOPHj10+PBhc5a2b9++mjdvns6cOSM3NzdJUpMmTeTn56eZM2dKunkvbFBQkFavXm1uu2PHjkpKStKqVauyte+NGzeqQYMGunDhghYtWqRXX31VR48elaenp7y8vDRlyhR1795dMTExatq0qY4dO6aSJUtKkuLj4xUcHKydO3eqRo0amjJliqZNm6bDhw9LujkbXa5cOSUkJKh8+fJZ1jNgwACdPn060x8FMiQmJqp06dLas2dPlg8GGz16tJYvX37He6LT09Pl5eWlzz//XC1atJB0c+b59ddf19ixYyVJO3bsUFhYmKKjo9WzZ09J0sKFC9WjRw9dvXo1y+1KUkhIiPr27WsXsu/k5MmTKlWqlD7//HO1b9/ebCtRooS2bdumsLAws+/LL7+sTZs26bvvvpN083M+deqU8ubNq7S0NF27dk21atXSmjVr5OXlleX+Ro8erTFjxmRqH7X5qFzc3C3rBQDcf8NCvXO7BAAAlJSUJE9PT126dEkeHh537PdA7nk+efKkVqxYoSZNmmjjxo2qWrWq3YO21q9fr0aNGqlEiRJyd3dXly5ddO7cOV25csXskz9/fjM4S1LRokXl5+dnBueMttvvhb01dGW8T0hIyNG+M/Tq1UuFChXSxIkTMy1LSEhQyZIlzeAsSRUqVJCXl5e5v44dOyoxMVE7duyQdHPWuWrVqnbBefr06apWrZoKFy4sNzc3ffzxxzmavbVy5swZ9e7dWwEBAfL09JSHh4dSUlIy7ePWP24ULVpUklSxYkW7tmvXrpkztikpKRo6d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yTdnC2tWrWqypcvb64zffp0VatWTYULF5abm5s+/vhjy9nbnDhz5ox69+6tgIAAeXp6ysPDQykpKZn2cesfNzLCa8WKFe3arl27Zs7GpqSkaOjQoQoKCpKXl5fc3NyUkJBwx9rT0tLUuXNnjRkzRoGBgX/qmPr06aOIiAhVrFhRUVFRmjt3rpYtW2Z3Wbl08/7puLg47d27V1988YW++uor8w8rWRk+fLguXbpkvk6cOPGn6gQAAADw75Ljr6pycXFR48aNNWLECG3btk3du3c3L9NNTExUixYtVKlSJS1dulS7d+8270u+ceOGuY28efPabdNms2XZlp6enu26srvvDI6Ojho3bpymTp2qkydPZns/GXx8fNSwYUN9/vnnkqTPP/9cUVFR5vKFCxdq6NCh6tWrl9atW6e4uDj16NEjy1ruVbdu3RQXF6epU6dq27ZtiouLU6FChTLt49axtdlsd2zLGO+hQ4dq2bJleuutt7RlyxbFxcWpYsWKd6w9OTlZu3bt0oABA+To6ChHR0e98cYb2rt3rxwdHfXNN9/I29tbDg4OmR4idubMGfn4+NzxGDMuxT58+LBde8mSJeXv76+goCC1a9dOgwcP1nvvvadr165luR1nZ2d5eHjYvQAAAAAgu/709zxXqFBBly9fliTt3r1b6enpeu+99/Too48qMDDwnoLpnWTM8t76Pigo6J733a5dOwUHB2e6nDcoKEgnTpywm52Mj4/XxYsXVaFCBbMtKipKixYt0vbt23X06FF17NjRXBYbG6vatWurf//+Cg0Nlb+/f6bZ0z8rNjZWAwcOVLNmzRQcHCxnZ2f9/vvv92W73bt3V+vWrVWxYkX5+PgoMTHxjv09PDy0b98+xcXFma++ffuqXLlyiouLU61ateTk5KRq1appw4YN5nrp6enasGFDlg8Xy5DxtV3FihW7a80ODg5KTU29r3+cAAAAAIAM2b7n+dy5c2rXrp169uypSpUqyd3dXbt27dLbb7+tli1bSpL8/f31xx9/6IMPPlBkZKRiY2M1c+bM+1ZsbGys3n77bbVq1UoxMTFavHixvv766z+17wkTJpj3/mYIDw83LxueMmWKUlNT1b9/f9WrV0/Vq1c3+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09P2Ww2832RIkU0adIkPfLII3J2dlaVKlW0Zs2aO24rLS1NPXv2VPny5XX8+HFJ0ldffaWqVavKxcVFZcqU0ZgxY5SammquY7PZ9Mknn6h169bKnz+/AgICtGLFCnP5hQsXFBUVpcKFCytfvnwKCAjQrFmz7lhD/fr1NWDAAA0YMECenp7y9vbWiBEjZBiG2ef69esaOnSoSpQoIVdXV9WqVUsbN240l8+ePVteXl5asWKFKlSoIGdnZ/N4bvXf//5XderU0UsvvaRy5copMDBQrVq10vTp0+36WY3BxYsX9eyzz6po0aJycXFRSEiIVq5caS5funSpgoOD5ezsLD8/P7333nt22/fz89Nbb72lnj17yt3dXaVKldLHH39s12fnzp0KDQ2Vi4uLqlevrj179txxDAEAWSM8AwCALE2dOlXvvfee3n33Xf3444+KiIjQk08+qUOHDmXqe/36dbVr105xcXHasmWLSpUqpS1btqhr164aNGiQ4uPj9dFHH2n27NkaN26c3bpjxoxR+/bt9eOPP6pZs2aKiorS+fPnJUkjRoxQfHy8Vq9erYSEBM2YMUPe3t53rXvOnDlydHTUzp07NXXqVE2aNEmffPKJuXzAgAHavn27Fi5cqB9//FHt2rVTkyZN7I7rypUrmjhxoj755BPt379fRYoUybQfHx8f7d+/Xz/99NMda7Eag/T0dDVt2lSxsbH67LPPFB8frwkTJsjBwUGStHv3brVv314dO3bUvn37NHr0aI0YMUKzZ8+22897771nhuL+/furX79+5hUEKSkpatGihSpUqKDdu3dr9OjRGjp06F3HEACQBQMAAMAwjFmzZhmenp7m++LFixvjxo2z61OjRg2jf//+hmEYxrFjxwxJxpYtW4xGjRoZjz32mHHx4kWzb6NGjYy33nrLbv158+YZxYoVM99LMl5//XXzfUpKiiHJWL16tWEYhhEZGWn06NEj28dQr149IygoyEhPTzfbXnnlFSMoKMgwDMP45ZdfDAcHB+PXX3+1W69Ro0bG8OHDzXGQZMTFxd11XykpKUazZs0MSYavr6/RoUMHIzo62rh27Vq2x2Dt2rVGnjx5jAMHDmS5j86dOxuNGze2a3vppZeMChU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Ngb16tVT3bp11aZNG02aNEn+/v76+eefZbPZ1KRJEw0ZMkQ1atTQ2LFj1aFDB23fvl3Tpk3Thx9+mO06O3furNdee029e/fW8OHDlZiYeM8z9wDwb0Z4BgAAWRo4cKAuXbqkIUOG6OzZs6pQoYJWrFihgICALPsPHjxY6enpatasmdasWaOIiAitXLlSb7zxhiZOnKi8efOqfPnyeuaZZ7Jdg5OTkxn48uXLp8cff1wLFy686zpdu3bV1atXVbNmTTk4OGjQoEHq06ePuXzW/2vvDnETiKIwjP71GBIMnoQExTgcLACHJ0g8aAQgwI0ZjSdB4dgPglVQ0aSpe1Q1bc9ZwZ1xX+68N6dT9vt9VqtV7vd7Op1ORqNRptPpy3MlyXg8TtM0mc/neTweabfbqaoqt9st/X4/SV56B5fLJev1+vPseK/Xy+FwSPKxuT6fz9lsNtntdul2u9lut1ksFi/P2Wq1cr1es1wuU1VVBoNBjsdjZrPZt54X4L97ez6//PgQAOAXm0wmGQ6Hqev6p0cB4I9x2zYAAAAUiGcAAAAo8Nk2AAAAFNg8AwAAQIF4BgAAgALxDAAAAAXiGQAAAArEMwAAABSIZwAAACgQzwAAAFAgngEAAKDgHUy/L0hI2QupAAAAAElFTkSuQmCC\n"+ },+ "metadata": {}+ }]}- ],- "metadata": {- "colab": {- "provenance": []- },- "kernelspec": {- "display_name": "Python 3",- "name": "python3"- },- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 0-}+ ]+}\ No newline at end of filediff --git a/docs/cookbooks/roleplaying_scraper.ipynb b/docs/cookbooks/roleplaying_scraper.ipynbindex 602990300..fdc8d0a0f 100644--- a/docs/cookbooks/roleplaying_scraper.ipynb+++ b/docs/cookbooks/roleplaying_scraper.ipynb@@ -1,1408 +1,1423 @@{- "cells": [- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "ymsq1Lw0VEqT"- },- "source": [- "# Role-Playing **Scraper** for **Report** & **Knowledge Graph** Generation\n"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "7V3aV16AmY0K"- },- "source": [- "You can also check this cookbook in colab [here](https://colab.research.google.com/drive/1XN18zb5ay97ju8LvL7WikEDqQBws-t0U?usp=sharing)"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "G5gE04UuPUWj"- },- "source": [- "This notebook demonstrates how to set up and leverage CAMEL's Retrieval-Augmented Generation (RAG) combined with Firecrawl for efficient web scraping, multi-agent role-playing tasks, and knowledge graph construction. We will walk through an example of conducting a comprehensive study of the Turkish shooter in the 2024 Paris Olympics by using Mistral's models.\n",- "\n",- "In this notebook, you'll explore:\n",- "\n",- "* **CAMEL**: A powerful multi-agent framework that enables Retrieval-Augmented Generation and multi-agent role-playing scenarios, allowing for sophisticated AI-driven tasks.\n",- "* **Mistral**: Utilized for its state-of-the-art language models, which enable tool-calling capabilities to execute external functions, while its powerful embeddings are employed for semantic search and content retrieval.\n",- "* **Firecrawl**: A robust web scraping tool that simplifies extracting and cleaning content from various web pages.\n",- "* **AgentOps**: Track and analysis the running of CAMEL Agents.\n",- "* **Qdrant**: An efficient vector storage system used with CAMELโs AutoRetriever to store and retrieve relevant information based on vector similarities.\n",- "* **Neo4j**: A leading graph database management system used for constructing and storing knowledge graphs, enabling complex relationships between entities to be mapped and queried efficiently.\n",- "* **DuckDuckGo Search**: Utilized within the SearchToolkit to gather relevant URLs and information from the web, serving as the primary search engine for retrieving initial content.\n",- "* **Unstructured IO:** Used for content chunking, facilitating the management of unstructured data for more efficient processing.\n",- "\n",- "\n",- "This setup not only demonstrates a practical application but also serves as a flexible framework that can be adapted for various scenarios requiring advanced web information retrieval, AI collaboration, and multi-source data aggregation."- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "soIw38pJLv2f"- },- "source": [- "โญ **Star the Repo**\n",- "\n",- "If you find CAMEL useful or interesting, please consider giving it a star on our [CAMEL GitHub Repo](https://github.com/camel-ai/camel)! Your stars help others find this project and motivate us to continue improving it."- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "vq-HTbJyN4wn"- },- "source": [- ""- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "0J0_iW-YVcq2"- },- "source": [- "## ๐ฆ Installation"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "7p-JjpyNVcCT"- },- "source": [- "First, install the CAMEL package with all its dependencies:"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "collapsed": true,- "id": "0GXs2pruU9Vl"- },- "outputs": [],- "source": [- "%pip install \"camel-ai[all]==0.2.1\""- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "lfNvFbhD6o8B"- },- "source": [- "## ๐ Setting Up API Keys"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "jqV12oQfQTyl"- },- "source": [- "You'll need to set up your API keys for Mistral AI, Firecrawl and AgentOps. This ensures that the tools can interact with external services securely."- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "Sc3MAQwiH9Pd"- },- "source": [- "You can go to [here](https://app.agentops.ai/signin) to get **free** API Key from AgentOps\n"- ]- },- {- "cell_type": "code",- "execution_count": 2,- "metadata": {+ "nbformat": 4,+ "nbformat_minor": 0,+ "metadata": {"colab": {- "base_uri": "https://localhost:8080/"+ "provenance": []},- "id": "HQ_yOT5_Hyt4",- "outputId": "13d7251a-108b-4578-a6aa-24667afaadda"- },- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "Enter your API key: ยทยทยทยทยทยทยทยทยทยท\n"- ]+ "kernelspec": {+ "name": "python3",+ "display_name": "Python 3"+ },+ "language_info": {+ "name": "python"}- ],- "source": [- "import os\n",- "from getpass import getpass\n",- "\n",- "# Prompt for the AgentOps API key securely\n",- "agentops_api_key = getpass('Enter your API key: ')\n",- "os.environ[\"AGENTOPS_API_KEY\"] = agentops_api_key"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "czxWvnvnAimt"- },- "source": [- "Your can go to [here](https://console.mistral.ai/api-keys/) to get API Key from Mistral AI with **free** credits."- ]},- {- "cell_type": "code",- "execution_count": 3,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"+ "cells": [+ {+ "cell_type": "markdown",+ "source": [+ "# ๐ซ CAMEL Role-Playing **Scraper** for **Report** & **Knowledge Graph** Generation\n"+ ],+ "metadata": {+ "id": "ymsq1Lw0VEqT"+ }},- "id": "T0FBl1WF6jFs",- "outputId": "a1133116-6137-4345-b013-13abbeb8178c"- },- "outputs": [{- "name": "stdout",- "output_type": "stream",- "text": [- "Enter your API key: ยทยทยทยทยทยทยทยทยทยท\n"- ]- }- ],- "source": [- "# 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",- "metadata": {- "id": "qdG7LbDgDNe7"- },- "source": [- "Set up the Mistral Large 2 model using the CAMEL ModelFactory. You can also configure other models as needed."- ]- },- {- "cell_type": "code",- "execution_count": 4,- "metadata": {- "id": "ojjHCTsUDK6s"- },- "outputs": [],- "source": [- "from camel.models import ModelFactory\n",- "from camel.types import ModelPlatformType, ModelType\n",- "from camel.configs import MistralConfig\n",- "\n",- "# Set up model\n",- "mistral_large_2 = ModelFactory.create(\n",- " model_platform=ModelPlatformType.MISTRAL,\n",- " model_type=ModelType.MISTRAL_LARGE,\n",- " model_config_dict=MistralConfig(temperature=0.2).as_dict(),\n",- ")"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "akkwlXcjTLcH"- },- "source": [- "Your can go to [here](https://www.firecrawl.dev/) to get API Key from Firecrawl with **free** credits."- ]- },- {- "cell_type": "code",- "execution_count": 5,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"+ "cell_type": "markdown",+ "source": [+ "You can also check this cookbook in colab [here](https://colab.research.google.com/drive/1XN18zb5ay97ju8LvL7WikEDqQBws-t0U?usp=sharing)"+ ],+ "metadata": {+ "id": "7V3aV16AmY0K"+ }},- "id": "0byeytnFWiaG",- "outputId": "72fa62c9-c046-4e75-e6a6-017494551537"- },- "outputs": [{- "name": "stdout",- "output_type": "stream",- "text": [- "Enter your API key: ยทยทยทยทยทยทยทยทยทยท\n"- ]- }- ],- "source": [- "# Prompt for the Firecrawl API key securely\n",- "firecrawl_api_key = getpass('Enter your API key: ')\n",- "os.environ[\"FIRECRAWL_API_KEY\"] = firecrawl_api_key"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "kiyIq4I3pSE2"- },- "source": [- "## ๐ Web Scraping with Firecrawl"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "qgx3GS9LNaVe"- },- "source": [- "Firecrawl is a powerful tool that simplifies web scraping and cleaning content from web pages. In this section, we will scrape content from a specific post on the CAMEL AI website as an example."- ]- },- {- "cell_type": "code",- "execution_count": 13,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"+ "cell_type": "markdown",+ "source": [+ "This notebook demonstrates how to set up and leverage CAMEL's Retrieval-Augmented Generation (RAG) combined with Firecrawl for efficient web scraping, multi-agent role-playing tasks, and knowledge graph construction. We will walk through an example of conducting a comprehensive study of the Turkish shooter in the 2024 Paris Olympics by using Mistral's models.\n",+ "\n",+ "In this notebook, you'll explore:\n",+ "\n",+ "* **CAMEL**: A powerful multi-agent framework that enables Retrieval-Augmented Generation and multi-agent role-playing scenarios, allowing for sophisticated AI-driven tasks.\n",+ "* **Mistral**: Utilized for its state-of-the-art language models, which enable tool-calling capabilities to execute external functions, while its powerful embeddings are employed for semantic search and content retrieval.\n",+ "* **Firecrawl**: A robust web scraping tool that simplifies extracting and cleaning content from various web pages.\n",+ "* **AgentOps**: Track and analysis the running of CAMEL Agents.\n",+ "* **Qdrant**: An efficient vector storage system used with CAMELโs AutoRetriever to store and retrieve relevant information based on vector similarities.\n",+ "* **Neo4j**: A leading graph database management system used for constructing and storing knowledge graphs, enabling complex relationships between entities to be mapped and queried efficiently.\n",+ "* **DuckDuckGo Search**: Utilized within the SearchToolkit to gather relevant URLs and information from the web, serving as the primary search engine for retrieving initial content.\n",+ "* **Unstructured IO:** Used for content chunking, facilitating the management of unstructured data for more efficient processing.\n",+ "\n",+ "\n",+ "This setup not only demonstrates a practical application but also serves as a flexible framework that can be adapted for various scenarios requiring advanced web information retrieval, AI collaboration, and multi-source data aggregation."+ ],+ "metadata": {+ "id": "G5gE04UuPUWj"+ }},- "id": "i1jiXAdopRNH",- "outputId": "b681fc35-3b67-4585-ef7f-4d524a2e94c7"- },- "outputs": [{- "name": "stdout",- "output_type": "stream",- "text": [- "9th August, 2024\n",- "\n",- "# CRAB: Cross-environment Agent Benchmark for Multimodal Language Model Agents\n",- "\n",- "> Abstract: Recently, spearheaded by the CAMEL-AI community, a pioneer in open-source multi-agent projects, researchers from institutions such as King Abdullah University of Science and Technology, Oxford University, University of Tokyo, Carnegie Mellon University, Stanford University, and Tsinghua University have developed a cross-platform multimodal agent benchmark framework: CRAB, innovatively enabling agents to operate multiple devices simultaneously.\n",- "\n",- "### Introduction\n",- "\n",- "With the rapid development of multimodal large language models (MLLM), many agents capable of operating graphical user interfaces (GUIs) have emerged this year. Various companies have launched their innovative solutions, creating intense competition. GUI agents, leveraging powerful visual understanding and reasoning abilities of large models, can now efficiently and flexibly complete tasks such as booking appointments, shopping, and controlling smart homes.\n",- "\n",- "**This raises the question: will future agents truly be able to sit in front of a computer and work on my behalf?**\n",- "\n",- "However, in today's era of the Internet of Everything, most work requires the coordination of multiple devices. For example, taking a photo with a phone and then transferring it to a computer for editing involves crossing two different devices (environments). Currently, these GUI agents can only operate on a single device, making what is an easy task for humans exceedingly difficult for today's agents.\n",- "\n",- "Researchers from the CAMEL-AI community noticed this problem and proposed the first cross-environment, multi-device agent benchmark frameworkโCRAB, the **CR** oss-environment **A** gent **B** enchmark.\n",- "\n",- "\n",- "\n",- "Paper link: [https://arxiv.org/abs/2407.01511](https://arxiv.org/abs/2407.01511)\n",- "\n",- "The CAMEL framework ( [https://github.com/camel-ai](https://github.com/camel-ai)) developed by the CAMEL-AI community is one of the earliest open-source multi-agent projects based on large language models. Therefore, community members are researchers and engineers with rich research and practical experience in the field of agents.\n",- "\n",- "In CRAB, the authors not only designed a network-based multi-environment architecture that enables agents to operate multiple devices simultaneously to complete tasks, but also proposed two new technologies to address the issues existing in current agent benchmarks: the graph evaluator and task synthesis. CRAB is not only a brand new benchmark tool but also provides an interaction protocol and its implementation between the environment and agents, which is expected to become an important foundation for agents in practical fields.\n",- "\n",- "The authors believe that CRAB will become one of the standards for evaluating GUI agents in the future, and thus have put considerable effort into improving the framework's usability. The entire codebase adopts a modular design, with the configuration of each environment abstracted into independent and reusable components. Users can easily and quickly build multiple custom environments like building blocks and create their own benchmarks based on them.\n",- "\n",- "For users who wish to evaluate their agents' performance using CRAB, the authors thoughtfully provide a hard disk image on the Google Cloud Platform. With just one click, all the tedious configurations of virtual machines, deep learning models, Python packages, etc., will be completed automatically, allowing users to immediately engage in important experiments.\n",- "\n",- "Currently, CRAB's paper has been published on Arxiv, and the related code and data are open-sourced on the CAMEL-AI community's GitHub.\n",- "\n",- "GitHub repository: [https://github.com/camel-ai/crab](https://github.com/camel-ai/crab)\n",- "\n",- "What does CRAB look like in operation? Let's take a look at the video below:\n",- "\n",- "โ\n",- "\n",- "\n",- "\n",- "The process of testing a multi-agent system on CRAB.\n",- "\n",- "First, the system extracts tasks from the dataset, passes the task instructions to the main agent, and initializes the corresponding graph evaluator in CRAB.\n",- "\n",- "The workflow is a loop: the main agent observes, plans, and instructs the sub-agents; each sub-agent corresponds to an environment. In the diagram, two sub-agents are responsible for the Ubuntu system computer and the Android system phone, respectively, and the sub-agents perform operations in their respective platforms.\n",- "\n",- "The graph evaluator monitors the state of each environment in the platform, updates the progress of the agent in completing the task after each operation, and outputs evaluation metrics.\n",- "\n",- "Having understood how CRAB works, it's time to see how current models perform on this new benchmark. The authors introduced CRAB-Benchmark-v0, a dataset supporting two environments with a total of 100 tasks, and tested several state-of-the-art models.\n",- "\n",- "\n",- "\n",- "As shown, the best-performing GPT-4o scored only 35.26 (CR refers to completion rate).\n",- "\n",- "Cross-platform tasks are much more complex than single-platform tasks, and achieving the top score already demonstrates the outstanding ability of the GPT-4 series models in solving practical problems. However, we believe that emerging new methods and models can achieve better scores on CRAB, truly becoming efficient tools for solving real-world problems.\n",- "\n",- "### Cross-Platform Multimodal Agent Evaluation\n",- "\n",- "CRAB provides a comprehensive interactive agent evaluation framework. Through CRAB's foundational setup, agents can operate on various devices and platforms simultaneously, efficiently completing tasks in multiple isolated systems.\n",- "\n",- "The authors propose a new evaluation method called the graph evaluator, which differs from traditional methods based on final goals or action trajectories. The graph evaluator checks the intermediate states of task completion by breaking down tasks into multiple sub-goals.\n",- "\n",- "Each sub-goal is assigned an evaluation function to verify its completion, with each sub-goal being treated as a node in the graph evaluator.\n",- "\n",- "The graph structure describes the precedence and parallel relationships between sub-goals, thus providing fine-grained evaluation metrics; at the same time, the independent evaluation function for each sub-goal inherently adapts to multiple platforms.\n",- "\n",- "\n",- "\n",- "The table above compares CRAB with existing frameworks, including several key capabilities involved in testing:\n",- "\n",- "- **Interactive Environment:** Indicates whether an interactive platform or static dataset is used.\n",- "- **Multimodal Observation:** Indicates whether multimodal input (e.g., screenshots) is supported.\n",- "- **Cross-platform:** Indicates whether multiple operating systems or platforms are supported simultaneously.\n",- "- **Evaluation:** Describes evaluation metrics, divided into goal-based (only checking if the final goal is completed), trajectory-based (comparing the agent's action trajectory with a predefined standard action sequence), multiple (varies by task), or graph-based (each node as an intermediate checkpoint in a DAG).\n",- "- **Task Construction:** Shows the method of constructing tasks in the test dataset, including manually created, LLM-inspired (e.g., LLM generates task drafts but is verified and annotated by humans), template (multiple tasks generated based on manually written templates), or sub-task composition (composing multiple sub-tasks to construct task descriptions and evaluators).\n",- "\n",- "Based on the CRAB framework, the authors developed a benchmark dataset, CRAB Benchmark v0, supporting Android and Ubuntu environments.\n",- "\n",- "The benchmark includes 100 real-world tasks, covering various levels of difficulty for cross-platform and single-platform tasks. Tasks involve a variety of common issues and use multiple practical applications and tools, including but not limited to calendars, emails, maps, web browsers, and terminals, also replicating common coordination methods between smartphones and computers.\n",- "\n",- "\n",- "\n",- "### Problem Definition\n",- "\n",- "Assume an agent autonomously executes tasks on a device (such as a desktop). The device is usually equipped with input devices (like a mouse and keyboard) and output devices (like a screen) for human-computer interaction. The authors refer to a device or application with a fixed input method and output method as an environment.\n",- "\n",- "Formally, a single environment can be defined as a reward-free partially observable Markov decision process (Reward-free POMDP), represented by a tuple M := (S, A, T, O), where S represents the state space, A represents the action space, T: S ร A โ S is the transition function, and O is the observation space.\n",- "\n",- "Considering the collaborative nature of multiple devices in real-world scenarios, multiple platforms can be combined into a set M = {M1, M2, ..., Mn}, where n is the number of platforms, and each platform can be represented as Mj = (Sj, Aj, Tj, Oj).\n",- "\n",- "A task requiring operation across multiple platforms can be formalized as a tuple (M, I, R), where M is the platform set, I is the task goal described in natural language, and R is the task reward function.\n",- "\n",- "The authors call the algorithm responsible for completing the task the agent system. Each agent in the agent system uses a fixed backend model and predefined system prompt, retaining its dialogue history. The agent system can be a single agent or a multi-agent system with multiple agents cooperating.\n",- "\n",- "### Graph of Decomposed Tasks\n",- "\n",- "\n",- "\n",- "Breaking down complex tasks into simpler sub-tasks is an effective method for prompting large language models. The authors introduced this concept into the benchmark field, breaking down complex tasks into sub-tasks with precedence and parallel relationships, known as the Graph of Decomposed Tasks (GDT) as shown above.\n",- "\n",- "GDT uses a graph-based task decomposition method: using a DAG structure to represent decomposed sub-tasks.\n",- "\n",- "In GDT, each node is a sub-task, formalized as a tuple (m, i, r), where m specifies the environment for executing the sub-task, i provides natural language instructions, and r represents the reward function. The reward function evaluates the state of environment m and outputs a boolean value to determine if the sub-task is completed. Edges in GDT represent the precedence relationships between sub-tasks.\n",- "\n",- "### Graph Evaluator\n",- "\n",- "To evaluate the capabilities of large language models as agents, most benchmarks rely solely on the final state of the platform after the agent's operations.\n",- "\n",- "Simply judging whether the final goal is successful or failed is obviously not fair; it's like in a math exam, even if you can't solve the big problem, you should get points for writing some solution steps.\n",- "\n",- "Another method is trajectory-based matching, comparing the agent's operations with a predefined standard operation sequence (Label) for each task.\n",- "\n",- "However, in real-world systems, tasks may have multiple valid execution paths. For example, copying a file can be done using a file manager or a command line. Specifying a unique correct path is unfair to agents that achieve the goal in different ways.\n",- "\n",- "Therefore, this paper adopts a graph evaluator synchronized with platform states, tracking the agent's progress through the current state of sub-task completion.\n",- "\n",- "In addition to the traditional success rate (SR), which marks a task as successful only when all sub-tasks are completed, the authors introduced three metrics to measure the agent's performance and efficiency:\n",- "\n",- "1. **Completion Rate (CR):** Measures the proportion of completed sub-task nodes, calculated as the number of completed nodes/total nodes. This metric intuitively reflects the agent's progress on the given task.\n",- "2. **Execution Efficiency (EE):** Calculated as CR/A, where A represents the number of actions performed, reflecting the agent's task execution efficiency.\n",- "3. **Cost Efficiency (CE):** Calculated as CR/T, where T is the total number of tokens used by the agent, evaluating the agent's efficiency in terms of cost.\n",- "\n",- "### Experiments\n",- "\n",- "To run in Crab Benchmark-v0, the backend model needs to support the following features:\n",- "\n",- "1. Support multimodal mixed input: The system provides both screenshots and text instructions as prompts.\n",- "2. Support multi-turn conversations: All tasks require the agent to perform multiple operations, so historical messages must be stored in context.\n",- "3. Generate structured output through Function Call or similar functions: Used to execute operations in the environment.\n",- "\n",- "The experiments selected four multimodal models that meet these criteria: GPT-4o, GPT-4 Turbo, Gemini 1.5 Pro, and Claude 3 Opus.\n",- "\n",- "To compare the performance differences between multi-agent and single-agent systems, the paper designed three different agent systems:\n",- "\n",- "1. **Single Agent:** A single agent handles the entire process from understanding the task, observing the environment, planning, to executing actions.\n",- "2. **Multi-agent by Functionality:** Consists of a main agent and a sub-agent. The main agent observes the environment and provides instructions to the sub-agent, which translates the instructions into specific operations.\n",- "3. **Multi-agent by Environment:** Consists of a main agent and multiple sub-agents. Each sub-agent is responsible for one environment. The main agent understands the task, plans the execution process, and provides instructions to each sub-agent. The sub-agents observe their respective environments and translate the instructions into specific operations.\n",- "\n",- "The combinations of different agent systems and backend models provide multiple dimensions for comparison. Additionally, the paper compares the performance of models in tasks involving different platforms:\n",- "\n",- "**Ubuntu single-platform tasks:**\n",- "\n",- "\n",- "\n",- "**Android single-platform tasks:**\n",- "\n",- "\n",- "\n",- "**Cross-platform tasks:**\n",- "\n",- "\n",- "\n",- "Through data analysis, the paper draws several conclusions:\n",- "\n",- "**Performance Differences Among Models:**\n",- "\n",- "1. GPT-4o has the highest success and completion rates overall.\n",- "2. GPT-4 TURBO performs better in cost efficiency (CE) than other models.\n",- "3. Gemini 1.5 Pro and Claude 3 Opus struggle with task completion, finding it almost impossible to complete tasks. **โ**\n",- "\n",- "**Efficiency Metrics Reflect Different Characteristics of Models:**\n",- "\n",- "1. GPT-4 TURBO shows excellent cost efficiency in the single-agent mode, demonstrating cost-effective performance.\n",- "2. GPT-4o maintains a balance between efficiency and performance, especially in the single-agent mode.\n",- "3. Gemini 1.5 Pro shows low efficiency and incomplete cost efficiency metrics, mainly due to its low completion rate.\n",- "\n",- "**Evaluation of Termination Reasons Indicates Areas for Improvement:**\n",- "\n",- "1. All models have a high percentage of reaching the step limit (RSL), indicating that agents often run out of steps without achieving the final goal.\n",- "2. Gemini 1.5 Pro has a high rate of invalid actions (IA), highlighting its inability to stably generate the correct format for interacting with the environment.\n",- "3. The false completion (FC) rate in multi-agent systems is higher than in single-agent systems, indicating that message loss during communication between multiple agents can easily cause the executing sub-agent to misjudge.\n",- "\n",- "### ๐ซ Thanks from everyone at CAMEL-AI\n",- "\n",- "Hello there, passionate AI enthusiasts! ๐ We are ๐ซ CAMEL-AI.org, a global coalition of students, researchers, and engineers dedicated to advancing the frontier of AI and fostering a harmonious relationship between agents and humans.\n",- "\n",- "**๐ Our Mission:** To harness the potential of AI agents in crafting a brighter and more inclusive future for all. Every contribution we receive helps push the boundaries of whatโs possible in the AI realm.\n",- "\n",- "**๐ Join Us:** If you believe in a world where AI and humanity coexist and thrive, then youโre in the right place. Your support can make a significant difference. Letโs build the AI society of tomorrow, together!\n",- "\n",- "- Find all our updates on [X](https://twitter.com/CamelAIOrg).\n",- "- Make sure to star our [GitHub](https://github.com/camel-ai) repositories.\n",- "- Join our [Discord,](https://discord.gg/nCpraan3sS) [WeChat](https://ghli.org/camel/wechat.png) or [Slack](https://join.slack.com/t/camel-ai/shared_invite/zt-2icssxnkj-YHwFVhoZHMYpIG~ZU86WVw) community.\n",- "- You can contact us by email: [email protected]\n",- "- Dive deeper and explore our projects on [https://www.camel-ai.org/](https://www.camel-ai.org/)\n",- "\n",- "> โ\n",- "\n",- "Get started\n",- "\n",- "## Build your multi-agent system today\n",- "\n",- "Get started by joining our community\n",- "\n",- "[Join Discord](https://discord.gg/rBnhgxy6Fg)\n",- "\n",- "\n",- "\n",- "Finding the scaling law of agents\n",- "\n",- "\n",- "\n",- "RESEARCH\n",- "\n",- "[Agent Trust](https://agent-trust.camel-ai.org/) [CRAB](https://github.com/camel-ai/crab?tab=readme-ov-file)\n",- "\n",- "RESOURCES\n",- "\n",- "[Blog](/blog) [Docs](https://docs.camel-ai.org/) [Features & Integrations](/integration) [Team](/about)\n",- "\n",- "SOCIALS\n",- "\n",- "[Discord](https://discord.gg/3rWmpWegBK) [Github](https://github.com/camel-ai/camel) [LinkedIn](https://www.linkedin.com/company/camel-ai-org/) [Twitter](https://x.com/CamelAIOrg) [YouTube](https://www.youtube.com/@CamelAI)\n",- "\n",- "Copyright ยฉ 2024 Eigent AI - All Rights Reserved.\n",- "\n",- "```javascript\n",- "pip install camel-ai[all]==0.1.6.4\n",- "\n",- "```\n"- ]- }- ],- "source": [- "from camel.loaders import Firecrawl\n",- "\n",- "firecrawl = Firecrawl()\n",- "\n",- "# Scrape and clean content from a specified URL\n",- "response = firecrawl.scrape(\n",- " url=\"https://www.camel-ai.org/post/crab\"\n",- ")\n",- "\n",- "print(response[\"markdown\"])"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "q5NJlRL1N5vu"- },- "source": [- "**๐ Firecrawl makes obtaining clean, LLM-friendly content from URL effortless!**"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "NEUciNquON9_"- },- "source": [- "## ๐ ๏ธ Web Information Retrieval using CAMEL's RAG and Firecrawl"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "6f64VOMMP93d"- },- "source": [- "*In this section, we'll demonstrate how to retrieve relevant information from a list of URLs using CAMEL's RAG model. This is particularly useful for aggregating and analyzing data from multiple sources.*"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "46Irp_SurLaV"- },- "source": [- "### Setting Up Firecrawl with CAMEL's RAG"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "QVB-Xra8QIU1"- },- "source": [- "The following function retrieves relevant information from a list of URLs based on a given query. It combines web scraping with Firecrawl and CAMEL's AutoRetriever for a seamless information retrieval process."- ]- },- {- "cell_type": "code",- "execution_count": 8,- "metadata": {- "id": "gE_qBFCVveBR"- },- "outputs": [],- "source": [- "from camel.retrievers import AutoRetriever\n",- "from camel.toolkits import OpenAIFunction, SearchToolkit\n",- "from camel.types import ModelPlatformType, ModelType, StorageType\n",- "from camel.embeddings import MistralEmbedding"- ]- },- {- "cell_type": "code",- "execution_count": 14,- "metadata": {- "id": "A75lxSmLsLSr"- },- "outputs": [],- "source": [- "def retrieve_information_from_urls(urls: list[str], query: str) -> str:\n",- " r\"\"\"Retrieves relevant information from a list of URLs based on a given\n",- " query.\n",- "\n",- " This function uses the `Firecrawl` tool to scrape content from the\n",- " provided URLs and then uses the `AutoRetriever` from CAMEL to retrieve the\n",- " most relevant information based on the query from the scraped content.\n",- "\n",- " Args:\n",- " urls (list[str]): A list of URLs to scrape content from.\n",- " query (str): The query string to search for relevant information.\n",- "\n",- " Returns:\n",- " str: The most relevant information retrieved based on the query.\n",- "\n",- " Example:\n",- " >>> urls = [\"https://example.com/article1\", \"https://example.com/\n",- " article2\"]\n",- " >>> query = \"latest advancements in AI\"\n",- " >>> result = retrieve_information_from_urls(urls, query)\n",- " \"\"\"\n",- " aggregated_content = ''\n",- "\n",- " # Scrape and aggregate content from each URL\n",- " for url in urls:\n",- " scraped_content = Firecrawl().scrape(url)\n",- " aggregated_content += scraped_content[\"markdown\"]\n",- "\n",- " # Set up a vector retriever with local storage and embedding model from Mistral AI\n",- " auto_retriever = AutoRetriever(\n",- " vector_storage_local_path=\"local_data\",\n",- " storage_type=StorageType.QDRANT,\n",- " embedding_model=MistralEmbedding(),\n",- " )\n",- "\n",- " # Retrieve the most relevant information based on the query\n",- " # You can adjust the top_k and similarity_threshold value based on your needs\n",- " retrieved_info = auto_retriever.run_vector_retriever(\n",- " query=query,\n",- " contents=aggregated_content,\n",- " top_k=3,\n",- " similarity_threshold=0.5,\n",- " )\n",- "\n",- " return retrieved_info"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "nLh5nU7uUeo-"- },- "source": [- "Let's put the retrieval function to the test by gathering some information about the 2024 Olympics.\n",- "The first run may take about 50 seconds as it needs to build a local vector database."- ]- },- {- "cell_type": "code",- "execution_count": 15,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"+ "cell_type": "markdown",+ "source": [+ "โญ **Star the Repo**\n",+ "\n",+ "If you find CAMEL useful or interesting, please consider giving it a star on our [CAMEL GitHub Repo](https://github.com/camel-ai/camel)! Your stars help others find this project and motivate us to continue improving it."+ ],+ "metadata": {+ "id": "soIw38pJLv2f"+ }},- "id": "z4z00v9yWvFw",- "outputId": "e3084622-75fd-40ae-cf1c-56a26b011722"- },- "outputs": [{- "name": "stdout",- "output_type": "stream",- "text": [- "{'Original Query': 'Which country won the most golden prize in 2024 Olympics?', 'Retrieved Context': [' most medals since 1992](https://olympics.com/en/olympic-games/barcelona-1992/medals), when the โUnified Team,โ\\xa0athletes from the former Soviet Union republics, won 112 medals, including 45 golds. The Americans made 108 podium visits in Barcelona, with 37 of them on the top step.\\n\\nGold medalist Si', ' Olympic medals โ collected seven here.\\n\\nEcuador won five medals,more than doubling its overall summer total.\\n\\nKyrgyzstan made six podium trips, which is impressive given the central Asian nation came to Paris with only seven Olympic medals in history.\\n\\nBefore Paris 2024, Moldova had won six in national history. The tiny former Soviet republicmade four podium tripsin Paris.\\n\\n_David K. Li reported from Paris and Sean Nevin from London._\\n\\n[.\\n\\nWhile there had been no gold medal ties in Summer Games history, there have been three draws in the Winter Olympics.\\n\\nThe most recent draw was between Norway and Germany, each [winning 14\\xa0golds in PyeongChang 2018](https://olympics.com/en/olympic-games/pyeongchang-2018/medals).\\n\\nThe U.S. still came out with the most overall medals, taking home 126 from Paris this year.\\n\\nThe U.S. hasnโt failed to win [the']}\n"- ]- }- ],- "source": [- "retrieved_info = retrieve_information_from_urls(\n",- " query=\"Which country won the most golden prize in 2024 Olympics?\",\n",- " urls=[\n",- " \"https://www.nbcnews.com/sports/olympics/united-states-china-gold-medals-rcna166013\",\n",- " ],\n",- ")\n",- "\n",- "print(retrieved_info)"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "r8QpOBNLX-R_"- },- "source": [- "**๐ Thanks to CAMEL's RAG pipeline and Firecrawl's tidy scraping capabilities, this function effectively retrieves relevant information from the specified URLs! You can now integrate this function into CAMEL's Agents to automate the retrieval process further.**"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "b7jyteu-2SFc"- },- "source": [- "## ๐น Monitoring AI Agents with AgentOps"- ]- },- {- "cell_type": "code",- "execution_count": 16,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"+ "cell_type": "markdown",+ "source": [+ ""+ ],+ "metadata": {+ "id": "vq-HTbJyN4wn"+ }},- "id": "mHSfqXyhIK0N",- "outputId": "5b4c5f72-6c72-4a3a-ed27-1b0c0cab6389"- },- "outputs": [{- "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"- ]+ "cell_type": "markdown",+ "source": [+ "## ๐ฆ Installation"+ ],+ "metadata": {+ "id": "0J0_iW-YVcq2"+ }},{- "data": {- "text/plain": [- "<agentops.session.Session at 0x7c82f2b71ae0>"+ "cell_type": "markdown",+ "source": [+ "First, install the CAMEL package with all its dependencies:"+ ],+ "metadata": {+ "id": "7p-JjpyNVcCT"+ }+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {+ "collapsed": true,+ "id": "0GXs2pruU9Vl"+ },+ "outputs": [],+ "source": [+ "!pip install \"camel-ai[all]==0.2.4\""]- },- "execution_count": 16,- "metadata": {},- "output_type": "execute_result"- }- ],- "source": [- "import agentops\n",- "agentops.init(default_tags=[\"CAMEL cookbook\"])"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "n1Q8IKWUrAkr"- },- "source": [- "## ๐ง Knowledge Graph Construction"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "dD7p_9CkyUmK"- },- "source": [- "*A powerful feature of CAMEL is its ability to build and store knowledge graphs from text data. This allows for advanced analysis and visualization of relationships within the data.*"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "k_fZhcgnrUX1"- },- "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": 27,- "metadata": {- "id": "raMV4BwhrhNK"- },- "outputs": [],- "source": [- "from camel.storages import Neo4jGraph\n",- "from camel.loaders import UnstructuredIO\n",- "from camel.agents import KnowledgeGraphAgent\n",- "\n",- "def knowledge_graph_builder(text_input: str) -> None:\n",- " r\"\"\"Build and store a knowledge graph from the provided text.\n",- "\n",- " This function processes the input text to create and extract nodes and relationships,\n",- " which are then added to a Neo4j database as a knowledge graph.\n",- "\n",- " Args:\n",- " text_input (str): The input text from which the knowledge graph is to be constructed.\n",- "\n",- " Returns:\n",- " graph_elements: The generated graph element from knowlegde graph agent.\n",- " \"\"\"\n",- "\n",- " # Set Neo4j instance\n",- " n4j = Neo4jGraph(\n",- " url=\"Your_URL\",\n",- " username=\"Your_Username\",\n",- " password=\"Your_Password\",\n",- " )\n",- "\n",- " # Initialize instances\n",- " uio = UnstructuredIO()\n",- " kg_agent = KnowledgeGraphAgent(model=mistral_large_2)\n",- "\n",- " # Create an element from the provided text\n",- " element_example = uio.create_element_from_text(text=text_input, element_id=\"001\")\n",- "\n",- " # Extract nodes and relationships using the Knowledge Graph Agent\n",- " graph_elements = kg_agent.run(element_example, parse_graph_elements=True)\n",- "\n",- " # Add the extracted graph elements to the Neo4j database\n",- " n4j.add_graph_elements(graph_elements=[graph_elements])\n",- "\n",- " return graph_elements\n"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "uiDkPPrBshW4"- },- "source": [- "## ๐ค๐ค Multi-Agent Role-Playing with CAMEL"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "6MZVoQI7OltM"- },- "source": [- "*This section sets up a role-playing session where AI agents interact to accomplish a task using various tools. We will guide the assistant agent to perform a comprehensive study of the Turkish shooter in the 2024 Paris Olympics.*"- ]- },- {- "cell_type": "code",- "execution_count": 28,- "metadata": {- "id": "JTWQ4i6tt6mh"- },- "outputs": [],- "source": [- "from typing import List\n",- "\n",- "from colorama import Fore\n",- "\n",- "from camel.agents.chat_agent import FunctionCallingRecord\n",- "from camel.societies import RolePlaying\n",- "from camel.utils import print_text_animated"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "ggqh3_t9tURm"- },- "source": [- "Defining the Task Prompt"- ]- },- {- "cell_type": "code",- "execution_count": 29,- "metadata": {- "id": "rtwuPLI_ssrX"- },- "outputs": [],- "source": [- "task_prompt = \"\"\"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",- "to get the retrieved content back by providing the list of URLs, finially\n",- "use tool to build the knowledge graph to finish the task.\n",- "No more other actions needed\"\"\""- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "KI0k6XJZtaN5"- },- "source": [- "We will configure the assistant agent with tools for mathematical calculations, web information retrieval, and knowledge graph building."- ]- },- {- "cell_type": "code",- "execution_count": 30,- "metadata": {- "id": "Bw3_LyXiteVT"- },- "outputs": [],- "source": [- "retrieval_tool = OpenAIFunction(retrieve_information_from_urls)\n",- "search_tool = OpenAIFunction(SearchToolkit().search_duckduckgo)\n",- "knowledge_graph_tool = OpenAIFunction(knowledge_graph_builder)\n",- "\n",- "tool_list = [\n",- " retrieval_tool,\n",- " search_tool,\n",- " knowledge_graph_tool,\n",- "]\n",- "\n",- "assistant_model_config = MistralConfig(\n",- " tools=tool_list,\n",- " temperature=0.0,\n",- ")"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "Yc80X_ZItyvi"- },- "source": [- "Setting Up the Role-Playing Session"- ]- },- {- "cell_type": "code",- "execution_count": 31,- "metadata": {- "id": "insV1gSyt0b3"- },- "outputs": [],- "source": [- "# Initialize the role-playing session\n",- "role_play_session = RolePlaying(\n",- " assistant_role_name=\"CAMEL Assistant\",\n",- " user_role_name=\"CAMEL User\",\n",- " assistant_agent_kwargs=dict(\n",- " model=ModelFactory.create(\n",- " model_platform=ModelPlatformType.MISTRAL,\n",- " model_type=ModelType.MISTRAL_LARGE,\n",- " model_config_dict=assistant_model_config.as_dict(),\n",- " ),\n",- " tools=tool_list,\n",- " ),\n",- " user_agent_kwargs=dict(model=mistral_large_2),\n",- " task_prompt=task_prompt,\n",- " with_task_specify=False,\n",- ")"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "o7vfyJMdt8R1"- },- "source": [- "Print the system message and task prompt"- ]- },- {- "cell_type": "code",- "execution_count": 32,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"},- "id": "9xMDZxBmt-Ms",- "outputId": "265740fc-b3b8-4a00-9583-f5d877bd3693"- },- "outputs": [{- "name": "stdout",- "output_type": "stream",- "text": [- "\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",- "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",- "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",- "to get the retrieved content back by providing the list of URLs, finially\n",- "use tool to build the knowledge graph to finish the task.\n",- "No more other actions needed\n",- "\n",- "\u001B[36mSpecified task prompt:\n",- "None\n",- "\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",- "to get the retrieved content back by providing the list of URLs, finially\n",- "use tool to build the knowledge graph to finish the task.\n",- "No more other actions needed\n",- "\n"- ]- }- ],- "source": [- "# Print system and task messages\n",- "print(\n",- " Fore.GREEN\n",- " + f\"AI Assistant sys message:\\n{role_play_session.assistant_sys_msg}\\n\"\n",- ")\n",- "print(Fore.BLUE + f\"AI User sys message:\\n{role_play_session.user_sys_msg}\\n\")\n",- "\n",- "print(Fore.YELLOW + f\"Original task prompt:\\n{task_prompt}\\n\")\n",- "print(\n",- " Fore.CYAN\n",- " + \"Specified task prompt:\"\n",- " + f\"\\n{role_play_session.specified_task_prompt}\\n\"\n",- ")\n",- "print(Fore.RED + f\"Final task prompt:\\n{role_play_session.task_prompt}\\n\")"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "1ibe4da9uB2H"- },- "source": [- "Set the termination rule and start the interaction between agents\n",- "\n",- "**NOTE**: This session will take approximately 8 minutes and will consume around 60k tokens by using Mistral Large 2 Model."- ]- },- {- "cell_type": "code",- "execution_count": 33,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"+ "cell_type": "markdown",+ "source": [+ "## ๐ Setting Up API Keys"+ ],+ "metadata": {+ "id": "lfNvFbhD6o8B"+ }},- "id": "xOhdpjxuuH-2",- "outputId": "3d8018da-3c23-46c2-c12e-d5360a6fd95c"- },- "outputs": [{- "name": "stdout",- "output_type": "stream",- "text": [- "\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",- "\n",- "Function Execution: search_duckduckgo\n",- "\tArgs: {'query': 'Turkish shooter in the 2024 Paris Olympics'}\n",- "\tResult: [{'result_id': 1, 'title': 'Meet Yusuf Dikec: The Turkish shooter who has gone viral at Paris 2024 ...', 'description': \"Yusuf Dikec, experienced Olympian and Turkish record breaker. Paris is far from Dikec's first rodeo. The Turkish shooter made his Olympic debut at Beijing 2008 aged 35, and returned four years later at London 2012.It was there where he recorded his previous best result of 13 th in the men's 50m free pistol event.. Dikec then competed at Rio 2016 and Tokyo 2020 held in 2021, though always shy ...\", 'url': 'https://olympics.com/en/news/yusuf-dikec-turkish-shooting-viral-paris-2024-olympics'}, {'result_id': 2, 'title': 'Turkish sharpshooter Yusuf Dikeรง wins silver at Paris Olympics with ...', 'description': \"Turkish sharpshooter Yusuf Dikeรง didn't need special lenses or big ear protectors to win the silver medal in the air pistol team event at the 2024 Paris Olympics.\", 'url': 'https://www.nbcnews.com/news/sports/sharpshooter-yusuf-dikec-silver-olympics-minimal-gear-internet-sensati-rcna164685'}, {'result_id': 3, 'title': 'Who is Yusuf Dikec, Turkish shooter who went viral at 2024 Olympics ...', 'description': 'CHATEAUROUX, France (AP) โ Turkish pistol shooter Yusuf Dikec has gone viral on social media for his seemingly casual attitude while shooting his way to a silver medal at the 2024 Olympics. The most-shared images show Dikec shooting in a T-shirt with one hand in his pocket, a seemingly standard pair of glasses and an impassive look on his face.', 'url': 'https://apnews.com/article/olympics-2024-yusuf-dikec-turkish-shooter-a7890124304080a48e7ee4294004d306'}, {'result_id': 4, 'title': \"WATCH: Turkey's sharpshooter wins silver without high-tech aids - NBC News\", 'description': 'Turkish Olympian Yusuf Dikec won silver in the 2024 Paris Olympics mixed air pistol team event. Dikec went viral for his nonchalant approach of not using any high-tech aids in the competition.', 'url': 'https://www.nbcnews.com/video/watch-turkey-s-sharpshooter-wins-silver-without-high-tech-aids-216173637766'}, {'result_id': 5, 'title': \"Yusuf Dikeรง: Turkey's viral Olympian inspires new celebration with ...\", 'description': \"Turkey's Yusuf Dikec competes in the shooting 10m air pistol mixed team gold medal match during the Paris 2024 Olympic Games at Chateauroux Shooting Centre on July 30, 2024. (Photo by Alain JOCARD ...\", 'url': 'https://www.cnn.com/2024/08/09/sport/yusuf-dikec-olympic-celebration-craze-spt-intl/index.html'}]\n",- "\n",- "Solution: I have used the search tool to find related URLs about the Turkish shooter in the 2024 Paris Olympics. Here are the results:\n",- "\n",- "1. **Title:** Meet Yusuf Dikec: The Turkish shooter who has gone viral at Paris 2024 ...\n",- " **Description:** Yusuf Dikec, experienced Olympian and Turkish record breaker. Paris is far from Dikec's first rodeo. The Turkish shooter made his Olympic debut at Beijing 2008 aged 35, and returned four years later at London 2012. It was there where he recorded his previous best result of 13th in the men's 50m free pistol event. Dikec then competed at Rio 2016 and Tokyo 2020 held in 2021, though always shy ...\n",- " **URL:** [https://olympics.com/en/news/yusuf-dikec-turkish-shooting-viral-paris-2024-olympics](https://olympics.com/en/news/yusuf-dikec-turkish-shooting-viral-paris-2024-olympics)\n",- "\n",- "2. **Title:** Turkish sharpshooter Yusuf Dikeรง wins silver at Paris Olympics with ...\n",- " **Description:** Turkish sharpshooter Yusuf Dikeรง didn't need special lenses or big ear protectors to win the silver medal in the air pistol team event at the 2024 Paris Olympics.\n",- " **URL:** [https://www.nbcnews.com/news/sports/sharpshooter-yusuf-dikec-silver-olympics-minimal-gear-internet-sensati-rcna164685](https://www.nbcnews.com/news/sports/sharpshooter-yusuf-dikec-silver-olympics-minimal-gear-internet-sensati-rcna164685)\n",- "\n",- "3. **Title:** Who is Yusuf Dikec, Turkish shooter who went viral at 2024 Olympics ...\n",- " **Description:** CHATEAUROUX, France (AP) โ Turkish pistol shooter Yusuf Dikec has gone viral on social media for his seemingly casual attitude while shooting his way to a silver medal at the 2024 Olympics. The most-shared images show Dikec shooting in a T-shirt with one hand in his pocket, a seemingly standard pair of glasses and an impassive look on his face.\n",- " **URL:** [https://apnews.com/article/olympics-2024-yusuf-dikec-turkish-shooter-a7890124304080a48e7ee4294004d306](https://apnews.com/article/olympics-2024-yusuf-dikec-turkish-shooter-a7890124304080a48e7ee4294004d306)\n",- "\n",- "4. **Title:** WATCH: Turkey's sharpshooter wins silver without high-tech aids - NBC News\n",- " **Description:** Turkish Olympian Yusuf Dikec won silver in the 2024 Paris Olympics mixed air pistol team event. Dikec went viral for his nonchalant approach of not using any high-tech aids in the competition.\n",- " **URL:** [https://www.nbcnews.com/video/watch-turkey-s-sharpshooter-wins-silver-without-high-tech-aids-216173637766](https://www.nbcnews.com/video/watch-turkey-s-sharpshooter-wins-silver-without-high-tech-aids-216173637766)\n",- "\n",- "5. **Title:** Yusuf Dikeรง: Turkey's viral Olympian inspires new celebration with ...\n",- " **Description:** Turkey's Yusuf Dikec competes in the shooting 10m air pistol mixed team gold medal match during the Paris 2024 Olympic Games at Chateauroux Shooting Centre on July 30, 2024. (Photo by Alain JOCARD ...\n",- " **URL:** [https://www.cnn.com/2024/08/09/sport/yusuf-dikec-olympic-celebration-craze-spt-intl/index.html](https://www.cnn.com/2024/08/09/sport/yusuf-dikec-olympic-celebration-craze-spt-intl/index.html)\n",- "\n",- "Next request.\n",- "\n",- "\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",- "\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",- "\tResult: {'Original Query': 'Turkish shooter in the 2024 Paris Olympics', 'Retrieved Context': [\"1/mobile/left.svg)\\n\\n\\n\\n\\n\\n## **Yusuf Dikec, experienced Olympian and Turkish record breaker**\\n\\nParis is far from Dikec's first rodeo. The Turkish shooter made his Olympic debut at [Beijing 2008](https://olympics.com/en/olympic-games/beijing-2008) aged 35, and returned four years later at [London 2012](https:\", \"to internet stardom.\\n\\nWithout the special lenses and ear protectors typical of the sport, and with one hand casually tucked into his pocket, Dikec effortlessly shot his way onto the podium. He and partner Sevval Ilayda Tarhan nabbed Turkeyโs first medal in Olympic shooting.\\n\\nTurkey's Yusuf Dikec competes in the shooting 10m air p\", \"ular pair of glasses. His partner, ลevval ฤฐlayda\\xa0Tarhan, also didn't wear any blinders and kept one hand tucked in her pocket. Their win was Turkeyโs first medal in an Olympic shooting event.\\n\\nSilver medalists ลevval ฤฐlayda Tarhan and Yusuf Dikeรง of Turkey on the podium during after the 10-meter air pistol mixed \"]}\n",- "\n",- "Solution: I have used the retrieval tool to get the content from the provided URLs. Here is the retrieved content:\n",- "\n",- "1. **URL:** [https://olympics.com/en/news/yusuf-dikec-turkish-shooting-viral-paris-2024-olympics](https://olympics.com/en/news/yusuf-dikec-turkish-shooting-viral-paris-2024-olympics)\n",- " **Content:**\n",- " ```\n",- " \n",- "\n",- " \n",- "\n",- " \n",- "\n",- " ## **Yusuf Dikec, experienced Olympian and Turkish record breaker**\n",- "\n",- " Paris is far from Dikec's first rodeo. The Turkish shooter made his Olympic debut at [Beijing 2008](https://olympics.com/en/olympic-games/beijing-2008) aged 35, and returned four years later at [London 2012](https:\n",- " ```\n",- "\n",- "2. **URL:** [https://www.nbcnews.com/news/sports/sharpshooter-yusuf-dikec-silver-olympics-minimal-gear-internet-sensati-rcna164685](https://www.nbcnews.com/news/sports/sharpshooter-yusuf-dikec-silver-olympics-minimal-gear-internet-sensati-rcna164685)\n",- " **Content:**\n",- " ```\n",- " Without the special lenses and ear protectors typical of the sport, and with one hand casually tucked into his pocket, Dikec effortlessly shot his way onto the podium. He and partner Sevval Ilayda Tarhan nabbed Turkeyโs first medal in Olympic shooting.\n",- "\n",- " \n",- " Turkey's Yusuf Dikec competes in the shooting 10m air pistol\n",- " ```\n",- "\n",- "3. **URL:** [https://apnews.com/article/olympics-2024-yusuf-dikec-turkish-shooter-a7890124304080a48e7ee4294004d306](https://apnews.com/article/olympics-2024-yusuf-dikec-turkish-shooter-a7890124304080a48e7ee4294004d306)\n",- " **Content:**\n",- " ```\n",- " With a regular pair of glasses. His partner, ลevval ฤฐlayda Tarhan, also didnโt wear any blinders and kept one hand tucked in her pocket. Their win was Turkeyโs first medal in an Olympic shooting event.\n",- "\n",- " \n",- " Silver medalists ลevval ฤฐlayda Tarhan and Yusuf Dikeรง of Turkey on the podium during after the 10-meter air pistol mixed\n",- " ```\n",- "\n",- "Next request.\n",- "\n",- "\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",- "\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",- "1. **Experienced Olympian:** Yusuf Dikec is an experienced Olympian who made his debut at the Beijing 2008 Olympics at the age of 35. He has also competed in the London 2012, Rio 2016, and Tokyo 2020 Olympics.\n",- "\n",- "2. **Silver Medal Win:** Dikec won a silver medal in the air pistol team event at the 2024 Paris Olympics. He competed with minimal gear, without special lenses or big ear protectors, and with one hand casually tucked into his pocket.\n",- "\n",- "3. **Viral Sensation:** Dikec's nonchalant approach and minimal gear during the competition went viral on the internet. His seemingly casual attitude while shooting his way to a silver medal caught the attention of many.\n",- "\n",- "4. **Partnership with Sevval Ilayda Tarhan:** Dikec competed alongside Sevval Ilayda Tarhan in the mixed air pistol team event. Together, they won Turkeyโs first medal in Olympic shooting.\n",- "\n",- "5. **Historic Achievement:** The win marked Turkeyโs first medal in an Olympic shooting event, highlighting the significance of Dikec and Tarhan's achievement.\n",- "\n",- "Next request.\n",- "\n",- "\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",- "\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",- "---\n",- "\n",- "### Comprehensive Report on Turkish Shooter Yusuf Dikec at the 2024 Paris Olympics\n",- "\n",- "#### Introduction\n",- "\n",- "Yusuf 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",- "\n",- "Yusuf 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",- "\n",- "At 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",- "\n",- "Dikec'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",- "\n",- "Dikec 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",- "\n",- "The 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",- "\n",- "Yusuf 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",- "\n",- "---\n",- "\n",- "Next request.\n",- "\n",- "\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",- "\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",- "\tResult: {'nodes': [{'id': 'Yusuf Dikec', 'type': 'Person', 'properties': {'source': 'agent_created'}}, {'id': 'Turkey', 'type': 'Country', 'properties': {'source': 'agent_created'}}, {'id': '2024 Paris Olympics', 'type': 'Event', 'properties': {'source': 'agent_created'}}, {'id': 'Silver Medal', 'type': 'Achievement', 'properties': {'source': 'agent_created'}}, {'id': 'Air Pistol Team Event', 'type': 'Event', 'properties': {'source': 'agent_created'}}, {'id': 'Sevval Ilayda Tarhan', 'type': 'Person', 'properties': {'source': 'agent_created'}}, {'id': 'Mixed Air Pistol Team Event', 'type': 'Event', 'properties': {'source': 'agent_created'}}, {'id': 'Beijing 2008 Olympics', 'type': 'Event', 'properties': {'source': 'agent_created'}}, {'id': 'London 2012 Olympics', 'type': 'Event', 'properties': {'source': 'agent_created'}}, {'id': 'Rio 2016 Olympics', 'type': 'Event', 'properties': {'source': 'agent_created'}}, {'id': 'Tokyo 2020 Olympics', 'type': 'Event', 'properties': {'source': 'agent_created'}}], 'relationships': [{'subj': {'id': 'Yusuf Dikec', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': 'Turkey', 'type': 'Country', 'properties': {'source': 'agent_created'}}, 'type': 'Represents', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Yusuf Dikec', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': '2024 Paris Olympics', 'type': 'Event', 'properties': {'source': 'agent_created'}}, 'type': 'ParticipatedIn', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Yusuf Dikec', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': 'Silver Medal', 'type': 'Achievement', 'properties': {'source': 'agent_created'}}, 'type': 'Won', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Yusuf Dikec', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': 'Air Pistol Team Event', 'type': 'Event', 'properties': {'source': 'agent_created'}}, 'type': 'CompetedIn', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Yusuf Dikec', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': 'Sevval Ilayda Tarhan', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'type': 'PartneredWith', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Yusuf Dikec', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': 'Mixed Air Pistol Team Event', 'type': 'Event', 'properties': {'source': 'agent_created'}}, 'type': 'CompetedIn', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Yusuf Dikec', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': 'Beijing 2008 Olympics', 'type': 'Event', 'properties': {'source': 'agent_created'}}, 'type': 'ParticipatedIn', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Yusuf Dikec', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': 'London 2012 Olympics', 'type': 'Event', 'properties': {'source': 'agent_created'}}, 'type': 'ParticipatedIn', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Yusuf Dikec', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': 'Rio 2016 Olympics', 'type': 'Event', 'properties': {'source': 'agent_created'}}, 'type': 'ParticipatedIn', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Yusuf Dikec', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': 'Tokyo 2020 Olympics', 'type': 'Event', 'properties': {'source': 'agent_created'}}, 'type': 'ParticipatedIn', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Sevval Ilayda Tarhan', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': 'Turkey', 'type': 'Country', 'properties': {'source': 'agent_created'}}, 'type': 'Represents', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Sevval Ilayda Tarhan', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': '2024 Paris Olympics', 'type': 'Event', 'properties': {'source': 'agent_created'}}, 'type': 'ParticipatedIn', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Sevval Ilayda Tarhan', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': 'Mixed Air Pistol Team Event', 'type': 'Event', 'properties': {'source': 'agent_created'}}, 'type': 'CompetedIn', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Turkey', 'type': 'Country', 'properties': {'source': 'agent_created'}}, 'obj': {'id': 'Silver Medal', 'type': 'Achievement', 'properties': {'source': 'agent_created'}}, 'type': 'Achieved', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Yusuf Dikec', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': 'Turkey', 'type': 'Country', 'properties': {'source': 'agent_created'}}, 'type': 'Represents', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Yusuf Dikec', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': '2024 Paris Olympics', 'type': 'Event', 'properties': {'source': 'agent_created'}}, 'type': 'ParticipatedIn', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Yusuf Dikec', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': 'Silver Medal', 'type': 'Achievement', 'properties': {'source': 'agent_created'}}, 'type': 'Won', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Yusuf Dikec', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': 'Air Pistol Team Event', 'type': 'Event', 'properties': {'source': 'agent_created'}}, 'type': 'CompetedIn', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Yusuf Dikec', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': 'Sevval Ilayda Tarhan', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'type': 'PartneredWith', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Yusuf Dikec', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': 'Mixed Air Pistol Team Event', 'type': 'Event', 'properties': {'source': 'agent_created'}}, 'type': 'CompetedIn', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Yusuf Dikec', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': 'Beijing 2008 Olympics', 'type': 'Event', 'properties': {'source': 'agent_created'}}, 'type': 'ParticipatedIn', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Yusuf Dikec', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': 'London 2012 Olympics', 'type': 'Event', 'properties': {'source': 'agent_created'}}, 'type': 'ParticipatedIn', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Yusuf Dikec', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': 'Rio 2016 Olympics', 'type': 'Event', 'properties': {'source': 'agent_created'}}, 'type': 'ParticipatedIn', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Yusuf Dikec', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': 'Tokyo 2020 Olympics', 'type': 'Event', 'properties': {'source': 'agent_created'}}, 'type': 'ParticipatedIn', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Sevval Ilayda Tarhan', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': 'Turkey', 'type': 'Country', 'properties': {'source': 'agent_created'}}, 'type': 'Represents', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Sevval Ilayda Tarhan', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': '2024 Paris Olympics', 'type': 'Event', 'properties': {'source': 'agent_created'}}, 'type': 'ParticipatedIn', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Sevval Ilayda Tarhan', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': 'Mixed Air Pistol Team Event', 'type': 'Event', 'properties': {'source': 'agent_created'}}, 'type': 'CompetedIn', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Turkey', 'type': 'Country', 'properties': {'source': 'agent_created'}}, 'obj': {'id': 'Silver Medal', 'type': 'Achievement', 'properties': {'source': 'agent_created'}}, 'type': 'Achieved', 'properties': {'source': 'agent_created'}}], 'source': <unstructured.documents.elements.Text object at 0x7c82e2847520>}\n",- "\n",- "Solution: I have used the tool to build a knowledge graph based on the comprehensive report about the Turkish shooter Yusuf Dikec at the 2024 Paris Olympics. Here is the knowledge graph:\n",- "\n",- "### Knowledge Graph\n",- "\n",- "#### Nodes\n",- "\n",- "1. **Yusuf Dikec** (Person)\n",- "2. **Turkey** (Country)\n",- "3. **2024 Paris Olympics** (Event)\n",- "4. **Silver Medal** (Achievement)\n",- "5. **Air Pistol Team Event** (Event)\n",- "6. **Sevval Ilayda Tarhan** (Person)\n",- "7. **Mixed Air Pistol Team Event** (Event)\n",- "8. **Beijing 2008 Olympics** (Event)\n",- "9. **London 2012 Olympics** (Event)\n",- "10. **Rio 2016 Olympics** (Event)\n",- "11. **Tokyo 2020 Olympics** (Event)\n",- "\n",- "#### Relationships\n",- "\n",- "1. **Yusuf Dikec** (Person) - **Represents** - **Turkey** (Country)\n",- "2. **Yusuf Dikec** (Person) - **ParticipatedIn** - **2024 Paris Olympics** (Event)\n",- "3. **Yusuf Dikec** (Person) - **Won** - **Silver Medal** (Achievement)\n",- "4. **Yusuf Dikec** (Person) - **CompetedIn** - **Air Pistol Team Event** (Event)\n",- "5. **Yusuf Dikec** (Person) - **PartneredWith** - **Sevval Ilayda Tarhan** (Person)\n",- "6. **Yusuf Dikec** (Person) - **CompetedIn** - **Mixed Air Pistol Team Event** (Event)\n",- "7. **Yusuf Dikec** (Person) - **ParticipatedIn** - **Beijing 2008 Olympics** (Event)\n",- "8. **Yusuf Dikec** (Person) - **ParticipatedIn** - **London 2012 Olympics** (Event)\n",- "9. **Yusuf Dikec** (Person) - **ParticipatedIn** - **Rio 2016 Olympics** (Event)\n",- "10. **Yusuf Dikec** (Person) - **ParticipatedIn** - **Tokyo 2020 Olympics** (Event)\n",- "11. **Sevval Ilayda Tarhan** (Person) - **Represents** - **Turkey** (Country)\n",- "12. **Sevval Ilayda Tarhan** (Person) - **ParticipatedIn** - **2024 Paris Olympics** (Event)\n",- "13. **Sevval Ilayda Tarhan** (Person) - **CompetedIn** - **Mixed Air Pistol Team Event** (Event)\n",- "14. **Turkey** (Country) - **Achieved** - **Silver Medal** (Achievement)\n",- "\n",- "This knowledge graph captures the key entities and their relationships as described in the comprehensive report about Yusuf Dikec at the 2024 Paris Olympics.\n",- "\n",- "Next request.\n",- "\n",- "\n",- "\u001B[34mAI User:\n",- "\n",- "<CAMEL_TASK_DONE>\n",- "\n",- "\n"- ]- }- ],- "source": [- "n = 0\n",- "input_msg = role_play_session.init_chat()\n",- "while n < 20: # Limit the chat to 20 turns\n",- " n += 1\n",- " assistant_response, user_response = role_play_session.step(input_msg)\n",- "\n",- " if assistant_response.terminated:\n",- " print(\n",- " Fore.GREEN\n",- " + (\n",- " \"AI Assistant terminated. Reason: \"\n",- " f\"{assistant_response.info['termination_reasons']}.\"\n",- " )\n",- " )\n",- " break\n",- " if user_response.terminated:\n",- " print(\n",- " Fore.GREEN\n",- " + (\n",- " \"AI User terminated. \"\n",- " f\"Reason: {user_response.info['termination_reasons']}.\"\n",- " )\n",- " )\n",- " break\n",- " # Print output from the user\n",- " print_text_animated(\n",- " Fore.BLUE + f\"AI User:\\n\\n{user_response.msg.content}\\n\",\n",- " 0.01\n",- " )\n",- "\n",- " if \"CAMEL_TASK_DONE\" in user_response.msg.content:\n",- " break\n",- "\n",- " # Print output from the assistant, including any function\n",- " # execution information\n",- " print_text_animated(Fore.GREEN + \"AI Assistant:\", 0.01)\n",- " tool_calls: List[FunctionCallingRecord] = [\n",- " FunctionCallingRecord(**call.as_dict())\n",- " for call in assistant_response.info['tool_calls']\n",- " ]\n",- " for func_record in tool_calls:\n",- " print_text_animated(f\"{func_record}\", 0.01)\n",- " print_text_animated(f\"{assistant_response.msg.content}\\n\", 0.01)\n",- "\n",- " input_msg = assistant_response.msg"- ]- },- {- "cell_type": "code",- "execution_count": 34,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"+ "cell_type": "markdown",+ "source": [+ "You'll need to set up your API keys for Mistral AI, Firecrawl and AgentOps. This ensures that the tools can interact with external services securely."+ ],+ "metadata": {+ "id": "jqV12oQfQTyl"+ }},- "id": "t7zTkjDBIf_i",- "outputId": "32f89a58-ca8f-46fc-b9aa-cd5d6f003ace"- },- "outputs": [{- "name": "stderr",- "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"- ]+ "cell_type": "markdown",+ "source": [+ "You can go to [here](https://app.agentops.ai/signin) to get **free** API Key from AgentOps\n"+ ],+ "metadata": {+ "id": "Sc3MAQwiH9Pd"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "import os\n",+ "from getpass import getpass\n",+ "\n",+ "# Prompt for the AgentOps API key securely\n",+ "agentops_api_key = getpass('Enter your API key: ')\n",+ "os.environ[\"AGENTOPS_API_KEY\"] = agentops_api_key"+ ],+ "metadata": {+ "id": "HQ_yOT5_Hyt4",+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "outputId": "8e82dbad-55f1-4adb-a06d-73570f356766"+ },+ "execution_count": 2,+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Enter your API key: ยทยทยทยทยทยทยทยทยทยท\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "Your can go to [here](https://console.mistral.ai/api-keys/) to get API Key from Mistral AI with **free** credits."+ ],+ "metadata": {+ "id": "czxWvnvnAimt"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "# Prompt for the API key securely\n",+ "mistral_api_key = getpass('Enter your API key: ')\n",+ "os.environ[\"MISTRAL_API_KEY\"] = mistral_api_key"+ ],+ "metadata": {+ "id": "T0FBl1WF6jFs",+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "outputId": "05502406-c889-46bd-a104-f0a1fe25f763"+ },+ "execution_count": 3,+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Enter your API key: ยทยทยทยทยทยทยทยทยทยท\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "Set up the Mistral Large 2 model using the CAMEL ModelFactory. You can also configure other models as needed."+ ],+ "metadata": {+ "id": "qdG7LbDgDNe7"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "from camel.models import ModelFactory\n",+ "from camel.types import ModelPlatformType, ModelType\n",+ "from camel.configs import MistralConfig\n",+ "\n",+ "# Set up model\n",+ "mistral_large_2 = ModelFactory.create(\n",+ " model_platform=ModelPlatformType.MISTRAL,\n",+ " model_type=ModelType.MISTRAL_LARGE,\n",+ " model_config_dict=MistralConfig(temperature=0.2).as_dict(),\n",+ ")"+ ],+ "metadata": {+ "id": "ojjHCTsUDK6s"+ },+ "execution_count": 4,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "Your can go to [here](https://www.firecrawl.dev/) to get API Key from Firecrawl with **free** credits."+ ],+ "metadata": {+ "id": "akkwlXcjTLcH"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "# Prompt for the Firecrawl API key securely\n",+ "firecrawl_api_key = getpass('Enter your API key: ')\n",+ "os.environ[\"FIRECRAWL_API_KEY\"] = firecrawl_api_key"+ ],+ "metadata": {+ "id": "0byeytnFWiaG",+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "outputId": "64433b9f-b9a3-4ef2-c680-d489442e05a5"+ },+ "execution_count": 5,+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Enter your API key: ยทยทยทยทยทยทยทยทยทยท\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "## ๐ Web Scraping with Firecrawl"+ ],+ "metadata": {+ "id": "kiyIq4I3pSE2"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "Firecrawl is a powerful tool that simplifies web scraping and cleaning content from web pages. In this section, we will scrape content from a specific post on the CAMEL AI website as an example."+ ],+ "metadata": {+ "id": "qgx3GS9LNaVe"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "from camel.loaders import Firecrawl\n",+ "\n",+ "firecrawl = Firecrawl()\n",+ "\n",+ "# Scrape and clean content from a specified URL\n",+ "response = firecrawl.scrape(\n",+ " url=\"https://www.camel-ai.org/post/crab\"\n",+ ")\n",+ "\n",+ "print(response[\"markdown\"])"+ ],+ "metadata": {+ "id": "i1jiXAdopRNH",+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "outputId": "7a6d8530-e45e-4037-b532-a0a26718aee9"+ },+ "execution_count": 6,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "Aug 9\n",+ "\n",+ "CRAB: Cross-environment Agent Benchmark for Multimodal Language Model Agents\n",+ "----------------------------------------------------------------------------\n",+ "\n",+ "Introducing CRAB: A Benchmark for Cross-Platform Multimodal Agentsใ\n",+ "===================================================================\n",+ "\n",+ "> Abstract: Recently, spearheaded by the CAMEL-AI community, a pioneer in open-source multi-agent projects, researchers from institutions such as King Abdullah University of Science and Technology, Oxford University, University of Tokyo, Carnegie Mellon University, Stanford University, and Tsinghua University have developed a cross-platform multimodal agent benchmark framework: CRAB, innovatively enabling agents to operate multiple devices simultaneously.\n",+ "\n",+ "### Introduction\n",+ "\n",+ "With the rapid development of multimodal large language models (MLLM), many agents capable of operating graphical user interfaces (GUIs) have emerged this year. Various companies have launched their innovative solutions, creating intense competition. GUI agents, leveraging powerful visual understanding and reasoning abilities of large models, can now efficiently and flexibly complete tasks such as booking appointments, shopping, and controlling smart homes.\n",+ "\n",+ "**This raises the question: will future agents truly be able to sit in front of a computer and work on my behalf?**\n",+ "\n",+ "However, in today's era of the Internet of Everything, most work requires the coordination of multiple devices. For example, taking a photo with a phone and then transferring it to a computer for editing involves crossing two different devices (environments). Currently, these GUI agents can only operate on a single device, making what is an easy task for humans exceedingly difficult for today's agents.\n",+ "\n",+ "Researchers from the CAMEL-AI community noticed this problem and proposed the first cross-environment, multi-device agent benchmark frameworkโCRAB, the **CR**oss-environment **A**gent **B**enchmark.\n",+ "\n",+ "\n",+ "\n",+ "Paper link: [https://arxiv.org/abs/2407.01511](https://arxiv.org/abs/2407.01511)\n",+ "\n",+ "The CAMEL framework ([https://github.com/camel-ai](https://github.com/camel-ai)\n",+ ") developed by the CAMEL-AI community is one of the earliest open-source multi-agent projects based on large language models. Therefore, community members are researchers and engineers with rich research and practical experience in the field of agents.\n",+ "\n",+ "In CRAB, the authors not only designed a network-based multi-environment architecture that enables agents to operate multiple devices simultaneously to complete tasks, but also proposed two new technologies to address the issues existing in current agent benchmarks: the graph evaluator and task synthesis. CRAB is not only a brand new benchmark tool but also provides an interaction protocol and its implementation between the environment and agents, which is expected to become an important foundation for agents in practical fields.\n",+ "\n",+ "The authors believe that CRAB will become one of the standards for evaluating GUI agents in the future, and thus have put considerable effort into improving the framework's usability. The entire codebase adopts a modular design, with the configuration of each environment abstracted into independent and reusable components. Users can easily and quickly build multiple custom environments like building blocks and create their own benchmarks based on them.\n",+ "\n",+ "For users who wish to evaluate their agents' performance using CRAB, the authors thoughtfully provide a hard disk image on the Google Cloud Platform. With just one click, all the tedious configurations of virtual machines, deep learning models, Python packages, etc., will be completed automatically, allowing users to immediately engage in important experiments.\n",+ "\n",+ "Currently, CRAB's paper has been published on Arxiv, and the related code and data are open-sourced on the CAMEL-AI community's GitHub.\n",+ "\n",+ "GitHub repository: [https://github.com/camel-ai/crab](https://github.com/camel-ai/crab)\n",+ "\n",+ "What does CRAB look like in operation? Let's take a look at the video below: \n",+ "\n",+ "โ\n",+ "\n",+ "\n",+ "\n",+ "The process of testing a multi-agent system on CRAB.\n",+ "\n",+ "First, the system extracts tasks from the dataset, passes the task instructions to the main agent, and initializes the corresponding graph evaluator in CRAB.\n",+ "\n",+ "The workflow is a loop: the main agent observes, plans, and instructs the sub-agents; each sub-agent corresponds to an environment. In the diagram, two sub-agents are responsible for the Ubuntu system computer and the Android system phone, respectively, and the sub-agents perform operations in their respective platforms.\n",+ "\n",+ "The graph evaluator monitors the state of each environment in the platform, updates the progress of the agent in completing the task after each operation, and outputs evaluation metrics.\n",+ "\n",+ "Having understood how CRAB works, it's time to see how current models perform on this new benchmark. The authors introduced CRAB-Benchmark-v0, a dataset supporting two environments with a total of 100 tasks, and tested several state-of-the-art models.\n",+ "\n",+ "\n",+ "\n",+ "As shown, the best-performing GPT-4o scored only 35.26 (CR refers to completion rate).\n",+ "\n",+ "Cross-platform tasks are much more complex than single-platform tasks, and achieving the top score already demonstrates the outstanding ability of the GPT-4 series models in solving practical problems. However, we believe that emerging new methods and models can achieve better scores on CRAB, truly becoming efficient tools for solving real-world problems.\n",+ "\n",+ "### Cross-Platform Multimodal Agent Evaluation\n",+ "\n",+ "CRAB provides a comprehensive interactive agent evaluation framework. Through CRAB's foundational setup, agents can operate on various devices and platforms simultaneously, efficiently completing tasks in multiple isolated systems.\n",+ "\n",+ "The authors propose a new evaluation method called the graph evaluator, which differs from traditional methods based on final goals or action trajectories. The graph evaluator checks the intermediate states of task completion by breaking down tasks into multiple sub-goals.\n",+ "\n",+ "Each sub-goal is assigned an evaluation function to verify its completion, with each sub-goal being treated as a node in the graph evaluator.\n",+ "\n",+ "The graph structure describes the precedence and parallel relationships between sub-goals, thus providing fine-grained evaluation metrics; at the same time, the independent evaluation function for each sub-goal inherently adapts to multiple platforms.\n",+ "\n",+ "\n",+ "\n",+ "The table above compares CRAB with existing frameworks, including several key capabilities involved in testing:\n",+ "\n",+ "* **Interactive Environment:** Indicates whether an interactive platform or static dataset is used.\n",+ "* **Multimodal Observation:** Indicates whether multimodal input (e.g., screenshots) is supported.\n",+ "* **Cross-platform:** Indicates whether multiple operating systems or platforms are supported simultaneously.\n",+ "* **Evaluation:** Describes evaluation metrics, divided into goal-based (only checking if the final goal is completed), trajectory-based (comparing the agent's action trajectory with a predefined standard action sequence), multiple (varies by task), or graph-based (each node as an intermediate checkpoint in a DAG).\n",+ "* **Task Construction:** Shows the method of constructing tasks in the test dataset, including manually created, LLM-inspired (e.g., LLM generates task drafts but is verified and annotated by humans), template (multiple tasks generated based on manually written templates), or sub-task composition (composing multiple sub-tasks to construct task descriptions and evaluators).\n",+ "\n",+ "Based on the CRAB framework, the authors developed a benchmark dataset, CRAB Benchmark v0, supporting Android and Ubuntu environments.\n",+ "\n",+ "The benchmark includes 100 real-world tasks, covering various levels of difficulty for cross-platform and single-platform tasks. Tasks involve a variety of common issues and use multiple practical applications and tools, including but not limited to calendars, emails, maps, web browsers, and terminals, also replicating common coordination methods between smartphones and computers.\n",+ "\n",+ "\n",+ "\n",+ "### Problem Definition\n",+ "\n",+ "Assume an agent autonomously executes tasks on a device (such as a desktop). The device is usually equipped with input devices (like a mouse and keyboard) and output devices (like a screen) for human-computer interaction. The authors refer to a device or application with a fixed input method and output method as an environment.\n",+ "\n",+ "Formally, a single environment can be defined as a reward-free partially observable Markov decision process (Reward-free POMDP), represented by a tuple M := (S, A, T, O), where S represents the state space, A represents the action space, T: S ร A โ S is the transition function, and O is the observation space.\n",+ "\n",+ "Considering the collaborative nature of multiple devices in real-world scenarios, multiple platforms can be combined into a set M = {M1, M2, ..., Mn}, where n is the number of platforms, and each platform can be represented as Mj = (Sj, Aj, Tj, Oj).\n",+ "\n",+ "A task requiring operation across multiple platforms can be formalized as a tuple (M, I, R), where M is the platform set, I is the task goal described in natural language, and R is the task reward function.\n",+ "\n",+ "The authors call the algorithm responsible for completing the task the agent system. Each agent in the agent system uses a fixed backend model and predefined system prompt, retaining its dialogue history. The agent system can be a single agent or a multi-agent system with multiple agents cooperating.\n",+ "\n",+ "### Graph of Decomposed Tasks\n",+ "\n",+ "\n",+ "\n",+ "Breaking down complex tasks into simpler sub-tasks is an effective method for prompting large language models. The authors introduced this concept into the benchmark field, breaking down complex tasks into sub-tasks with precedence and parallel relationships, known as the Graph of Decomposed Tasks (GDT) as shown above.\n",+ "\n",+ "GDT uses a graph-based task decomposition method: using a DAG structure to represent decomposed sub-tasks.\n",+ "\n",+ "In GDT, each node is a sub-task, formalized as a tuple (m, i, r), where m specifies the environment for executing the sub-task, i provides natural language instructions, and r represents the reward function. The reward function evaluates the state of environment m and outputs a boolean value to determine if the sub-task is completed. Edges in GDT represent the precedence relationships between sub-tasks.\n",+ "\n",+ "### Graph Evaluator\n",+ "\n",+ "To evaluate the capabilities of large language models as agents, most benchmarks rely solely on the final state of the platform after the agent's operations.\n",+ "\n",+ "Simply judging whether the final goal is successful or failed is obviously not fair; it's like in a math exam, even if you can't solve the big problem, you should get points for writing some solution steps.\n",+ "\n",+ "Another method is trajectory-based matching, comparing the agent's operations with a predefined standard operation sequence (Label) for each task.\n",+ "\n",+ "However, in real-world systems, tasks may have multiple valid execution paths. For example, copying a file can be done using a file manager or a command line. Specifying a unique correct path is unfair to agents that achieve the goal in different ways.\n",+ "\n",+ "Therefore, this paper adopts a graph evaluator synchronized with platform states, tracking the agent's progress through the current state of sub-task completion.\n",+ "\n",+ "In addition to the traditional success rate (SR), which marks a task as successful only when all sub-tasks are completed, the authors introduced three metrics to measure the agent's performance and efficiency:\n",+ "\n",+ "1. **Completion Rate (CR):** Measures the proportion of completed sub-task nodes, calculated as the number of completed nodes/total nodes. This metric intuitively reflects the agent's progress on the given task.\n",+ "2. **Execution Efficiency (EE):** Calculated as CR/A, where A represents the number of actions performed, reflecting the agent's task execution efficiency.\n",+ "3. **Cost Efficiency (CE):** Calculated as CR/T, where T is the total number of tokens used by the agent, evaluating the agent's efficiency in terms of cost.\n",+ "\n",+ "### Experiments\n",+ "\n",+ "To run in Crab Benchmark-v0, the backend model needs to support the following features:\n",+ "\n",+ "1. Support multimodal mixed input: The system provides both screenshots and text instructions as prompts.\n",+ "2. Support multi-turn conversations: All tasks require the agent to perform multiple operations, so historical messages must be stored in context.\n",+ "3. Generate structured output through Function Call or similar functions: Used to execute operations in the environment.\n",+ "\n",+ "The experiments selected four multimodal models that meet these criteria: GPT-4o, GPT-4 Turbo, Gemini 1.5 Pro, and Claude 3 Opus.\n",+ "\n",+ "To compare the performance differences between multi-agent and single-agent systems, the paper designed three different agent systems:\n",+ "\n",+ "1. **Single Agent:** A single agent handles the entire process from understanding the task, observing the environment, planning, to executing actions.\n",+ "2. **Multi-agent by Functionality:** Consists of a main agent and a sub-agent. The main agent observes the environment and provides instructions to the sub-agent, which translates the instructions into specific operations.\n",+ "3. **Multi-agent by Environment:** Consists of a main agent and multiple sub-agents. Each sub-agent is responsible for one environment. The main agent understands the task, plans the execution process, and provides instructions to each sub-agent. The sub-agents observe their respective environments and translate the instructions into specific operations.\n",+ "\n",+ "The combinations of different agent systems and backend models provide multiple dimensions for comparison. Additionally, the paper compares the performance of models in tasks involving different platforms:\n",+ "\n",+ "**Ubuntu single-platform tasks:**\n",+ "\n",+ "\n",+ "\n",+ "**Android single-platform tasks:**\n",+ "\n",+ "\n",+ "\n",+ "**Cross-platform tasks:**\n",+ "\n",+ "\n",+ "\n",+ "Through data analysis, the paper draws several conclusions:\n",+ "\n",+ "**Performance Differences Among Models:**\n",+ "\n",+ "1. GPT-4o has the highest success and completion rates overall.\n",+ "2. GPT-4 TURBO performs better in cost efficiency (CE) than other models.\n",+ "3. Gemini 1.5 Pro and Claude 3 Opus struggle with task completion, finding it almost impossible to complete tasks.**โ**\n",+ "\n",+ "**Efficiency Metrics Reflect Different Characteristics of Models:**\n",+ "\n",+ "1. GPT-4 TURBO shows excellent cost efficiency in the single-agent mode, demonstrating cost-effective performance.\n",+ "2. GPT-4o maintains a balance between efficiency and performance, especially in the single-agent mode.\n",+ "3. Gemini 1.5 Pro shows low efficiency and incomplete cost efficiency metrics, mainly due to its low completion rate.\n",+ "\n",+ "**Evaluation of Termination Reasons Indicates Areas for Improvement:**\n",+ "\n",+ "1. All models have a high percentage of reaching the step limit (RSL), indicating that agents often run out of steps without achieving the final goal.\n",+ "2. Gemini 1.5 Pro has a high rate of invalid actions (IA), highlighting its inability to stably generate the correct format for interacting with the environment.\n",+ "3. The false completion (FC) rate in multi-agent systems is higher than in single-agent systems, indicating that message loss during communication between multiple agents can easily cause the executing sub-agent to misjudge.\n",+ "\n",+ "### ๐ซ Thanks from everyone at CAMEL-AI\n",+ "\n",+ "Hello there, passionate AI enthusiasts! ๐ We are ๐ซ CAMEL-AI.org, a global coalition of students, researchers, and engineers dedicated to advancing the frontier of AI and fostering a harmonious relationship between agents and humans.\n",+ "\n",+ "**๐ Our Mission:** To harness the potential of AI agents in crafting a brighter and more inclusive future for all. Every contribution we receive helps push the boundaries of whatโs possible in the AI realm.\n",+ "\n",+ "**๐ Join Us:** If you believe in a world where AI and humanity coexist and thrive, then youโre in the right place. Your support can make a significant difference. Letโs build the AI society of tomorrow, together!\n",+ "\n",+ "* Find all our updates on [X](https://twitter.com/CamelAIOrg)\n",+ " .\n",+ "* Make sure to star our [GitHub](https://github.com/camel-ai)\n",+ " repositories.\n",+ "* Join our [Discord,](https://discord.gg/nCpraan3sS)\n",+ " [WeChat](https://ghli.org/camel/wechat.png)\n",+ " or [Slack](https://join.slack.com/t/camel-ai/shared_invite/zt-2icssxnkj-YHwFVhoZHMYpIG~ZU86WVw)\n",+ " community.\n",+ "* You can contact us by email: [email protected]\n",+ "* Dive deeper and explore our projects on [https://www.camel-ai.org/](https://www.camel-ai.org/)\n",+ " \n",+ "\n",+ "> โ\n",+ "\n",+ "Get started\n",+ "\n",+ "Build your multi-agent system today\n",+ "-----------------------------------\n",+ "\n",+ "Get started by joining our community\n",+ "\n",+ "[Join Discord](http://discord.camel-ai.org/)\n",+ "\n",+ "\n",+ "\n",+ "Finding the scaling law of agents\n",+ "\n",+ "[](#)\n",+ "\n",+ "RESEARCH\n",+ "\n",+ "[Agent Trust](https://agent-trust.camel-ai.org/)\n",+ "[CRAB](https://github.com/camel-ai/crab?tab=readme-ov-file)\n",+ "\n",+ "RESOURCES\n",+ "\n",+ "[Newsroom](/newsroom)\n",+ "[Blog](/blog)\n",+ "[Docs](https://docs.camel-ai.org/)\n",+ "[Features & Integrations](/integration)\n",+ "[Team](/about)\n",+ "\n",+ "SOCIALS\n",+ "\n",+ "[Discord](http://discord.camel-ai.org/)\n",+ "[Github](https://github.com/camel-ai/camel)\n",+ "[LinkedIn](https://www.linkedin.com/company/camel-ai-org/)\n",+ "[Twitter](https://x.com/CamelAIOrg)\n",+ "[YouTube](https://www.youtube.com/@CamelAI)\n",+ "\n",+ "Copyright ยฉ 2024 Eigent AI - All Rights Reserved.\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "**๐ Firecrawl makes obtaining clean, LLM-friendly content from URL effortless!**"+ ],+ "metadata": {+ "id": "q5NJlRL1N5vu"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "## ๐ ๏ธ Web Information Retrieval using CAMEL's RAG and Firecrawl"+ ],+ "metadata": {+ "id": "NEUciNquON9_"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "*In this section, we'll demonstrate how to retrieve relevant information from a list of URLs using CAMEL's RAG model. This is particularly useful for aggregating and analyzing data from multiple sources.*"+ ],+ "metadata": {+ "id": "6f64VOMMP93d"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "### Setting Up Firecrawl with CAMEL's RAG"+ ],+ "metadata": {+ "id": "46Irp_SurLaV"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "The following function retrieves relevant information from a list of URLs based on a given query. It combines web scraping with Firecrawl and CAMEL's AutoRetriever for a seamless information retrieval process."+ ],+ "metadata": {+ "id": "QVB-Xra8QIU1"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "from camel.retrievers import AutoRetriever\n",+ "from camel.toolkits import FunctionTool, SearchToolkit\n",+ "from camel.types import ModelPlatformType, ModelType, StorageType\n",+ "from camel.embeddings import MistralEmbedding"+ ],+ "metadata": {+ "id": "gE_qBFCVveBR"+ },+ "execution_count": 16,+ "outputs": []+ },+ {+ "cell_type": "code",+ "source": [+ "def retrieve_information_from_urls(urls: list[str], query: str) -> str:\n",+ " r\"\"\"Retrieves relevant information from a list of URLs based on a given\n",+ " query.\n",+ "\n",+ " This function uses the `Firecrawl` tool to scrape content from the\n",+ " provided URLs and then uses the `AutoRetriever` from CAMEL to retrieve the\n",+ " most relevant information based on the query from the scraped content.\n",+ "\n",+ " Args:\n",+ " urls (list[str]): A list of URLs to scrape content from.\n",+ " query (str): The query string to search for relevant information.\n",+ "\n",+ " Returns:\n",+ " str: The most relevant information retrieved based on the query.\n",+ "\n",+ " Example:\n",+ " >>> urls = [\"https://example.com/article1\", \"https://example.com/\n",+ " article2\"]\n",+ " >>> query = \"latest advancements in AI\"\n",+ " >>> result = retrieve_information_from_urls(urls, query)\n",+ " \"\"\"\n",+ " aggregated_content = ''\n",+ "\n",+ " # Scrape and aggregate content from each URL\n",+ " for url in urls:\n",+ " scraped_content = Firecrawl().scrape(url)\n",+ " aggregated_content += scraped_content[\"markdown\"]\n",+ "\n",+ " # Set up a vector retriever with local storage and embedding model from Mistral AI\n",+ " auto_retriever = AutoRetriever(\n",+ " vector_storage_local_path=\"local_data\",\n",+ " storage_type=StorageType.QDRANT,\n",+ " embedding_model=MistralEmbedding(),\n",+ " )\n",+ "\n",+ " # Retrieve the most relevant information based on the query\n",+ " # You can adjust the top_k and similarity_threshold value based on your needs\n",+ " retrieved_info = auto_retriever.run_vector_retriever(\n",+ " query=query,\n",+ " contents=aggregated_content,\n",+ " top_k=3,\n",+ " similarity_threshold=0.5,\n",+ " )\n",+ "\n",+ " return retrieved_info"+ ],+ "metadata": {+ "id": "A75lxSmLsLSr"+ },+ "execution_count": 8,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "Let's put the retrieval function to the test by gathering some information about the 2024 Olympics.\n",+ "The first run may take about 50 seconds as it needs to build a local vector database."+ ],+ "metadata": {+ "id": "nLh5nU7uUeo-"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "retrieved_info = retrieve_information_from_urls(\n",+ " query=\"Which country won the most golden prize in 2024 Olympics?\",\n",+ " urls=[\n",+ " \"https://www.nbcnews.com/sports/olympics/united-states-china-gold-medals-rcna166013\",\n",+ " ],\n",+ ")\n",+ "\n",+ "print(retrieved_info)"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "z4z00v9yWvFw",+ "outputId": "79eb717b-8dcf-4806-da19-bbb97f462c78"+ },+ "execution_count": 9,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "{'Original Query': 'Which country won the most golden prize in 2024 Olympics?', 'Retrieved Context': [', when the โUnified Team,โ\\xa0athletes from the former Soviet Union republics, won 112 medals, including 45 golds. The Americans made 108 podium visits in Barcelona, with 37 of them on the top step.\\n\\n', '* Chinaโs Li Wenwen won gold in [womenโs heavyweight weightlifting](https://olympics.com/en/news/paris-2024-weightlifting-results-li-wenwen-81kg-gold)\\n in what could have been a death knell for American hopes to capture overall gold.\\n* U.S. hopes were dimmed further when [Chicago native](https://www.nbcchicago.com/paris-2024-summer-olympics/chicagos-kennedy-blades-scores-medal-in-her-first-ever-olympic-games/3519220/)', 'While there had been no gold medal ties in Summer Games history, there have been three draws in the Winter Olympics.\\n\\nThe most recent draw was between Norway and Germany, each [winning 14\\xa0golds in PyeongChang 2018](https://olympics.com/en/olympic-games/pyeongchang-2018/medals)\\n.\\n\\nThe U.S. still came out with the most overall medals, taking home 126 from Paris this year.\\n\\nThe U.S. hasnโt failed to win [the most medals since 1992](https://olympics.com/en/olympic-games/barcelona-1992/medals)']}\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "**๐ Thanks to CAMEL's RAG pipeline and Firecrawl's tidy scraping capabilities, this function effectively retrieves relevant information from the specified URLs! You can now integrate this function into CAMEL's Agents to automate the retrieval process further.**"+ ],+ "metadata": {+ "id": "r8QpOBNLX-R_"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "## ๐น Monitoring AI Agents with AgentOps"+ ],+ "metadata": {+ "id": "b7jyteu-2SFc"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "import agentops\n",+ "agentops.init(default_tags=[\"CAMEL cookbook\"])"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "mHSfqXyhIK0N",+ "outputId": "52d5c876-e7cf-480f-8355-495c6ff0e061"+ },+ "execution_count": 10,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stderr",+ "text": [+ "๐ AgentOps: \u001b[34m\u001b[34mSession Replay: https://app.agentops.ai/drilldown?session_id=85d13cd7-2417-448c-aac7-d8c360091e2d\u001b[0m\u001b[0m\n"+ ]+ },+ {+ "output_type": "execute_result",+ "data": {+ "text/plain": [+ "<agentops.session.Session at 0x7dafe4b91b40>"+ ]+ },+ "metadata": {},+ "execution_count": 10+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "## ๐ง Knowledge Graph Construction"+ ],+ "metadata": {+ "id": "n1Q8IKWUrAkr"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "*A powerful feature of CAMEL is its ability to build and store knowledge graphs from text data. This allows for advanced analysis and visualization of relationships within the data.*"+ ],+ "metadata": {+ "id": "dD7p_9CkyUmK"+ }+ },+ {+ "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": "k_fZhcgnrUX1"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "from camel.storages import Neo4jGraph\n",+ "from camel.loaders import UnstructuredIO\n",+ "from camel.agents import KnowledgeGraphAgent\n",+ "\n",+ "def knowledge_graph_builder(text_input: str) -> None:\n",+ " r\"\"\"Build and store a knowledge graph from the provided text.\n",+ "\n",+ " This function processes the input text to create and extract nodes and relationships,\n",+ " which are then added to a Neo4j database as a knowledge graph.\n",+ "\n",+ " Args:\n",+ " text_input (str): The input text from which the knowledge graph is to be constructed.\n",+ "\n",+ " Returns:\n",+ " graph_elements: The generated graph element from knowlegde graph agent.\n",+ " \"\"\"\n",+ "\n",+ " # Set Neo4j instance\n",+ " n4j = Neo4jGraph(\n",+ " url=\"Your_URL\",\n",+ " username=\"Your_Username\",\n",+ " password=\"Your_Password\",\n",+ " )\n",+ "\n",+ " # Initialize instances\n",+ " uio = UnstructuredIO()\n",+ " kg_agent = KnowledgeGraphAgent(model=mistral_large_2)\n",+ "\n",+ " # Create an element from the provided text\n",+ " element_example = uio.create_element_from_text(text=text_input, element_id=\"001\")\n",+ "\n",+ " # Extract nodes and relationships using the Knowledge Graph Agent\n",+ " graph_elements = kg_agent.run(element_example, parse_graph_elements=True)\n",+ "\n",+ " # Add the extracted graph elements to the Neo4j database\n",+ " n4j.add_graph_elements(graph_elements=[graph_elements])\n",+ "\n",+ " return graph_elements\n"+ ],+ "metadata": {+ "id": "raMV4BwhrhNK"+ },+ "execution_count": 12,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "## ๐ค๐ค Multi-Agent Role-Playing with CAMEL"+ ],+ "metadata": {+ "id": "uiDkPPrBshW4"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "*This section sets up a role-playing session where AI agents interact to accomplish a task using various tools. We will guide the assistant agent to perform a comprehensive study of the Turkish shooter in the 2024 Paris Olympics.*"+ ],+ "metadata": {+ "id": "6MZVoQI7OltM"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "from typing import List\n",+ "\n",+ "from colorama import Fore\n",+ "\n",+ "from camel.agents.chat_agent import FunctionCallingRecord\n",+ "from camel.societies import RolePlaying\n",+ "from camel.utils import print_text_animated"+ ],+ "metadata": {+ "id": "JTWQ4i6tt6mh"+ },+ "execution_count": 13,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "Defining the Task Prompt"+ ],+ "metadata": {+ "id": "ggqh3_t9tURm"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "task_prompt = \"\"\"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",+ "to get the retrieved content back by providing the list of URLs, finially\n",+ "use tool to build the knowledge graph to finish the task.\n",+ "No more other actions needed\"\"\""+ ],+ "metadata": {+ "id": "rtwuPLI_ssrX"+ },+ "execution_count": 14,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "We will configure the assistant agent with tools for mathematical calculations, web information retrieval, and knowledge graph building."+ ],+ "metadata": {+ "id": "KI0k6XJZtaN5"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "retrieval_tool = FunctionTool(retrieve_information_from_urls)\n",+ "search_tool = FunctionTool(SearchToolkit().search_duckduckgo)\n",+ "knowledge_graph_tool = FunctionTool(knowledge_graph_builder)\n",+ "\n",+ "tool_list = [\n",+ " retrieval_tool,\n",+ " search_tool,\n",+ " knowledge_graph_tool,\n",+ "]\n",+ "\n",+ "assistant_model_config = MistralConfig(\n",+ " tools=tool_list,\n",+ " temperature=0.0,\n",+ ")"+ ],+ "metadata": {+ "id": "Bw3_LyXiteVT"+ },+ "execution_count": 17,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "Setting Up the Role-Playing Session"+ ],+ "metadata": {+ "id": "Yc80X_ZItyvi"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "# Initialize the role-playing session\n",+ "role_play_session = RolePlaying(\n",+ " assistant_role_name=\"CAMEL Assistant\",\n",+ " user_role_name=\"CAMEL User\",\n",+ " assistant_agent_kwargs=dict(\n",+ " model=ModelFactory.create(\n",+ " model_platform=ModelPlatformType.MISTRAL,\n",+ " model_type=ModelType.MISTRAL_LARGE,\n",+ " model_config_dict=assistant_model_config.as_dict(),\n",+ " ),\n",+ " tools=tool_list,\n",+ " ),\n",+ " user_agent_kwargs=dict(model=mistral_large_2),\n",+ " task_prompt=task_prompt,\n",+ " with_task_specify=False,\n",+ ")"+ ],+ "metadata": {+ "id": "insV1gSyt0b3"+ },+ "execution_count": 18,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "Print the system message and task prompt"+ ],+ "metadata": {+ "id": "o7vfyJMdt8R1"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "# Print system and task messages\n",+ "print(\n",+ " Fore.GREEN\n",+ " + f\"AI Assistant sys message:\\n{role_play_session.assistant_sys_msg}\\n\"\n",+ ")\n",+ "print(Fore.BLUE + f\"AI User sys message:\\n{role_play_session.user_sys_msg}\\n\")\n",+ "\n",+ "print(Fore.YELLOW + f\"Original task prompt:\\n{task_prompt}\\n\")\n",+ "print(\n",+ " Fore.CYAN\n",+ " + \"Specified task prompt:\"\n",+ " + f\"\\n{role_play_session.specified_task_prompt}\\n\"\n",+ ")\n",+ "print(Fore.RED + f\"Final task prompt:\\n{role_play_session.task_prompt}\\n\")"+ ],+ "metadata": {+ "id": "9xMDZxBmt-Ms",+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "outputId": "cf73c34a-326f-40fa-f690-6347ca7ad600"+ },+ "execution_count": 19,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "\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",+ "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",+ "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",+ "to get the retrieved content back by providing the list of URLs, finially\n",+ "use tool to build the knowledge graph to finish the task.\n",+ "No more other actions needed\n",+ "\n",+ "\u001b[36mSpecified task prompt:\n",+ "None\n",+ "\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",+ "to get the retrieved content back by providing the list of URLs, finially\n",+ "use tool to build the knowledge graph to finish the task.\n",+ "No more other actions needed\n",+ "\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "Set the termination rule and start the interaction between agents\n",+ "\n",+ "**NOTE**: This session will take approximately 8 minutes and will consume around 60k tokens by using Mistral Large 2 Model."+ ],+ "metadata": {+ "id": "1ibe4da9uB2H"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "n = 0\n",+ "input_msg = role_play_session.init_chat()\n",+ "while n < 20: # Limit the chat to 20 turns\n",+ " n += 1\n",+ " assistant_response, user_response = role_play_session.step(input_msg)\n",+ "\n",+ " if assistant_response.terminated:\n",+ " print(\n",+ " Fore.GREEN\n",+ " + (\n",+ " \"AI Assistant terminated. Reason: \"\n",+ " f\"{assistant_response.info['termination_reasons']}.\"\n",+ " )\n",+ " )\n",+ " break\n",+ " if user_response.terminated:\n",+ " print(\n",+ " Fore.GREEN\n",+ " + (\n",+ " \"AI User terminated. \"\n",+ " f\"Reason: {user_response.info['termination_reasons']}.\"\n",+ " )\n",+ " )\n",+ " break\n",+ " # Print output from the user\n",+ " print_text_animated(\n",+ " Fore.BLUE + f\"AI User:\\n\\n{user_response.msg.content}\\n\",\n",+ " 0.01\n",+ " )\n",+ "\n",+ " if \"CAMEL_TASK_DONE\" in user_response.msg.content:\n",+ " break\n",+ "\n",+ " # Print output from the assistant, including any function\n",+ " # execution information\n",+ " print_text_animated(Fore.GREEN + \"AI Assistant:\", 0.01)\n",+ " tool_calls: List[FunctionCallingRecord] = [\n",+ " FunctionCallingRecord(**call.as_dict())\n",+ " for call in assistant_response.info['tool_calls']\n",+ " ]\n",+ " for func_record in tool_calls:\n",+ " print_text_animated(f\"{func_record}\", 0.01)\n",+ " print_text_animated(f\"{assistant_response.msg.content}\\n\", 0.01)\n",+ "\n",+ " input_msg = assistant_response.msg"+ ],+ "metadata": {+ "id": "xOhdpjxuuH-2",+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "outputId": "3d8018da-3c23-46c2-c12e-d5360a6fd95c"+ },+ "execution_count": null,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "\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",+ "\n",+ "Function Execution: search_duckduckgo\n",+ "\tArgs: {'query': 'Turkish shooter in the 2024 Paris Olympics'}\n",+ "\tResult: [{'result_id': 1, 'title': 'Meet Yusuf Dikec: The Turkish shooter who has gone viral at Paris 2024 ...', 'description': \"Yusuf Dikec, experienced Olympian and Turkish record breaker. Paris is far from Dikec's first rodeo. The Turkish shooter made his Olympic debut at Beijing 2008 aged 35, and returned four years later at London 2012.It was there where he recorded his previous best result of 13 th in the men's 50m free pistol event.. Dikec then competed at Rio 2016 and Tokyo 2020 held in 2021, though always shy ...\", 'url': 'https://olympics.com/en/news/yusuf-dikec-turkish-shooting-viral-paris-2024-olympics'}, {'result_id': 2, 'title': 'Turkish sharpshooter Yusuf Dikeรง wins silver at Paris Olympics with ...', 'description': \"Turkish sharpshooter Yusuf Dikeรง didn't need special lenses or big ear protectors to win the silver medal in the air pistol team event at the 2024 Paris Olympics.\", 'url': 'https://www.nbcnews.com/news/sports/sharpshooter-yusuf-dikec-silver-olympics-minimal-gear-internet-sensati-rcna164685'}, {'result_id': 3, 'title': 'Who is Yusuf Dikec, Turkish shooter who went viral at 2024 Olympics ...', 'description': 'CHATEAUROUX, France (AP) โ Turkish pistol shooter Yusuf Dikec has gone viral on social media for his seemingly casual attitude while shooting his way to a silver medal at the 2024 Olympics. The most-shared images show Dikec shooting in a T-shirt with one hand in his pocket, a seemingly standard pair of glasses and an impassive look on his face.', 'url': 'https://apnews.com/article/olympics-2024-yusuf-dikec-turkish-shooter-a7890124304080a48e7ee4294004d306'}, {'result_id': 4, 'title': \"WATCH: Turkey's sharpshooter wins silver without high-tech aids - NBC News\", 'description': 'Turkish Olympian Yusuf Dikec won silver in the 2024 Paris Olympics mixed air pistol team event. Dikec went viral for his nonchalant approach of not using any high-tech aids in the competition.', 'url': 'https://www.nbcnews.com/video/watch-turkey-s-sharpshooter-wins-silver-without-high-tech-aids-216173637766'}, {'result_id': 5, 'title': \"Yusuf Dikeรง: Turkey's viral Olympian inspires new celebration with ...\", 'description': \"Turkey's Yusuf Dikec competes in the shooting 10m air pistol mixed team gold medal match during the Paris 2024 Olympic Games at Chateauroux Shooting Centre on July 30, 2024. (Photo by Alain JOCARD ...\", 'url': 'https://www.cnn.com/2024/08/09/sport/yusuf-dikec-olympic-celebration-craze-spt-intl/index.html'}]\n",+ "\n",+ "Solution: I have used the search tool to find related URLs about the Turkish shooter in the 2024 Paris Olympics. Here are the results:\n",+ "\n",+ "1. **Title:** Meet Yusuf Dikec: The Turkish shooter who has gone viral at Paris 2024 ...\n",+ " **Description:** Yusuf Dikec, experienced Olympian and Turkish record breaker. Paris is far from Dikec's first rodeo. The Turkish shooter made his Olympic debut at Beijing 2008 aged 35, and returned four years later at London 2012. It was there where he recorded his previous best result of 13th in the men's 50m free pistol event. Dikec then competed at Rio 2016 and Tokyo 2020 held in 2021, though always shy ...\n",+ " **URL:** [https://olympics.com/en/news/yusuf-dikec-turkish-shooting-viral-paris-2024-olympics](https://olympics.com/en/news/yusuf-dikec-turkish-shooting-viral-paris-2024-olympics)\n",+ "\n",+ "2. **Title:** Turkish sharpshooter Yusuf Dikeรง wins silver at Paris Olympics with ...\n",+ " **Description:** Turkish sharpshooter Yusuf Dikeรง didn't need special lenses or big ear protectors to win the silver medal in the air pistol team event at the 2024 Paris Olympics.\n",+ " **URL:** [https://www.nbcnews.com/news/sports/sharpshooter-yusuf-dikec-silver-olympics-minimal-gear-internet-sensati-rcna164685](https://www.nbcnews.com/news/sports/sharpshooter-yusuf-dikec-silver-olympics-minimal-gear-internet-sensati-rcna164685)\n",+ "\n",+ "3. **Title:** Who is Yusuf Dikec, Turkish shooter who went viral at 2024 Olympics ...\n",+ " **Description:** CHATEAUROUX, France (AP) โ Turkish pistol shooter Yusuf Dikec has gone viral on social media for his seemingly casual attitude while shooting his way to a silver medal at the 2024 Olympics. The most-shared images show Dikec shooting in a T-shirt with one hand in his pocket, a seemingly standard pair of glasses and an impassive look on his face.\n",+ " **URL:** [https://apnews.com/article/olympics-2024-yusuf-dikec-turkish-shooter-a7890124304080a48e7ee4294004d306](https://apnews.com/article/olympics-2024-yusuf-dikec-turkish-shooter-a7890124304080a48e7ee4294004d306)\n",+ "\n",+ "4. **Title:** WATCH: Turkey's sharpshooter wins silver without high-tech aids - NBC News\n",+ " **Description:** Turkish Olympian Yusuf Dikec won silver in the 2024 Paris Olympics mixed air pistol team event. Dikec went viral for his nonchalant approach of not using any high-tech aids in the competition.\n",+ " **URL:** [https://www.nbcnews.com/video/watch-turkey-s-sharpshooter-wins-silver-without-high-tech-aids-216173637766](https://www.nbcnews.com/video/watch-turkey-s-sharpshooter-wins-silver-without-high-tech-aids-216173637766)\n",+ "\n",+ "5. **Title:** Yusuf Dikeรง: Turkey's viral Olympian inspires new celebration with ...\n",+ " **Description:** Turkey's Yusuf Dikec competes in the shooting 10m air pistol mixed team gold medal match during the Paris 2024 Olympic Games at Chateauroux Shooting Centre on July 30, 2024. (Photo by Alain JOCARD ...\n",+ " **URL:** [https://www.cnn.com/2024/08/09/sport/yusuf-dikec-olympic-celebration-craze-spt-intl/index.html](https://www.cnn.com/2024/08/09/sport/yusuf-dikec-olympic-celebration-craze-spt-intl/index.html)\n",+ "\n",+ "Next request.\n",+ "\n",+ "\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",+ "\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",+ "\tResult: {'Original Query': 'Turkish shooter in the 2024 Paris Olympics', 'Retrieved Context': [\"1/mobile/left.svg)\\n\\n\\n\\n\\n\\n## **Yusuf Dikec, experienced Olympian and Turkish record breaker**\\n\\nParis is far from Dikec's first rodeo. The Turkish shooter made his Olympic debut at [Beijing 2008](https://olympics.com/en/olympic-games/beijing-2008) aged 35, and returned four years later at [London 2012](https:\", \"to internet stardom.\\n\\nWithout the special lenses and ear protectors typical of the sport, and with one hand casually tucked into his pocket, Dikec effortlessly shot his way onto the podium. He and partner Sevval Ilayda Tarhan nabbed Turkeyโs first medal in Olympic shooting.\\n\\nTurkey's Yusuf Dikec competes in the shooting 10m air p\", \"ular pair of glasses. His partner, ลevval ฤฐlayda\\xa0Tarhan, also didn't wear any blinders and kept one hand tucked in her pocket. Their win was Turkeyโs first medal in an Olympic shooting event.\\n\\nSilver medalists ลevval ฤฐlayda Tarhan and Yusuf Dikeรง of Turkey on the podium during after the 10-meter air pistol mixed \"]}\n",+ "\n",+ "Solution: I have used the retrieval tool to get the content from the provided URLs. Here is the retrieved content:\n",+ "\n",+ "1. **URL:** [https://olympics.com/en/news/yusuf-dikec-turkish-shooting-viral-paris-2024-olympics](https://olympics.com/en/news/yusuf-dikec-turkish-shooting-viral-paris-2024-olympics)\n",+ " **Content:**\n",+ " ```\n",+ " \n",+ "\n",+ " \n",+ "\n",+ " \n",+ "\n",+ " ## **Yusuf Dikec, experienced Olympian and Turkish record breaker**\n",+ "\n",+ " Paris is far from Dikec's first rodeo. The Turkish shooter made his Olympic debut at [Beijing 2008](https://olympics.com/en/olympic-games/beijing-2008) aged 35, and returned four years later at [London 2012](https:\n",+ " ```\n",+ "\n",+ "2. **URL:** [https://www.nbcnews.com/news/sports/sharpshooter-yusuf-dikec-silver-olympics-minimal-gear-internet-sensati-rcna164685](https://www.nbcnews.com/news/sports/sharpshooter-yusuf-dikec-silver-olympics-minimal-gear-internet-sensati-rcna164685)\n",+ " **Content:**\n",+ " ```\n",+ " Without the special lenses and ear protectors typical of the sport, and with one hand casually tucked into his pocket, Dikec effortlessly shot his way onto the podium. He and partner Sevval Ilayda Tarhan nabbed Turkeyโs first medal in Olympic shooting.\n",+ "\n",+ " \n",+ " Turkey's Yusuf Dikec competes in the shooting 10m air pistol\n",+ " ```\n",+ "\n",+ "3. **URL:** [https://apnews.com/article/olympics-2024-yusuf-dikec-turkish-shooter-a7890124304080a48e7ee4294004d306](https://apnews.com/article/olympics-2024-yusuf-dikec-turkish-shooter-a7890124304080a48e7ee4294004d306)\n",+ " **Content:**\n",+ " ```\n",+ " With a regular pair of glasses. His partner, ลevval ฤฐlayda Tarhan, also didnโt wear any blinders and kept one hand tucked in her pocket. Their win was Turkeyโs first medal in an Olympic shooting event.\n",+ "\n",+ " \n",+ " Silver medalists ลevval ฤฐlayda Tarhan and Yusuf Dikeรง of Turkey on the podium during after the 10-meter air pistol mixed\n",+ " ```\n",+ "\n",+ "Next request.\n",+ "\n",+ "\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",+ "\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",+ "1. **Experienced Olympian:** Yusuf Dikec is an experienced Olympian who made his debut at the Beijing 2008 Olympics at the age of 35. He has also competed in the London 2012, Rio 2016, and Tokyo 2020 Olympics.\n",+ "\n",+ "2. **Silver Medal Win:** Dikec won a silver medal in the air pistol team event at the 2024 Paris Olympics. He competed with minimal gear, without special lenses or big ear protectors, and with one hand casually tucked into his pocket.\n",+ "\n",+ "3. **Viral Sensation:** Dikec's nonchalant approach and minimal gear during the competition went viral on the internet. His seemingly casual attitude while shooting his way to a silver medal caught the attention of many.\n",+ "\n",+ "4. **Partnership with Sevval Ilayda Tarhan:** Dikec competed alongside Sevval Ilayda Tarhan in the mixed air pistol team event. Together, they won Turkeyโs first medal in Olympic shooting.\n",+ "\n",+ "5. **Historic Achievement:** The win marked Turkeyโs first medal in an Olympic shooting event, highlighting the significance of Dikec and Tarhan's achievement.\n",+ "\n",+ "Next request.\n",+ "\n",+ "\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",+ "\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",+ "---\n",+ "\n",+ "### Comprehensive Report on Turkish Shooter Yusuf Dikec at the 2024 Paris Olympics\n",+ "\n",+ "#### Introduction\n",+ "\n",+ "Yusuf 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",+ "\n",+ "Yusuf 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",+ "\n",+ "At 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",+ "\n",+ "Dikec'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",+ "\n",+ "Dikec 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",+ "\n",+ "The 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",+ "\n",+ "Yusuf 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",+ "\n",+ "---\n",+ "\n",+ "Next request.\n",+ "\n",+ "\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",+ "\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",+ "\tResult: {'nodes': [{'id': 'Yusuf Dikec', 'type': 'Person', 'properties': {'source': 'agent_created'}}, {'id': 'Turkey', 'type': 'Country', 'properties': {'source': 'agent_created'}}, {'id': '2024 Paris Olympics', 'type': 'Event', 'properties': {'source': 'agent_created'}}, {'id': 'Silver Medal', 'type': 'Achievement', 'properties': {'source': 'agent_created'}}, {'id': 'Air Pistol Team Event', 'type': 'Event', 'properties': {'source': 'agent_created'}}, {'id': 'Sevval Ilayda Tarhan', 'type': 'Person', 'properties': {'source': 'agent_created'}}, {'id': 'Mixed Air Pistol Team Event', 'type': 'Event', 'properties': {'source': 'agent_created'}}, {'id': 'Beijing 2008 Olympics', 'type': 'Event', 'properties': {'source': 'agent_created'}}, {'id': 'London 2012 Olympics', 'type': 'Event', 'properties': {'source': 'agent_created'}}, {'id': 'Rio 2016 Olympics', 'type': 'Event', 'properties': {'source': 'agent_created'}}, {'id': 'Tokyo 2020 Olympics', 'type': 'Event', 'properties': {'source': 'agent_created'}}], 'relationships': [{'subj': {'id': 'Yusuf Dikec', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': 'Turkey', 'type': 'Country', 'properties': {'source': 'agent_created'}}, 'type': 'Represents', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Yusuf Dikec', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': '2024 Paris Olympics', 'type': 'Event', 'properties': {'source': 'agent_created'}}, 'type': 'ParticipatedIn', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Yusuf Dikec', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': 'Silver Medal', 'type': 'Achievement', 'properties': {'source': 'agent_created'}}, 'type': 'Won', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Yusuf Dikec', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': 'Air Pistol Team Event', 'type': 'Event', 'properties': {'source': 'agent_created'}}, 'type': 'CompetedIn', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Yusuf Dikec', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': 'Sevval Ilayda Tarhan', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'type': 'PartneredWith', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Yusuf Dikec', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': 'Mixed Air Pistol Team Event', 'type': 'Event', 'properties': {'source': 'agent_created'}}, 'type': 'CompetedIn', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Yusuf Dikec', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': 'Beijing 2008 Olympics', 'type': 'Event', 'properties': {'source': 'agent_created'}}, 'type': 'ParticipatedIn', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Yusuf Dikec', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': 'London 2012 Olympics', 'type': 'Event', 'properties': {'source': 'agent_created'}}, 'type': 'ParticipatedIn', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Yusuf Dikec', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': 'Rio 2016 Olympics', 'type': 'Event', 'properties': {'source': 'agent_created'}}, 'type': 'ParticipatedIn', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Yusuf Dikec', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': 'Tokyo 2020 Olympics', 'type': 'Event', 'properties': {'source': 'agent_created'}}, 'type': 'ParticipatedIn', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Sevval Ilayda Tarhan', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': 'Turkey', 'type': 'Country', 'properties': {'source': 'agent_created'}}, 'type': 'Represents', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Sevval Ilayda Tarhan', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': '2024 Paris Olympics', 'type': 'Event', 'properties': {'source': 'agent_created'}}, 'type': 'ParticipatedIn', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Sevval Ilayda Tarhan', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': 'Mixed Air Pistol Team Event', 'type': 'Event', 'properties': {'source': 'agent_created'}}, 'type': 'CompetedIn', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Turkey', 'type': 'Country', 'properties': {'source': 'agent_created'}}, 'obj': {'id': 'Silver Medal', 'type': 'Achievement', 'properties': {'source': 'agent_created'}}, 'type': 'Achieved', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Yusuf Dikec', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': 'Turkey', 'type': 'Country', 'properties': {'source': 'agent_created'}}, 'type': 'Represents', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Yusuf Dikec', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': '2024 Paris Olympics', 'type': 'Event', 'properties': {'source': 'agent_created'}}, 'type': 'ParticipatedIn', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Yusuf Dikec', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': 'Silver Medal', 'type': 'Achievement', 'properties': {'source': 'agent_created'}}, 'type': 'Won', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Yusuf Dikec', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': 'Air Pistol Team Event', 'type': 'Event', 'properties': {'source': 'agent_created'}}, 'type': 'CompetedIn', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Yusuf Dikec', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': 'Sevval Ilayda Tarhan', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'type': 'PartneredWith', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Yusuf Dikec', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': 'Mixed Air Pistol Team Event', 'type': 'Event', 'properties': {'source': 'agent_created'}}, 'type': 'CompetedIn', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Yusuf Dikec', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': 'Beijing 2008 Olympics', 'type': 'Event', 'properties': {'source': 'agent_created'}}, 'type': 'ParticipatedIn', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Yusuf Dikec', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': 'London 2012 Olympics', 'type': 'Event', 'properties': {'source': 'agent_created'}}, 'type': 'ParticipatedIn', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Yusuf Dikec', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': 'Rio 2016 Olympics', 'type': 'Event', 'properties': {'source': 'agent_created'}}, 'type': 'ParticipatedIn', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Yusuf Dikec', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': 'Tokyo 2020 Olympics', 'type': 'Event', 'properties': {'source': 'agent_created'}}, 'type': 'ParticipatedIn', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Sevval Ilayda Tarhan', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': 'Turkey', 'type': 'Country', 'properties': {'source': 'agent_created'}}, 'type': 'Represents', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Sevval Ilayda Tarhan', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': '2024 Paris Olympics', 'type': 'Event', 'properties': {'source': 'agent_created'}}, 'type': 'ParticipatedIn', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Sevval Ilayda Tarhan', 'type': 'Person', 'properties': {'source': 'agent_created'}}, 'obj': {'id': 'Mixed Air Pistol Team Event', 'type': 'Event', 'properties': {'source': 'agent_created'}}, 'type': 'CompetedIn', 'properties': {'source': 'agent_created'}}, {'subj': {'id': 'Turkey', 'type': 'Country', 'properties': {'source': 'agent_created'}}, 'obj': {'id': 'Silver Medal', 'type': 'Achievement', 'properties': {'source': 'agent_created'}}, 'type': 'Achieved', 'properties': {'source': 'agent_created'}}], 'source': <unstructured.documents.elements.Text object at 0x7c82e2847520>}\n",+ "\n",+ "Solution: I have used the tool to build a knowledge graph based on the comprehensive report about the Turkish shooter Yusuf Dikec at the 2024 Paris Olympics. Here is the knowledge graph:\n",+ "\n",+ "### Knowledge Graph\n",+ "\n",+ "#### Nodes\n",+ "\n",+ "1. **Yusuf Dikec** (Person)\n",+ "2. **Turkey** (Country)\n",+ "3. **2024 Paris Olympics** (Event)\n",+ "4. **Silver Medal** (Achievement)\n",+ "5. **Air Pistol Team Event** (Event)\n",+ "6. **Sevval Ilayda Tarhan** (Person)\n",+ "7. **Mixed Air Pistol Team Event** (Event)\n",+ "8. **Beijing 2008 Olympics** (Event)\n",+ "9. **London 2012 Olympics** (Event)\n",+ "10. **Rio 2016 Olympics** (Event)\n",+ "11. **Tokyo 2020 Olympics** (Event)\n",+ "\n",+ "#### Relationships\n",+ "\n",+ "1. **Yusuf Dikec** (Person) - **Represents** - **Turkey** (Country)\n",+ "2. **Yusuf Dikec** (Person) - **ParticipatedIn** - **2024 Paris Olympics** (Event)\n",+ "3. **Yusuf Dikec** (Person) - **Won** - **Silver Medal** (Achievement)\n",+ "4. **Yusuf Dikec** (Person) - **CompetedIn** - **Air Pistol Team Event** (Event)\n",+ "5. **Yusuf Dikec** (Person) - **PartneredWith** - **Sevval Ilayda Tarhan** (Person)\n",+ "6. **Yusuf Dikec** (Person) - **CompetedIn** - **Mixed Air Pistol Team Event** (Event)\n",+ "7. **Yusuf Dikec** (Person) - **ParticipatedIn** - **Beijing 2008 Olympics** (Event)\n",+ "8. **Yusuf Dikec** (Person) - **ParticipatedIn** - **London 2012 Olympics** (Event)\n",+ "9. **Yusuf Dikec** (Person) - **ParticipatedIn** - **Rio 2016 Olympics** (Event)\n",+ "10. **Yusuf Dikec** (Person) - **ParticipatedIn** - **Tokyo 2020 Olympics** (Event)\n",+ "11. **Sevval Ilayda Tarhan** (Person) - **Represents** - **Turkey** (Country)\n",+ "12. **Sevval Ilayda Tarhan** (Person) - **ParticipatedIn** - **2024 Paris Olympics** (Event)\n",+ "13. **Sevval Ilayda Tarhan** (Person) - **CompetedIn** - **Mixed Air Pistol Team Event** (Event)\n",+ "14. **Turkey** (Country) - **Achieved** - **Silver Medal** (Achievement)\n",+ "\n",+ "This knowledge graph captures the key entities and their relationships as described in the comprehensive report about Yusuf Dikec at the 2024 Paris Olympics.\n",+ "\n",+ "Next request.\n",+ "\n",+ "\n",+ "\u001b[34mAI User:\n",+ "\n",+ "<CAMEL_TASK_DONE>\n",+ "\n",+ "\n"+ ]+ }+ ]+ },+ {+ "cell_type": "code",+ "source": [+ "# End the AgentOps session\n",+ "agentops.end_session(\"Success\")"+ ],+ "metadata": {+ "id": "t7zTkjDBIf_i",+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "outputId": "32f89a58-ca8f-46fc-b9aa-cd5d6f003ace"+ },+ "execution_count": null,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stderr",+ "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"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "๐ Go to the AgentOps link shown above, you will be able to see the detailed record for this running like below.\n",+ "\n",+ "**NOTE**: The AgentOps link is private and tied to the AgentOps account. To access the link, youโll need to run the session using your own AgentOps API Key, which will then allow you to open the link with the sessionโs running information.\n",+ "\n",+ "Currently AgentOps can't get the running cost for Mistral AI directly."+ ],+ "metadata": {+ "id": "4au_S6ITIfnx"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ ""+ ],+ "metadata": {+ "id": "OTGVmZ2bouJv"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "๐ You can also go the the [Neo4j Aura](https://login.neo4j.com/u/login/identifier?state=hKFo2SBRTk8tVW5CU201cGtOMDdGYlp1bFJYRlVUZGlUY05SdqFur3VuaXZlcnNhbC1sb2dpbqN0aWTZIEFSYTFtMVJsekVnVy1vaHZjQzRNWDB4SXlYak9SOUw5o2NpZNkgV1NMczYwNDdrT2pwVVNXODNnRFo0SnlZaElrNXpZVG8) to check the knowledge graph generated by CAMEL's Agent like below."+ ],+ "metadata": {+ "id": "yDriFSAr4QRw"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ ""+ ],+ "metadata": {+ "id": "Tq_wssFTYaKH"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "## ๐ Highlights"+ ],+ "metadata": {+ "id": "flYNal6-R4yR"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "This notebook has guided you through setting up and running a CAMEL RAG workflow with Firecrawl for a complex, multi-agent role-playing task. You can adapt and expand this example for various other scenarios requiring advanced web information retrieval and AI collaboration.\n",+ "\n",+ "Key tools utilized in this notebook include:\n",+ "\n",+ "* **CAMEL**: A powerful multi-agent framework that enables Retrieval-Augmented Generation and multi-agent role-playing scenarios, allowing for sophisticated AI-driven tasks.\n",+ "* **Mistral**: Utilized for its state-of-the-art language models, which enable tool-calling capabilities to execute external functions, while its powerful embeddings are employed for semantic search and content retrieval.\n",+ "* **Firecrawl**: A robust web scraping tool that simplifies extracting and cleaning content from various web pages.\n",+ "* **AgentOps**: Track and analysis the running of CAMEL Agents.\n",+ "* **Qdrant**: An efficient vector storage system used with CAMELโs AutoRetriever to store and retrieve relevant information based on vector similarities.\n",+ "* **Neo4j**: A leading graph database management system used for constructing and storing knowledge graphs, enabling complex relationships between entities to be mapped and queried efficiently.\n",+ "* **DuckDuckGo Search**: Utilized within the SearchToolkit to gather relevant URLs and information from the web, serving as the primary search engine for retrieving initial content.\n",+ "* **Unstructured IO:** Used for content chunking, facilitating the management of unstructured data for more efficient processing.\n",+ "\n",+ "This comprehensive setup allows you to adapt and expand the example for various scenarios requiring advanced web information retrieval, AI collaboration, and multi-source data aggregation.\n",+ "\n",+ "**CAMEL also support advanced GraphRAG, for more information please check [here](https://colab.research.google.com/drive/1meBf9w8KzZvQdQU2I1bCyOg9ehoGDK1u?authuser=1)**"+ ],+ "metadata": {+ "id": "SmkXhy4JR726"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "โญ **Star the Repo**\n",+ "\n",+ "If you find CAMEL useful or interesting, please consider giving it a star on [GitHub](https://github.com/camel-ai/camel)! Your stars help others find this project and motivate us to continue improving it."+ ],+ "metadata": {+ "id": "s6Det-fcMb9A"+ }}- ],- "source": [- "# End the AgentOps session\n",- "agentops.end_session(\"Success\")"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "4au_S6ITIfnx"- },- "source": [- "๐ Go to the AgentOps link shown above, you will be able to see the detailed record for this running like below.\n",- "\n",- "**NOTE**: The AgentOps link is private and tied to the AgentOps account. To access the link, youโll need to run the session using your own AgentOps API Key, which will then allow you to open the link with the sessionโs running information.\n",- "\n",- "Currently AgentOps can't get the running cost for Mistral AI directly."- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "OTGVmZ2bouJv"- },- "source": [- ""- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "yDriFSAr4QRw"- },- "source": [- "๐ You can also go the the [Neo4j Aura](https://login.neo4j.com/u/login/identifier?state=hKFo2SBRTk8tVW5CU201cGtOMDdGYlp1bFJYRlVUZGlUY05SdqFur3VuaXZlcnNhbC1sb2dpbqN0aWTZIEFSYTFtMVJsekVnVy1vaHZjQzRNWDB4SXlYak9SOUw5o2NpZNkgV1NMczYwNDdrT2pwVVNXODNnRFo0SnlZaElrNXpZVG8) to check the knowledge graph generated by CAMEL's Agent like below."- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "Tq_wssFTYaKH"- },- "source": [- ""- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "flYNal6-R4yR"- },- "source": [- "## ๐ Highlights"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "SmkXhy4JR726"- },- "source": [- "This notebook has guided you through setting up and running a CAMEL RAG workflow with Firecrawl for a complex, multi-agent role-playing task. You can adapt and expand this example for various other scenarios requiring advanced web information retrieval and AI collaboration.\n",- "\n",- "Key tools utilized in this notebook include:\n",- "\n",- "* **CAMEL**: A powerful multi-agent framework that enables Retrieval-Augmented Generation and multi-agent role-playing scenarios, allowing for sophisticated AI-driven tasks.\n",- "* **Mistral**: Utilized for its state-of-the-art language models, which enable tool-calling capabilities to execute external functions, while its powerful embeddings are employed for semantic search and content retrieval.\n",- "* **Firecrawl**: A robust web scraping tool that simplifies extracting and cleaning content from various web pages.\n",- "* **AgentOps**: Track and analysis the running of CAMEL Agents.\n",- "* **Qdrant**: An efficient vector storage system used with CAMELโs AutoRetriever to store and retrieve relevant information based on vector similarities.\n",- "* **Neo4j**: A leading graph database management system used for constructing and storing knowledge graphs, enabling complex relationships between entities to be mapped and queried efficiently.\n",- "* **DuckDuckGo Search**: Utilized within the SearchToolkit to gather relevant URLs and information from the web, serving as the primary search engine for retrieving initial content.\n",- "* **Unstructured IO:** Used for content chunking, facilitating the management of unstructured data for more efficient processing.\n",- "\n",- "This comprehensive setup allows you to adapt and expand the example for various scenarios requiring advanced web information retrieval, AI collaboration, and multi-source data aggregation.\n",- "\n",- "**CAMEL also support advanced GraphRAG, for more information please check [here](https://colab.research.google.com/drive/1meBf9w8KzZvQdQU2I1bCyOg9ehoGDK1u?authuser=1)**"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "s6Det-fcMb9A"- },- "source": [- "โญ **Star the Repo**\n",- "\n",- "If you find CAMEL useful or interesting, please consider giving it a star on [GitHub](https://github.com/camel-ai/camel)! Your stars help others find this project and motivate us to continue improving it."- ]- }- ],- "metadata": {- "colab": {- "provenance": []- },- "kernelspec": {- "display_name": "Python 3",- "name": "python3"- },- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 0-}+ ]+}\ No newline at end of filediff --git a/docs/cookbooks/task_generation.ipynb b/docs/cookbooks/task_generation.ipynbindex 89f0442fe..a8d9be1fd 100644--- a/docs/cookbooks/task_generation.ipynb+++ b/docs/cookbooks/task_generation.ipynb@@ -1,328 +1,322 @@{- "cells": [- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "Fvdt_pMpf7EK"- },- "source": [- "# Task Generation Cookbook"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "pf-CrViNgJqn"- },- "source": [- "You can also check this cookbook in colab [here](https://colab.research.google.com/drive/1n_SjiE7NRmpUUBcRge-gqKAv5mzWPcU0?usp=sharing)"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "2XXT4d1tf7EM"- },- "source": [- "In this tutorial, we will focus on demonstrating how to use the task module in the CAMEL framework. We will guide you through creating, evolving, and decomposing tasks to illustrate how the task module can be utilized for efficient task management in agent-based systems."- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "ph2dWXb-f7EM"- },- "source": [- "Sections included:\n",- "\n",- "- Setting up a ChatAgent with the CAMEL framework\n",- "- Creating a Task and evolving it with the agent using TaskManager\n",- "- Task decomposition using the CAMEL task module\n",- "\n",- "Let's go step by step!"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "4uoXafBRf7EN"- },- "source": [- "## Step 1: Import necessary CAMEL modules\n",- "\n",- "First, we need to import the required CAMEL modules for creating the ChatAgent and handling tasks."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "id": "My_O9chyf7EN"- },- "outputs": [],- "source": [- "%pip install \"camel-ai==0.2.1\""- ]- },- {- "cell_type": "code",- "execution_count": 2,- "metadata": {- "id": "3povzm9qf7EO"- },- "outputs": [],- "source": [- "from camel.agents import ChatAgent\n",- "from camel.configs import ChatGPTConfig\n",- "from camel.messages import BaseMessage\n",- "from camel.models import ModelFactory\n",- "from camel.tasks import (\n",- " Task,\n",- " TaskManager,\n",- ")\n",- "from camel.types import (\n",- " ModelPlatformType,\n",- " ModelType,\n",- ")"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "H9ANkBsuf7EO"- },- "source": [- "Set your OpenAI key"- ]- },- {- "cell_type": "code",- "execution_count": 3,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"+ "cells": [+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "Fvdt_pMpf7EK"+ },+ "source": [+ "# ๐ซ CAMEL Task Generation Cookbook"+ ]},- "id": "t7u1PNhnf7EO",- "outputId": "2a0d53d5-1a56-4b63-f305-7894939f71c6"- },- "outputs": [{- "name": "stdout",- "output_type": "stream",- "text": [- "Enter your API key: ยทยทยทยทยทยทยทยทยทยท\n"- ]- }- ],- "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"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "brQ0v3kaf7EP"- },- "source": [- "## Step 2: Set up the Large Language Model (LLM)\n",- "\n",- "Next, we set up the model configuration. We are using a GPT-4O Mini in this case for our assistant agent. The configuration is designed to ensure the agentโs behavior remains deterministic by setting temperature=0.0, meaning no randomness will be introduced in the responses."- ]- },- {- "cell_type": "code",- "execution_count": 4,- "metadata": {- "id": "DLXsqm7mf7EP"- },- "outputs": [],- "source": [- "# Model configuration for the assistant\n",- "assistant_model_config = ChatGPTConfig(\n",- " temperature=0.0, # Set to 0 for deterministic output\n",- ")\n",- "\n",- "# Create the model using the configuration\n",- "model = ModelFactory.create(\n",- " model_platform=ModelPlatformType.OPENAI,\n",- " model_type=ModelType.GPT_4O_MINI,\n",- " model_config_dict=assistant_model_config.as_dict(),\n",- ")"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "IAstp4cyf7EP"- },- "source": [- "## Step 3: Initialize the ChatAgent\n",- "\n",- "We now create a ChatAgent using the previously defined model. This agent will interact with tasks in the CAMEL framework, following the role of a personal math tutor and programmer."- ]- },- {- "cell_type": "code",- "execution_count": 5,- "metadata": {- "id": "rSo-keNnf7EP"- },- "outputs": [],- "source": [- "# Set up the assistant's system message\n",- "assistant_sys_msg = BaseMessage.make_user_message(\n",- " role_name=\"Teacher\",\n",- " content=(\"You are a personal math tutor and programmer.\"),\n",- ")\n",- "\n",- "# Initialize the ChatAgent\n",- "agent = ChatAgent(assistant_sys_msg, model)\n",- "agent.reset() # Reset the agent's internal state"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "b-RGszDYf7EP"- },- "source": [- "## Step 4: Evolve and decompose tasks\n",- "\n",- "We now create a Task that represents a math problem for the assistant to solve. In this case, we are asking the assistant to calculate how much Weng earned for babysitting based on her hourly rate and the time she worked."- ]- },- {- "cell_type": "code",- "execution_count": 6,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"+ "cell_type": "markdown",+ "metadata": {+ "id": "pf-CrViNgJqn"+ },+ "source": [+ "You can also check this cookbook in colab [here](https://colab.research.google.com/drive/1n_SjiE7NRmpUUBcRge-gqKAv5mzWPcU0?usp=sharing)"+ ]},- "id": "YZ8TaZzjf7EQ",- "outputId": "9b176f78-a505-4d35-94a3-ee34313a884d"- },- "outputs": [{- "name": "stdout",- "output_type": "stream",- "text": [- "Task 0: Weng earns $12 an hour for babysitting. Yesterday, she just did 51 minutes of babysitting. How much did she earn?\n",- "\n"- ]- }- ],- "source": [- "# Create a Task for the agent to solve\n",- "task = Task(\n",- " content=\"Weng earns $12 an hour for babysitting. Yesterday, she just did 51 minutes of babysitting. How much did she earn?\",\n",- " id=\"0\", # Task identifier\n",- ")\n",- "\n",- "# Print the task to see the original form\n",- "print(task.to_string())"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "R1xHH7UAf7EQ"- },- "source": [- "### Evolve the Task\n",- "\n",- "We can evolve the task using the TaskManager, which allows the agent to potentially update or reframe the task based on its internal logic and context."- ]- },- {- "cell_type": "code",- "execution_count": 7,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"+ "cell_type": "markdown",+ "metadata": {+ "id": "2XXT4d1tf7EM"+ },+ "source": [+ "In this tutorial, we will focus on demonstrating how to use the task module in the CAMEL framework. We will guide you through creating, evolving, and decomposing tasks to illustrate how the task module can be utilized for efficient task management in agent-based systems."+ ]},- "id": "ThFlgKehf7EQ",- "outputId": "de37eb43-a0f0-4a58-c65f-1318a0f01916"- },- "outputs": [{- "name": "stdout",- "output_type": "stream",- "text": [- "Task 0.0: Weng earns $12 an hour for babysitting. Yesterday, she babysat for 1 hour and 45 minutes. Additionally, she received a bonus of $5 for excellent service. How much did she earn in total for her babysitting job yesterday?\n",- "\n"- ]+ "cell_type": "markdown",+ "metadata": {+ "id": "ph2dWXb-f7EM"+ },+ "source": [+ "Sections included:\n",+ "\n",+ "- Setting up a ChatAgent with the CAMEL framework\n",+ "- Creating a Task and evolving it with the agent using TaskManager\n",+ "- Task decomposition using the CAMEL task module\n",+ "\n",+ "Let's go step by step!"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "4uoXafBRf7EN"+ },+ "source": [+ "## Step 1: Import necessary CAMEL modules\n",+ "\n",+ "First, we need to import the required CAMEL modules for creating the ChatAgent and handling tasks."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {+ "id": "My_O9chyf7EN"+ },+ "outputs": [],+ "source": [+ "!pip install \"camel-ai==0.2.4\""+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 2,+ "metadata": {+ "id": "3povzm9qf7EO"+ },+ "outputs": [],+ "source": [+ "from camel.agents import ChatAgent\n",+ "from camel.configs import ChatGPTConfig\n",+ "from camel.messages import BaseMessage\n",+ "from camel.models import ModelFactory\n",+ "from camel.tasks import (\n",+ " Task,\n",+ " TaskManager,\n",+ ")\n",+ "from camel.types import (\n",+ " ModelPlatformType,\n",+ " ModelType,\n",+ ")"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "H9ANkBsuf7EO"+ },+ "source": [+ "Set your OpenAI key"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 3,+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "t7u1PNhnf7EO",+ "outputId": "e507099a-cba2-443c-aef1-b015f97aa584"+ },+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Enter your API key: ยทยทยทยทยทยทยทยทยทยท\n"+ ]+ }+ ],+ "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"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "brQ0v3kaf7EP"+ },+ "source": [+ "## Step 2: Set up the Large Language Model (LLM)\n",+ "\n",+ "Next, we set up the model configuration. We are using a GPT-4O Mini in this case for our assistant agent. The configuration is designed to ensure the agentโs behavior remains deterministic by setting temperature=0.0, meaning no randomness will be introduced in the responses."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 5,+ "metadata": {+ "id": "DLXsqm7mf7EP"+ },+ "outputs": [],+ "source": [+ "# Create the model using the configuration\n",+ "model = ModelFactory.create(\n",+ " model_platform=ModelPlatformType.OPENAI,\n",+ " model_type=ModelType.GPT_4O_MINI,\n",+ " model_config_dict=ChatGPTConfig(temperature=0.0).as_dict(), # [Optional] the config for model\n",+ ")"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "IAstp4cyf7EP"+ },+ "source": [+ "## Step 3: Initialize the ChatAgent\n",+ "\n",+ "We now create a ChatAgent using the previously defined model. This agent will interact with tasks in the CAMEL framework, following the role of a personal math tutor and programmer."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 6,+ "metadata": {+ "id": "rSo-keNnf7EP"+ },+ "outputs": [],+ "source": [+ "# Set up the assistant's system message\n",+ "assistant_sys_msg = BaseMessage.make_user_message(\n",+ " role_name=\"Teacher\",\n",+ " content=\"You are a personal math tutor and programmer.\",\n",+ ")\n",+ "\n",+ "# Initialize the ChatAgent\n",+ "agent = ChatAgent(assistant_sys_msg, model)\n",+ "agent.reset() # Reset the agent's internal state"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "b-RGszDYf7EP"+ },+ "source": [+ "## Step 4: Evolve and decompose tasks\n",+ "\n",+ "We now create a Task that represents a math problem for the assistant to solve. In this case, we are asking the assistant to calculate how much Weng earned for babysitting based on her hourly rate and the time she worked."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 7,+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "YZ8TaZzjf7EQ",+ "outputId": "c30e51d5-7ae7-41f6-825f-28e654bffc40"+ },+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Task 0: Weng earns $12 an hour for babysitting. Yesterday, she just did 51 minutes of babysitting. How much did she earn?\n",+ "\n"+ ]+ }+ ],+ "source": [+ "# Create a Task for the agent to solve\n",+ "task = Task(\n",+ " content=\"Weng earns $12 an hour for babysitting. Yesterday, she just did 51 minutes of babysitting. How much did she earn?\",\n",+ " id=\"0\", # Task identifier\n",+ ")\n",+ "\n",+ "# Print the task to see the original form\n",+ "print(task.to_string())"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "R1xHH7UAf7EQ"+ },+ "source": [+ "### Evolve the Task\n",+ "\n",+ "We can evolve the task using the TaskManager, which allows the agent to potentially update or reframe the task based on its internal logic and context."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 8,+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "ThFlgKehf7EQ",+ "outputId": "3811ae11-1c78-4b3a-e011-e5430f9dd11c"+ },+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Task 0.0: Weng earns $12 an hour for babysitting. Yesterday, she babysat for 1 hour and 45 minutes. If she also received a bonus of $5 for exceptional service, how much did she earn in total?\n",+ "\n"+ ]+ }+ ],+ "source": [+ "task_manager = TaskManager(task)\n",+ "\n",+ "evolved_task = task_manager.evolve(task, agent=agent)\n",+ "if evolved_task is not None:\n",+ " print(evolved_task.to_string())\n",+ "else:\n",+ " print(\"Evolved task is None.\")"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "b_6IxCWPf7EQ"+ },+ "source": [+ "### Decompose the Task\n",+ "\n",+ "Sometimes, tasks are complex and need to be broken down into smaller subtasks. We use decompose() to allow the agent to split the original task into simpler parts."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 9,+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "bWNpUckzf7EQ",+ "outputId": "4012310b-6210-4360-aef1-9620bd621785"+ },+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Task 0.0: Convert the babysitting time from minutes to hours.\n",+ "\n",+ "Task 0.1: Calculate the earnings based on the hourly rate of $12 and the converted time in hours.\n",+ "\n",+ "Task 0.2: Present the final earnings amount clearly.\n",+ "\n"+ ]+ }+ ],+ "source": [+ "new_tasks = task.decompose(agent=agent)\n",+ "for t in new_tasks:\n",+ " print(t.to_string())"+ ]}- ],- "source": [- "task_manager = TaskManager(task)\n",- "\n",- "evolved_task = task_manager.evolve(task, agent=agent)\n",- "if evolved_task is not None:\n",- " print(evolved_task.to_string())\n",- "else:\n",- " print(\"Evolved task is None.\")"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "b_6IxCWPf7EQ"- },- "source": [- "### Decompose the Task\n",- "\n",- "Sometimes, tasks are complex and need to be broken down into smaller subtasks. We use decompose() to allow the agent to split the original task into simpler parts."- ]- },- {- "cell_type": "code",- "execution_count": 8,- "metadata": {+ ],+ "metadata": {"colab": {- "base_uri": "https://localhost:8080/"+ "provenance": []},- "id": "bWNpUckzf7EQ",- "outputId": "15e70418-792b-46c5-f46e-bbadf70daefd"- },- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "Task 0.0: Convert the babysitting time from minutes to hours.\n",- "\n",- "Task 0.1: Calculate the earnings based on the hourly rate of $12 and the converted time in hours.\n",- "\n",- "Task 0.2: Present the final earnings amount clearly.\n",- "\n"- ]+ "kernelspec": {+ "display_name": "Python 3",+ "name": "python3"+ },+ "language_info": {+ "name": "python"}- ],- "source": [- "new_tasks = task.decompose(agent=agent)\n",- "for t in new_tasks:\n",- " print(t.to_string())"- ]- }- ],- "metadata": {- "colab": {- "provenance": []- },- "kernelspec": {- "display_name": "Python 3",- "name": "python3"},- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 0+ "nbformat": 4,+ "nbformat_minor": 0}diff --git a/docs/get_started/installation.md b/docs/get_started/installation.mdindex 1a2faa178..3c72324ea 100644--- a/docs/get_started/installation.md+++ b/docs/get_started/installation.md@@ -60,7 +60,7 @@ conda create --name camel python=3.10conda activate camel# Clone github repo-git clone -b v0.2.4a1 https://github.com/camel-ai/camel.git+git clone -b v0.2.4 https://github.com/camel-ai/camel.git# Change directory into project directorycd cameldiff --git a/pyproject.toml b/pyproject.tomlindex de6dedeea..63a378532 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "poetry.core.masonry.api"[tool.poetry]name = "camel-ai"-version = "0.2.4a1"+version = "0.2.4"authors = ["CAMEL-AI.org"]description = "Communicative Agents for AI Society Study"readme = "README.md"