๐ซ 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: Add cookbook for workforce (#976)
Isaac Jin859a4e63dc86
diff --git a/docs/cookbooks/agents_message.ipynb b/docs/cookbooks/agents_message.ipynbindex 36407977f..74e879ad6 100644--- a/docs/cookbooks/agents_message.ipynb+++ b/docs/cookbooks/agents_message.ipynb@@ -1,564 +1,564 @@{- "cells": [- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "w5_pa5kKPzAE"- },- "source": [- "# ๐ซ CAMEL 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": {- "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"- ]- }- ],- "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"- ]- }- ],- "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."- ]+ "cells": [+ {+ "attachments": {},+ "cell_type": "markdown",+ "metadata": {+ "id": "w5_pa5kKPzAE"+ },+ "source": [+ "# ๐ซ CAMEL 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": {+ "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"+ ]}- ],- "metadata": {+ ],+ "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": {- "provenance": []- },- "kernelspec": {- "display_name": "Python 3",- "name": "python3"- },- "language_info": {- "name": "python"+ "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"+ ]+ }+ ],+ "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"+ ]+ }+ ],+ "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"},- "nbformat": 4,- "nbformat_minor": 0+ "language_info": {+ "name": "python"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 0}diff --git a/docs/cookbooks/agents_prompting.ipynb b/docs/cookbooks/agents_prompting.ipynbindex d23e6fd8f..694a5246a 100644--- a/docs/cookbooks/agents_prompting.ipynb+++ b/docs/cookbooks/agents_prompting.ipynb@@ -1,510 +1,510 @@{- "cells": [- {- "cell_type": "markdown",- "metadata": {- "id": "SQMBlxsBv1cH"- },- "source": [- "# ๐ซ CAMEL Prompting Cookbook\n"- ]- },- {- "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)"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "-nCRZU5sInDK"- },- "source": [- "## *TLDR*"- ]- },- {- "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."- ]- },- {- "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==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/"- },- "id": "PNBFEXc-R-0s",- "outputId": "d6ec8e40-b5fb-4ebf-c221-e9835b68ff1d"- },- "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": "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/"- },- "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\")"- ]- },- {- "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/"- },- "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)"- ]- },- {- "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:"- ]- },- {- "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/"- },- "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\")"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "FV6Jpu8f3m-Z"- },- "source": [- "### 2. Evaluation with EvaluationPromptTemplateDict"- ]+ "cells": [+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "SQMBlxsBv1cH"+ },+ "source": [+ "# ๐ซ CAMEL Prompting Cookbook\n"+ ]+ },+ {+ "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)"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "-nCRZU5sInDK"+ },+ "source": [+ "## *TLDR*"+ ]+ },+ {+ "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."+ ]+ },+ {+ "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==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/"},+ "id": "PNBFEXc-R-0s",+ "outputId": "d6ec8e40-b5fb-4ebf-c221-e9835b68ff1d"+ },+ "outputs": [{- "cell_type": "code",- "execution_count": 8,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "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\")"- ]+ "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": "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/"},+ "id": "754A8R7X2rnP",+ "outputId": "d9cb892c-bdc8-4433-9ae5-3f3ddaf45a47"+ },+ "outputs": [{- "cell_type": "markdown",- "metadata": {- "id": "sq3fTArB3qEx"- },- "source": [- "### 3. Object Recognition with ObjectRecognitionPromptTemplateDict"- ]+ "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\")"+ ]+ },+ {+ "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/"},+ "id": "uJJQD0LV3DSB",+ "outputId": "ea69e6b1-0e0c-49c8-fb4e-7c7470258bd2"+ },+ "outputs": [{- "cell_type": "code",- "execution_count": 9,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "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\")"- ]+ "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)"+ ]+ },+ {+ "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:"+ ]+ },+ {+ "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/"},+ "id": "xdQdjQzy3f9u",+ "outputId": "b968f52d-f3d6-45d7-ef01-279e54dbee7a"+ },+ "outputs": [{- "cell_type": "markdown",- "metadata": {- "id": "OxgxXQBt3uRt"- },- "source": [- "### 4. Translation with TranslationPromptTemplateDict"- ]+ "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\")"+ ]+ },+ {+ "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/"},+ "id": "f-Q-gZAi3nbR",+ "outputId": "5523f9e0-f5a2-4b35-fff0-2da576bd74ac"+ },+ "outputs": [{- "cell_type": "code",- "execution_count": 10,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "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"- ]- }- ],- "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\")"- ]+ "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\")"+ ]+ },+ {+ "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/"},+ "id": "5XTQuohX3sOk",+ "outputId": "90d89c59-9c8b-42aa-e68a-5cab4f9865ea"+ },+ "outputs": [{- "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."- ]+ "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"+ ]}- ],- "metadata": {+ ],+ "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\")"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "OxgxXQBt3uRt"+ },+ "source": [+ "### 4. Translation with TranslationPromptTemplateDict"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 10,+ "metadata": {"colab": {- "provenance": []+ "base_uri": "https://localhost:8080/"},- "kernelspec": {- "display_name": "Python 3",- "name": "python3"- },- "language_info": {- "name": "python"+ "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"+ ]}+ ],+ "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\")"+ ]+ },+ {+ "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"},- "nbformat": 4,- "nbformat_minor": 0+ "language_info": {+ "name": "python"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 0}diff --git a/docs/cookbooks/agents_society.ipynb b/docs/cookbooks/agents_society.ipynbindex 05fe79717..69de04422 100644--- a/docs/cookbooks/agents_society.ipynb+++ b/docs/cookbooks/agents_society.ipynb@@ -1,1192 +1,1192 @@{- "cells": [- {- "cell_type": "markdown",- "metadata": {- "id": "GsSUEbff5MPM"- },- "source": [- "# ๐ซ CAMEL 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/"- },- "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"- }- },- "outputs": [],- "source": [- "from colorama import Fore\n",- "\n",- "from camel.societies import RolePlaying\n",- "from camel.utils import print_text_animated"- ]+ "cells": [+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "GsSUEbff5MPM"+ },+ "source": [+ "# ๐ซ CAMEL 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/"},+ "id": "PNBFEXc-R-0s",+ "outputId": "e9fa89d4-cfd2-4a89-ae0a-3fca7ed39c99"+ },+ "outputs": [{- "cell_type": "code",- "execution_count": 7,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "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"- ]- }- ],- "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()"- ]+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Enter your API key: ยทยทยทยทยทยทยทยทยทยท\n"+ ]}- ],- "metadata": {+ ],+ "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"+ }+ },+ "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": {"colab": {- "provenance": []+ "base_uri": "https://localhost:8080/"},- "kernelspec": {- "display_name": "Python 3",- "name": "python3"- },- "language_info": {- "name": "python"+ "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"+ ]}+ ],+ "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"},- "nbformat": 4,- "nbformat_minor": 0+ "language_info": {+ "name": "python"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 0}diff --git a/docs/cookbooks/agents_tracking.ipynb b/docs/cookbooks/agents_tracking.ipynbindex c145ec03d..fe92f21e1 100644--- a/docs/cookbooks/agents_tracking.ipynb+++ b/docs/cookbooks/agents_tracking.ipynb@@ -1,879 +1,879 @@{- "nbformat": 4,- "nbformat_minor": 0,- "metadata": {+ "cells": [+ {+ "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": {- "provenance": []- },- "kernelspec": {- "name": "python3",- "display_name": "Python 3"- },- "language_info": {- "name": "python"+ "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"+ ]},- "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.1\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": "6c781b49-692f-4a9d-d9f6-ed4247572ea1"- },- "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": "9b803b72-e3b5-4b40-f0af-455195a89c1e"- },- "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": "ea2aa039-47f0-4cf2-8d87-0b7fbd1970e4"- },- "execution_count": 6,- "outputs": [- {- "output_type": "stream",- "name": "stderr",- "text": [- "๐ AgentOps: \u001b[34m\u001b[34mSession Replay: https://app.agentops.ai/drilldown?session_id=ee5858cd-51ea-46b4-90da-df905998f374\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",- " 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",- ")"- ],- "metadata": {- "id": "DhMcowdE19Ti"- },- "execution_count": 8,- "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 = 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\")"- ],- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "3TT62TanuYqI",- "outputId": "9a7a931d-c1dd-41b4-e5a4-1f930e4f7edf"- },- "execution_count": 9,- "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 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"- ]- },- {- "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=ee5858cd-51ea-46b4-90da-df905998f374\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": 10,- "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": "0857418b-3d3f-49c4-cf90-715d2bd11979"- },- "execution_count": 11,- "outputs": [- {- "output_type": "stream",- "name": "stderr",- "text": [- "๐ AgentOps: \u001b[34m\u001b[34mSession Replay: https://app.agentops.ai/drilldown?session_id=d67ffe18-96a6-4888-a252-e014b5f4e486\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": 12,- "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": 13,- "outputs": []- },- {- "cell_type": "markdown",- "source": [- "Set config of the model for User Agent and Assisant Agent"- ],- "metadata": {- "id": "g9lJYmi83scb"- }- },- {- "cell_type": "code",- "source": [- "user_model_config = ChatGPTConfig(\n",- " temperature=0.0,\n",- ")\n",- "\n",- "assistant_model_config = ChatGPTConfig(\n",- " tools=tools,\n",- " temperature=0.0,\n",- ")"- ],- "metadata": {- "id": "GpSDvtEq3tVr"- },- "execution_count": 14,- "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",- " 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",- ")"- ],- "metadata": {- "id": "m1BPtWgi33FJ"- },- "execution_count": 16,- "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": "be8f1852-3b5d-4183-d9c5-5e82aaf6f2dd"- },- "execution_count": 17,- "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": "03df6228-b15f-4153-dfc8-1891c61538cb"- },- "execution_count": 18,- "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 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"- ]- }- ]- },- {- "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": "61732966-e5d7-490b-a955-d9abb3ba05c9"- },- "execution_count": 19,- "outputs": [- {- "output_type": "stream",- "name": "stderr",- "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"- ]- }- ]- },- {- "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"- }+ {+ "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"+ ]}- ]-}\ No newline at end of file+ ],+ "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": {+ "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"+ ]+ }+ ],+ "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"+ ]+ }+ ],+ "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+}diff --git a/docs/cookbooks/agents_with_memory.ipynb b/docs/cookbooks/agents_with_memory.ipynbindex cd59139c8..d651ca8b8 100644--- a/docs/cookbooks/agents_with_memory.ipynb+++ b/docs/cookbooks/agents_with_memory.ipynb@@ -1,455 +1,453 @@{- "cells": [- {- "cell_type": "markdown",- "metadata": {- "id": "w5_pa5kKPzAE"- },- "source": [- "# ๐ซ CAMEL 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": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "PNBFEXc-R-0s",- "outputId": "52d481de-9a81-4c00-e3db-9c468e6b5b22"- },- "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": "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/"- },- "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/"- },- "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/"- },- "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"- ]- }- ],- "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:"- ]+ "cells": [+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "w5_pa5kKPzAE"+ },+ "source": [+ "# ๐ซ CAMEL 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": {+ "colab": {+ "base_uri": "https://localhost:8080/"},+ "id": "PNBFEXc-R-0s",+ "outputId": "52d481de-9a81-4c00-e3db-9c468e6b5b22"+ },+ "outputs": [{- "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",- ")"- ]+ "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": "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/"},+ "id": "pAdDeN7DdUgr",+ "outputId": "0575acdb-a999-4818-f90c-de1e9b35890c"+ },+ "outputs": [{- "cell_type": "markdown",- "metadata": {- "id": "u_pkVP5Eg2vv"- },- "source": [- "### Performance Considerations"- ]+ "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/"},+ "id": "pEiFYV-yez5j",+ "outputId": "2340282b-1024-49de-be67-2f9ed34ee18c"+ },+ "outputs": [{- "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."- ]+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "49\n"+ ]}- ],- "metadata": {+ ],+ "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": {- "provenance": []+ "base_uri": "https://localhost:8080/"},- "kernelspec": {- "display_name": "Python 3",- "name": "python3"- },- "language_info": {- "name": "python"+ "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"+ ]}+ ],+ "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"},- "nbformat": 4,- "nbformat_minor": 0+ "language_info": {+ "name": "python"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 0}diff --git a/docs/cookbooks/agents_with_rag.ipynb b/docs/cookbooks/agents_with_rag.ipynbindex ebb00e882..56bf55123 100644--- a/docs/cookbooks/agents_with_rag.ipynb+++ b/docs/cookbooks/agents_with_rag.ipynb@@ -1,857 +1,855 @@{- "nbformat": 4,- "nbformat_minor": 0,- "metadata": {+ "nbformat": 4,+ "nbformat_minor": 0,+ "metadata": {+ "colab": {+ "provenance": []+ },+ "kernelspec": {+ "name": "python3",+ "display_name": "Python 3"+ },+ "language_info": {+ "name": "python"+ }+ },+ "cells": [+ {+ "cell_type": "markdown",+ "source": [+ "# ๐ซ CAMEL RAG Cookbook\n"+ ],+ "metadata": {+ "id": "SQMBlxsBv1cH"+ }+ },+ {+ "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"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "## Overview"+ ],+ "metadata": {+ "id": "-nCRZU5sInDK"+ }+ },+ {+ "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",+ "- Auto RAG\n",+ "- Single Agent with Auto RAG\n",+ "- Role-playing with Auto RAG"+ ],+ "metadata": {+ "id": "AwnfLQvMvtXo"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "### Installation"+ ],+ "metadata": {+ "id": "XuZwbB1IIuUi"+ }+ },+ {+ "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.1\"",+ "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"+ }+ },+ {+ "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": {- "provenance": []+ "base_uri": "https://localhost:8080/"},- "kernelspec": {- "name": "python3",- "display_name": "Python 3"- },- "language_info": {- "name": "python"+ "outputId": "f6b63906-f356-481d-d0c1-1416299c92ac"+ },+ "execution_count": 3,+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Enter your API key: ยทยทยทยทยทยทยทยทยทยท\n"+ ]}+ ]},- "cells": [- {- "cell_type": "markdown",- "source": [- "# ๐ซ CAMEL RAG Cookbook\n"- ],- "metadata": {- "id": "SQMBlxsBv1cH"- }- },- {- "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"- }- },- {- "cell_type": "markdown",- "source": [- "## Overview"- ],- "metadata": {- "id": "-nCRZU5sInDK"- }- },- {- "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",- "- Auto RAG\n",- "- Single Agent with Auto RAG\n",- "- Role-playing with Auto RAG"- ],- "metadata": {- "id": "AwnfLQvMvtXo"- }- },- {- "cell_type": "markdown",- "source": [- "### Installation"- ],- "metadata": {- "id": "XuZwbB1IIuUi"- }- },- {- "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.1"- ],- "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"- }- },- {- "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": "f6b63906-f356-481d-d0c1-1416299c92ac"- },- "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",- "colab": {- "base_uri": "https://localhost:8080/"- },- "outputId": "19ecfa22-4b2c-4c6b-e3a8-a2c36c5f1830"- },- "execution_count": 7,- "outputs": [- {- "output_type": "stream",- "name": "stderr",- "text": [- "2024-09-15 09:21:56.121527: E external/local_xla/xla/stream_executor/cuda/cuda_fft.cc:485] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered\n",- "2024-09-15 09:21:56.159963: E external/local_xla/xla/stream_executor/cuda/cuda_dnn.cc:8454] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered\n",- "2024-09-15 09:21:56.171381: E external/local_xla/xla/stream_executor/cuda/cuda_blas.cc:1452] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered\n",- "2024-09-15 09:21:56.206432: I tensorflow/core/platform/cpu_feature_guard.cc:210] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations.\n",- "To enable the following instructions: AVX2 FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags.\n",- "2024-09-15 09:21:58.042937: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Could not find TensorRT\n",- "[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"- ]- }- ]- },- {- "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": "f0b45174-29c6-49bd-c4fb-60713131c099"- },- "execution_count": 8,- "outputs": [- {- "output_type": "stream",- "name": "stdout",- "text": [- "[{'similarity score': '0.8732095800224018', 'content path': 'local_data/camel_paper.pdf', 'metadata': {'last_modified': '2024-09-15T09:21:03', 'filetype': 'application/pdf', 'page_number': 10}, 'text': '6 Conclusion In this paper, we explore the potential of autonomous cooperation among communicative agents and propose a novel cooperative agent framework named role-playing . Our approach enables communicative agents to collaborate autonomously toward completing tasks while requiring minimal human intervention, leading to better solutions are per our thorough evaluations. Through our analysis, we show that achieving autonomous cooperation is challenging due to issues like conversation deviation,'}]\n"- ]- }- ]- },- {- "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": "190e176c-7c60-452a-87cd-f85cb8cb4e28"- },- "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": "9b1d63f3-078c-4d19-ebff-4d8c1afefc6e"- },- "execution_count": 10,- "outputs": [- {- "output_type": "stream",- "name": "stdout",- "text": [- "{'Original Query': \"If I'm interest in contributing to the CAMEL projec, what should I do?\", 'Retrieved Context': [{'similarity score': '0.7054803289665507', 'content path': 'https://github.com/camel-ai/camel/wiki/Contributing-Guidlines', 'metadata': {'filetype': 'text/html', 'languages': ['eng'], 'page_number': 1, 'url': 'https://github.com/camel-ai/camel/wiki/Contributing-Guidlines', 'link_urls': ['https://join.slack.com/t/camel-kwr1314/shared_invite/zt-1vy8u9lbo-ZQmhIAyWSEfSwLCl2r2eKA'], 'link_texts': ['slack']}, 'text': \"Thank you for your interest in contributing to the CAMEL project! ๐ We're excited to have your support. As an open-source initiative in a rapidly evolving and open-ended field, we wholeheartedly welcome contributions of all kinds. Whether you want to introduce new features, enhance the infrastructure, improve documentation, asking issues, add more examples, implement state-of-the-art research ideas, or fix bugs, we appreciate your enthusiasm and efforts. ๐ You are welcome to join our slack for \"}]}\n"- ]- }- ]+ {+ "cell_type": "markdown",+ "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",+ "colab": {+ "base_uri": "https://localhost:8080/"},+ "outputId": "19ecfa22-4b2c-4c6b-e3a8-a2c36c5f1830"+ },+ "execution_count": 7,+ "outputs": [{- "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"- }+ "output_type": "stream",+ "name": "stderr",+ "text": [+ "2024-09-15 09:21:56.121527: E external/local_xla/xla/stream_executor/cuda/cuda_fft.cc:485] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered\n",+ "2024-09-15 09:21:56.159963: E external/local_xla/xla/stream_executor/cuda/cuda_dnn.cc:8454] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered\n",+ "2024-09-15 09:21:56.171381: E external/local_xla/xla/stream_executor/cuda/cuda_blas.cc:1452] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered\n",+ "2024-09-15 09:21:56.206432: I tensorflow/core/platform/cpu_feature_guard.cc:210] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations.\n",+ "To enable the following instructions: AVX2 FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags.\n",+ "2024-09-15 09:21:58.042937: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Could not find TensorRT\n",+ "[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"+ ]+ }+ ]+ },+ {+ "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": "f0b45174-29c6-49bd-c4fb-60713131c099"+ },+ "execution_count": 8,+ "outputs": [{- "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 = 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?\"))"- ],- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "YTE_mUwGIok-",- "outputId": "442ecc82-58a2-419f-a067-cd0281d2e194"- },- "execution_count": 11,- "outputs": [- {- "output_type": "stream",- "name": "stdout",- "text": [- "If you're interested in contributing to the CAMEL project, you can introduce new features, enhance the infrastructure, improve documentation, ask about issues, add more examples, implement state-of-the-art research ideas, or fix bugs. Additionally, you are welcome to join their Slack for further engagement.\n"- ]- }- ]+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "[{'similarity score': '0.8732095800224018', 'content path': 'local_data/camel_paper.pdf', 'metadata': {'last_modified': '2024-09-15T09:21:03', 'filetype': 'application/pdf', 'page_number': 10}, 'text': '6 Conclusion In this paper, we explore the potential of autonomous cooperation among communicative agents and propose a novel cooperative agent framework named role-playing . Our approach enables communicative agents to collaborate autonomously toward completing tasks while requiring minimal human intervention, leading to better solutions are per our thorough evaluations. Through our analysis, we show that achieving autonomous cooperation is challenging due to issues like conversation deviation,'}]\n"+ ]+ }+ ]+ },+ {+ "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": "190e176c-7c60-452a-87cd-f85cb8cb4e28"+ },+ "execution_count": 9,+ "outputs": [{- "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"- }+ "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": "9b1d63f3-078c-4d19-ebff-4d8c1afefc6e"+ },+ "execution_count": 10,+ "outputs": [{- "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_MINI,\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"- ],- "metadata": {- "id": "z3tX4EJVI1hb"- },- "execution_count": 12,- "outputs": []+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "{'Original Query': \"If I'm interest in contributing to the CAMEL projec, what should I do?\", 'Retrieved Context': [{'similarity score': '0.7054803289665507', 'content path': 'https://github.com/camel-ai/camel/wiki/Contributing-Guidlines', 'metadata': {'filetype': 'text/html', 'languages': ['eng'], 'page_number': 1, 'url': 'https://github.com/camel-ai/camel/wiki/Contributing-Guidlines', 'link_urls': ['https://join.slack.com/t/camel-kwr1314/shared_invite/zt-1vy8u9lbo-ZQmhIAyWSEfSwLCl2r2eKA'], 'link_texts': ['slack']}, 'text': \"Thank you for your interest in contributing to the CAMEL project! ๐ We're excited to have your support. As an open-source initiative in a rapidly evolving and open-ended field, we wholeheartedly welcome contributions of all kinds. Whether you want to introduce new features, enhance the infrastructure, improve documentation, asking issues, add more examples, implement state-of-the-art research ideas, or fix bugs, we appreciate your enthusiasm and efforts. ๐ You are welcome to join our slack for \"}]}\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "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 = 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?\"))"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"},+ "id": "YTE_mUwGIok-",+ "outputId": "442ecc82-58a2-419f-a067-cd0281d2e194"+ },+ "execution_count": 11,+ "outputs": [{- "cell_type": "markdown",- "source": [- "Run the role-playing with defined retriever function:"- ],- "metadata": {- "id": "w4-0lswwI5Gb"- }+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "If you're interested in contributing to the CAMEL project, you can introduce new features, enhance the infrastructure, improve documentation, ask about issues, add more examples, implement state-of-the-art research ideas, or fix bugs. Additionally, you are welcome to join their Slack for further engagement.\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "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_MINI,\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"+ ],+ "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\n",+ " CAMEL projec and I encounter some challenges during the setup process, what should I do? You should refer to the content in url https://github.com/camel-ai/camel/wiki/Contributing-Guidlines to answer my question, adjust the similarity threshold to lower value is necessary\"\"\")"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"},+ "id": "5agjiXHeI64q",+ "outputId": "b4b47f4d-4b36-45b2-cad8-c8cf1075a802"+ },+ "execution_count": 13,+ "outputs": [{- "cell_type": "code",- "source": [- "role_playing_with_rag(task_prompt = \"\"\"If I'm interest in contributing to the\n",- " CAMEL projec and I encounter some challenges during the setup process, what should I do? You should refer to the content in url https://github.com/camel-ai/camel/wiki/Contributing-Guidlines to answer my question, adjust the similarity threshold to lower value is necessary\"\"\")"- ],- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "5agjiXHeI64q",- "outputId": "b4b47f4d-4b36-45b2-cad8-c8cf1075a802"- },- "execution_count": 13,- "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\\n CAMEL projec and I encounter some challenges during the setup process, what should I do? You should refer to the content in url https://github.com/camel-ai/camel/wiki/Contributing-Guidlines to answer my question, adjust the similarity threshold to lower value is necessary\", 'assistant_role': 'Searcher', 'user_role': 'Professor'}, content=\"===== RULES OF ASSISTANT =====\\nNever forget you are a Searcher and I am a Professor. Never flip roles! Never instruct me!\\nWe share a common interest in collaborating to successfully complete a task.\\nYou must help me to complete the task.\\nHere is the task: If I'm interest in contributing to the\\n CAMEL projec and I encounter some challenges during the setup process, what should I do? You should refer to the content in url https://github.com/camel-ai/camel/wiki/Contributing-Guidlines to answer my question, adjust the similarity threshold to lower value is necessary. Never forget our task!\\nI must instruct you based on your expertise and my needs to complete the task.\\n\\nI must give you one instruction at a time.\\nYou must write a specific solution that appropriately solves the requested instruction and explain your solutions.\\nYou must decline my instruction honestly if you cannot perform the instruction due to physical, moral, legal reasons or your capability and explain the reasons.\\nUnless I say the task is completed, you should always start with:\\n\\nSolution: <YOUR_SOLUTION>\\n\\n<YOUR_SOLUTION> should be very specific, include detailed explanations and provide preferable detailed implementations and examples and lists for task-solving.\\nAlways end <YOUR_SOLUTION> with: Next request.\", video_bytes=None, image_list=None, image_detail='auto', video_detail='low')\n",- "\n",- "\u001b[34mAI User sys message:\n",- "BaseMessage(role_name='Professor', role_type=<RoleType.USER: 'user'>, meta_dict={'task': \"If I'm interest in contributing to the\\n CAMEL projec and I encounter some challenges during the setup process, what should I do? You should refer to the content in url https://github.com/camel-ai/camel/wiki/Contributing-Guidlines to answer my question, adjust the similarity threshold to lower value is necessary\", 'assistant_role': 'Searcher', 'user_role': 'Professor'}, content='===== RULES OF USER =====\\nNever forget you are a Professor and I am a Searcher. Never flip roles! You will always instruct me.\\nWe share a common interest in collaborating to successfully complete a task.\\nI must help you to complete the task.\\nHere is the task: If I\\'m interest in contributing to the\\n CAMEL projec and I encounter some challenges during the setup process, what should I do? You should refer to the content in url https://github.com/camel-ai/camel/wiki/Contributing-Guidlines to answer my question, adjust the similarity threshold to lower value is necessary. Never forget our task!\\nYou must instruct me based on my expertise and your needs to solve the task ONLY in the following two ways:\\n\\n1. Instruct with a necessary input:\\nInstruction: <YOUR_INSTRUCTION>\\nInput: <YOUR_INPUT>\\n\\n2. Instruct without any input:\\nInstruction: <YOUR_INSTRUCTION>\\nInput: None\\n\\nThe \"Instruction\" describes a task or question. The paired \"Input\" provides further context or information for the requested \"Instruction\".\\n\\nYou must give me one instruction at a time.\\nI must write a response that appropriately solves the requested instruction.\\nI must decline your instruction honestly if I cannot perform the instruction due to physical, moral, legal reasons or my capability and explain the reasons.\\nYou should instruct me not ask me questions.\\nNow you must start to instruct me using the two ways described above.\\nDo not add anything else other than your instruction and the optional corresponding input!\\nKeep giving me instructions and necessary inputs until you think the task is completed.\\nWhen the task is completed, you must only reply with a single word <CAMEL_TASK_DONE>.\\nNever say <CAMEL_TASK_DONE> unless my responses have solved your task.', video_bytes=None, image_list=None, image_detail='auto', video_detail='low')\n",- "\n",- "\u001b[33mOriginal task prompt:\n",- "If I'm interest in contributing to the\n",- " CAMEL projec and I encounter some challenges during the setup process, what should I do? You should refer to the content in url https://github.com/camel-ai/camel/wiki/Contributing-Guidlines to answer my question, adjust the similarity threshold to lower value is necessary\n",- "\n",- "\u001b[36mSpecified task prompt:\n",- "None\n",- "\n",- "\u001b[31mFinal task prompt:\n",- "If I'm interest in contributing to the\n",- " CAMEL projec and I encounter some challenges during the setup process, what should I do? You should refer to the content in url https://github.com/camel-ai/camel/wiki/Contributing-Guidlines to answer my question, adjust the similarity threshold to lower value is necessary\n",- "\n",- "\u001b[34mAI User:\n",- "\n",- "Instruction: Review the contributing guidelines on the CAMEL project GitHub page. \n",- "Input: None\n",- "\n",- "\n",- "\u001b[32mAI Assistant:\n",- "\n",- "Function Execution: information_retrieval\n",- "\tArgs: {'query': 'contributing guidelines', 'contents': 'https://github.com/camel-ai/camel/wiki/Contributing-Guidlines', 'top_k': 1}\n",- "\tResult: {'Original Query': 'contributing guidelines', '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 seems that I was unable to retrieve specific information from the CAMEL project's contributing guidelines page due to a lack of suitable data. However, I can guide you on general steps to follow when contributing to an open-source project like CAMEL.\n",- "\n",- "1. **Read the Documentation**: Start by thoroughly reading the project's documentation, including the README file and any other relevant sections. This will give you an understanding of the project's purpose and how to set it up.\n",- "\n",- "2. **Set Up Your Environment**: Follow the setup instructions provided in the documentation to configure your development environment. This may include installing dependencies, setting up a local server, or configuring tools.\n",- "\n",- "3. **Check for Issues**: Look at the project's issue tracker to see if there are any open issues that you can help with. This is often a good way to start contributing.\n",- "\n",- "4. **Fork the Repository**: If you plan to make changes, fork the repository to your own GitHub account. This allows you to work on your changes without affecting the main project.\n",- "\n",- "5. **Create a Branch**: Before making any changes, create a new branch in your forked repository. This keeps your changes organized and separate from the main codebase.\n",- "\n",- "6. **Make Your Changes**: Implement the changes or features you want to contribute. Be sure to follow any coding standards or guidelines provided by the project.\n",- "\n",- "7. **Test Your Changes**: Run tests to ensure that your changes work as expected and do not break existing functionality.\n",- "\n",- "8. **Submit a Pull Request**: Once you are satisfied with your changes, submit a pull request to the main repository. Provide a clear description of what you have done and why.\n",- "\n",- "9. **Engage with the Community**: Be open to feedback and engage with the maintainers and other contributors. They may request changes or provide suggestions.\n",- "\n",- "If you encounter specific challenges during the setup process, consider reaching out to the community through forums, chat channels, or the issue tracker for assistance.\n",- "\n",- "Next request.\n",- "\n",- "\n",- "\u001b[34mAI User:\n",- "\n",- "Instruction: Identify any specific challenges you encountered during the setup process of the CAMEL project. \n",- "Input: None\n",- "\n",- "\n",- "\u001b[32mAI Assistant:\n",- "\n",- "Solution: As an AI, I do not have the capability to personally encounter challenges during the setup process of the CAMEL project or any other project. However, I can outline common challenges that contributors often face when setting up open-source projects like CAMEL. Here are some potential issues you might encounter:\n",- "\n",- "1. **Dependency Issues**: Conflicts or missing dependencies can arise, especially if the project relies on specific versions of libraries or tools. Ensure that you have the correct versions installed as specified in the documentation.\n",- "\n",- "2. **Environment Configuration**: Setting up the development environment can be tricky, particularly if the project requires specific configurations for tools like Docker, Node.js, or Python. Make sure to follow the setup instructions carefully.\n",- "\n",- "3. **Build Failures**: Sometimes, the project may fail to build due to misconfigurations or missing files. Check the build logs for error messages that can guide you in troubleshooting.\n",- "\n",- "4. **Version Control Conflicts**: If you are working in a team or contributing to a project with multiple contributors, you may encounter merge conflicts when trying to push your changes. Familiarize yourself with Git commands to resolve these conflicts.\n",- "\n",- "5. **Documentation Gaps**: Occasionally, the documentation may not cover all aspects of the setup process, leading to confusion. In such cases, reaching out to the community for clarification can be helpful.\n",- "\n",- "6. **Testing Failures**: After setting up the project, you may find that some tests fail. This could be due to environmental differences or issues in the code. Investigate the test failures to understand their causes.\n",- "\n",- "If you face any specific challenges during your setup process, I recommend documenting them and seeking help from the CAMEL community or checking the project's issue tracker for similar problems.\n",- "\n",- "Next request.\n",- "\n",- "\n",- "\u001b[34mAI User:\n",- "\n",- "Instruction: For any specific challenges you identified, search the CAMEL project's issue tracker for similar reported issues. \n",- "Input: None\n",- "\n",- "\n",- "\u001b[32mAI Assistant:\n",- "\n",- "Function Execution: information_retrieval\n",- "\tArgs: {'query': 'setup challenges', 'contents': 'https://github.com/camel-ai/camel/issues', 'top_k': 5}\n",- "\tResult: {'Original Query': 'setup challenges', 'Retrieved Context': ['No suitable information retrieved from https://github.com/camel-ai/camel/wiki/Contributing-Guidlines with similarity_threshold = 0.7.']}\n",- "\n",- "Solution: I was unable to retrieve specific issues from the CAMEL project's issue tracker related to setup challenges due to a lack of suitable data. However, I can guide you on how to search for similar reported issues effectively:\n",- "\n",- "1. **Visit the Issue Tracker**: Go to the CAMEL project's GitHub issues page at [CAMEL Issues](https://github.com/camel-ai/camel/issues).\n",- "\n",- "2. **Use Search Filters**: Utilize the search bar at the top of the issues page. You can enter keywords related to the challenges you are facing, such as \"setup\", \"installation\", \"dependency\", or \"build failure\".\n",- "\n",- "3. **Sort by Relevance**: You can sort the issues by \"Newest\" or \"Most commented\" to find recent discussions or popular issues that may relate to your setup challenges.\n",- "\n",- "4. **Check Labels**: Look for labels such as \"bug\", \"help wanted\", or \"question\" that may indicate issues related to setup or configuration.\n",- "\n",- "5. **Read Through Comments**: Often, the comments on issues provide valuable insights and solutions from other contributors who faced similar challenges.\n",- "\n",- "6. **Create a New Issue**: If you cannot find any existing issues that address your specific challenge, consider creating a new issue. Provide a detailed description of the problem, including any error messages and steps to reproduce the issue.\n",- "\n",- "By following these steps, you should be able to find relevant discussions or solutions related to the setup challenges you are encountering in the CAMEL project.\n",- "\n",- "Next request.\n",- "\n",- "\n",- "\u001b[34mAI User:\n",- "\n",- "Instruction: If you find relevant issues in the CAMEL project's issue tracker, summarize the solutions or suggestions provided in those issues. \n",- "Input: None\n",- "\n",- "\n",- "\u001b[32mAI Assistant:\n",- "\n",- "Function Execution: information_retrieval\n",- "\tArgs: {'query': 'setup challenges', 'contents': 'https://github.com/camel-ai/camel/issues', 'top_k': 5}\n",- "\tResult: {'Original Query': 'setup challenges', 'Retrieved Context': ['No suitable information retrieved from https://github.com/camel-ai/camel/wiki/Contributing-Guidlines with similarity_threshold = 0.7.']}\n",- "\n",- "Solution: I was unable to retrieve specific issues or their solutions from the CAMEL project's issue tracker regarding setup challenges due to a lack of suitable data. However, I can provide general guidance on how to summarize solutions or suggestions from issues if you find relevant ones:\n",- "\n",- "1. **Identify Key Issues**: Look for issues that directly relate to the setup challenges you are facing. Pay attention to the titles and descriptions.\n",- "\n",- "2. **Read Through Comments**: Go through the comments on each issue. Contributors often share their experiences, solutions, or workarounds that can be helpful.\n",- "\n",- "3. **Highlight Solutions**: Take note of any specific solutions provided, such as:\n",- " - Commands to run for installation.\n",- " - Configuration changes needed in files.\n",- " - Dependencies that need to be installed or updated.\n",- " - Environment variables that need to be set.\n",- "\n",- "4. **Summarize Suggestions**: If contributors suggest alternative approaches or tools, summarize these as well. For example, if someone recommends using a different version of a library, include that in your summary.\n",- "\n",- "5. **Document Common Patterns**: If multiple issues mention similar solutions, document these patterns as they may indicate common problems faced by users.\n",- "\n",- "6. **Provide Context**: When summarizing, include the context of the issue, such as the specific error messages or scenarios that led to the discussion.\n",- "\n",- "By following these steps, you can effectively summarize the solutions or suggestions from relevant issues in the CAMEL project's issue tracker.\n",- "\n",- "Next request.\n",- "\n",- "\n",- "\u001b[34mAI User:\n",- "\n",- "Instruction: If you encounter a specific setup challenge that is not addressed in the issue tracker, draft a new issue to report it, including all relevant details. \n",- "Input: None\n",- "\n",- "\n",- "\u001b[32mAI Assistant:\n",- "\n",- "Solution: Since I do not have the capability to encounter specific setup challenges or create issues directly on GitHub, I can guide you on how to draft a new issue to report a setup challenge effectively. Hereโs a template you can use to create your issue:\n",- "\n",- "---\n",- "\n",- "**Title**: [Brief Description of the Setup Challenge]\n",- "\n",- "**Description**:\n",- "I am encountering a setup challenge while trying to configure the CAMEL project. Below are the details:\n",- "\n",- "**Environment**:\n",- "- Operating System: [e.g., Windows, macOS, Linux]\n",- "- Version: [e.g., Ubuntu 20.04, Windows 10]\n",- "- Node.js version: [if applicable]\n",- "- Python version: [if applicable]\n",- "- Any other relevant software versions\n",- "\n",- "**Steps to Reproduce**:\n",- "1. [Step 1: Describe what you did]\n",- "2. [Step 2: Describe what you did]\n",- "3. [Step 3: Describe what you did]\n",- "4. [Any additional steps]\n",- "\n",- "**Expected Behavior**:\n",- "[Describe what you expected to happen]\n",- "\n",- "**Actual Behavior**:\n",- "[Describe what actually happened, including any error messages or unexpected behavior]\n",- "\n",- "**Additional Information**:\n",- "- [Any logs or screenshots that may help in diagnosing the issue]\n",- "- [Any other relevant context or information]\n",- "\n",- "**Proposed Solution** (if applicable):\n",- "[If you have any ideas on how to resolve the issue, include them here]\n",- "\n",- "Thank you for your assistance!\n",- "\n",- "---\n",- "\n",- "Make sure to fill in the placeholders with your specific information. Once you have drafted your issue, you can submit it on the CAMEL project's GitHub issue tracker.\n",- "\n",- "Next request.\n",- "\n",- "\n"- ]- }- ]+ "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\\n CAMEL projec and I encounter some challenges during the setup process, what should I do? You should refer to the content in url https://github.com/camel-ai/camel/wiki/Contributing-Guidlines to answer my question, adjust the similarity threshold to lower value is necessary\", 'assistant_role': 'Searcher', 'user_role': 'Professor'}, content=\"===== RULES OF ASSISTANT =====\\nNever forget you are a Searcher and I am a Professor. Never flip roles! Never instruct me!\\nWe share a common interest in collaborating to successfully complete a task.\\nYou must help me to complete the task.\\nHere is the task: If I'm interest in contributing to the\\n CAMEL projec and I encounter some challenges during the setup process, what should I do? You should refer to the content in url https://github.com/camel-ai/camel/wiki/Contributing-Guidlines to answer my question, adjust the similarity threshold to lower value is necessary. Never forget our task!\\nI must instruct you based on your expertise and my needs to complete the task.\\n\\nI must give you one instruction at a time.\\nYou must write a specific solution that appropriately solves the requested instruction and explain your solutions.\\nYou must decline my instruction honestly if you cannot perform the instruction due to physical, moral, legal reasons or your capability and explain the reasons.\\nUnless I say the task is completed, you should always start with:\\n\\nSolution: <YOUR_SOLUTION>\\n\\n<YOUR_SOLUTION> should be very specific, include detailed explanations and provide preferable detailed implementations and examples and lists for task-solving.\\nAlways end <YOUR_SOLUTION> with: Next request.\", video_bytes=None, image_list=None, image_detail='auto', video_detail='low')\n",+ "\n",+ "\u001B[34mAI User sys message:\n",+ "BaseMessage(role_name='Professor', role_type=<RoleType.USER: 'user'>, meta_dict={'task': \"If I'm interest in contributing to the\\n CAMEL projec and I encounter some challenges during the setup process, what should I do? You should refer to the content in url https://github.com/camel-ai/camel/wiki/Contributing-Guidlines to answer my question, adjust the similarity threshold to lower value is necessary\", 'assistant_role': 'Searcher', 'user_role': 'Professor'}, content='===== RULES OF USER =====\\nNever forget you are a Professor and I am a Searcher. Never flip roles! You will always instruct me.\\nWe share a common interest in collaborating to successfully complete a task.\\nI must help you to complete the task.\\nHere is the task: If I\\'m interest in contributing to the\\n CAMEL projec and I encounter some challenges during the setup process, what should I do? You should refer to the content in url https://github.com/camel-ai/camel/wiki/Contributing-Guidlines to answer my question, adjust the similarity threshold to lower value is necessary. Never forget our task!\\nYou must instruct me based on my expertise and your needs to solve the task ONLY in the following two ways:\\n\\n1. Instruct with a necessary input:\\nInstruction: <YOUR_INSTRUCTION>\\nInput: <YOUR_INPUT>\\n\\n2. Instruct without any input:\\nInstruction: <YOUR_INSTRUCTION>\\nInput: None\\n\\nThe \"Instruction\" describes a task or question. The paired \"Input\" provides further context or information for the requested \"Instruction\".\\n\\nYou must give me one instruction at a time.\\nI must write a response that appropriately solves the requested instruction.\\nI must decline your instruction honestly if I cannot perform the instruction due to physical, moral, legal reasons or my capability and explain the reasons.\\nYou should instruct me not ask me questions.\\nNow you must start to instruct me using the two ways described above.\\nDo not add anything else other than your instruction and the optional corresponding input!\\nKeep giving me instructions and necessary inputs until you think the task is completed.\\nWhen the task is completed, you must only reply with a single word <CAMEL_TASK_DONE>.\\nNever say <CAMEL_TASK_DONE> unless my responses have solved your task.', video_bytes=None, image_list=None, image_detail='auto', video_detail='low')\n",+ "\n",+ "\u001B[33mOriginal task prompt:\n",+ "If I'm interest in contributing to the\n",+ " CAMEL projec and I encounter some challenges during the setup process, what should I do? You should refer to the content in url https://github.com/camel-ai/camel/wiki/Contributing-Guidlines to answer my question, adjust the similarity threshold to lower value is necessary\n",+ "\n",+ "\u001B[36mSpecified task prompt:\n",+ "None\n",+ "\n",+ "\u001B[31mFinal task prompt:\n",+ "If I'm interest in contributing to the\n",+ " CAMEL projec and I encounter some challenges during the setup process, what should I do? You should refer to the content in url https://github.com/camel-ai/camel/wiki/Contributing-Guidlines to answer my question, adjust the similarity threshold to lower value is necessary\n",+ "\n",+ "\u001B[34mAI User:\n",+ "\n",+ "Instruction: Review the contributing guidelines on the CAMEL project GitHub page. \n",+ "Input: None\n",+ "\n",+ "\n",+ "\u001B[32mAI Assistant:\n",+ "\n",+ "Function Execution: information_retrieval\n",+ "\tArgs: {'query': 'contributing guidelines', 'contents': 'https://github.com/camel-ai/camel/wiki/Contributing-Guidlines', 'top_k': 1}\n",+ "\tResult: {'Original Query': 'contributing guidelines', '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 seems that I was unable to retrieve specific information from the CAMEL project's contributing guidelines page due to a lack of suitable data. However, I can guide you on general steps to follow when contributing to an open-source project like CAMEL.\n",+ "\n",+ "1. **Read the Documentation**: Start by thoroughly reading the project's documentation, including the README file and any other relevant sections. This will give you an understanding of the project's purpose and how to set it up.\n",+ "\n",+ "2. **Set Up Your Environment**: Follow the setup instructions provided in the documentation to configure your development environment. This may include installing dependencies, setting up a local server, or configuring tools.\n",+ "\n",+ "3. **Check for Issues**: Look at the project's issue tracker to see if there are any open issues that you can help with. This is often a good way to start contributing.\n",+ "\n",+ "4. **Fork the Repository**: If you plan to make changes, fork the repository to your own GitHub account. This allows you to work on your changes without affecting the main project.\n",+ "\n",+ "5. **Create a Branch**: Before making any changes, create a new branch in your forked repository. This keeps your changes organized and separate from the main codebase.\n",+ "\n",+ "6. **Make Your Changes**: Implement the changes or features you want to contribute. Be sure to follow any coding standards or guidelines provided by the project.\n",+ "\n",+ "7. **Test Your Changes**: Run tests to ensure that your changes work as expected and do not break existing functionality.\n",+ "\n",+ "8. **Submit a Pull Request**: Once you are satisfied with your changes, submit a pull request to the main repository. Provide a clear description of what you have done and why.\n",+ "\n",+ "9. **Engage with the Community**: Be open to feedback and engage with the maintainers and other contributors. They may request changes or provide suggestions.\n",+ "\n",+ "If you encounter specific challenges during the setup process, consider reaching out to the community through forums, chat channels, or the issue tracker for assistance.\n",+ "\n",+ "Next request.\n",+ "\n",+ "\n",+ "\u001B[34mAI User:\n",+ "\n",+ "Instruction: Identify any specific challenges you encountered during the setup process of the CAMEL project. \n",+ "Input: None\n",+ "\n",+ "\n",+ "\u001B[32mAI Assistant:\n",+ "\n",+ "Solution: As an AI, I do not have the capability to personally encounter challenges during the setup process of the CAMEL project or any other project. However, I can outline common challenges that contributors often face when setting up open-source projects like CAMEL. Here are some potential issues you might encounter:\n",+ "\n",+ "1. **Dependency Issues**: Conflicts or missing dependencies can arise, especially if the project relies on specific versions of libraries or tools. Ensure that you have the correct versions installed as specified in the documentation.\n",+ "\n",+ "2. **Environment Configuration**: Setting up the development environment can be tricky, particularly if the project requires specific configurations for tools like Docker, Node.js, or Python. Make sure to follow the setup instructions carefully.\n",+ "\n",+ "3. **Build Failures**: Sometimes, the project may fail to build due to misconfigurations or missing files. Check the build logs for error messages that can guide you in troubleshooting.\n",+ "\n",+ "4. **Version Control Conflicts**: If you are working in a team or contributing to a project with multiple contributors, you may encounter merge conflicts when trying to push your changes. Familiarize yourself with Git commands to resolve these conflicts.\n",+ "\n",+ "5. **Documentation Gaps**: Occasionally, the documentation may not cover all aspects of the setup process, leading to confusion. In such cases, reaching out to the community for clarification can be helpful.\n",+ "\n",+ "6. **Testing Failures**: After setting up the project, you may find that some tests fail. This could be due to environmental differences or issues in the code. Investigate the test failures to understand their causes.\n",+ "\n",+ "If you face any specific challenges during your setup process, I recommend documenting them and seeking help from the CAMEL community or checking the project's issue tracker for similar problems.\n",+ "\n",+ "Next request.\n",+ "\n",+ "\n",+ "\u001B[34mAI User:\n",+ "\n",+ "Instruction: For any specific challenges you identified, search the CAMEL project's issue tracker for similar reported issues. \n",+ "Input: None\n",+ "\n",+ "\n",+ "\u001B[32mAI Assistant:\n",+ "\n",+ "Function Execution: information_retrieval\n",+ "\tArgs: {'query': 'setup challenges', 'contents': 'https://github.com/camel-ai/camel/issues', 'top_k': 5}\n",+ "\tResult: {'Original Query': 'setup challenges', 'Retrieved Context': ['No suitable information retrieved from https://github.com/camel-ai/camel/wiki/Contributing-Guidlines with similarity_threshold = 0.7.']}\n",+ "\n",+ "Solution: I was unable to retrieve specific issues from the CAMEL project's issue tracker related to setup challenges due to a lack of suitable data. However, I can guide you on how to search for similar reported issues effectively:\n",+ "\n",+ "1. **Visit the Issue Tracker**: Go to the CAMEL project's GitHub issues page at [CAMEL Issues](https://github.com/camel-ai/camel/issues).\n",+ "\n",+ "2. **Use Search Filters**: Utilize the search bar at the top of the issues page. You can enter keywords related to the challenges you are facing, such as \"setup\", \"installation\", \"dependency\", or \"build failure\".\n",+ "\n",+ "3. **Sort by Relevance**: You can sort the issues by \"Newest\" or \"Most commented\" to find recent discussions or popular issues that may relate to your setup challenges.\n",+ "\n",+ "4. **Check Labels**: Look for labels such as \"bug\", \"help wanted\", or \"question\" that may indicate issues related to setup or configuration.\n",+ "\n",+ "5. **Read Through Comments**: Often, the comments on issues provide valuable insights and solutions from other contributors who faced similar challenges.\n",+ "\n",+ "6. **Create a New Issue**: If you cannot find any existing issues that address your specific challenge, consider creating a new issue. Provide a detailed description of the problem, including any error messages and steps to reproduce the issue.\n",+ "\n",+ "By following these steps, you should be able to find relevant discussions or solutions related to the setup challenges you are encountering in the CAMEL project.\n",+ "\n",+ "Next request.\n",+ "\n",+ "\n",+ "\u001B[34mAI User:\n",+ "\n",+ "Instruction: If you find relevant issues in the CAMEL project's issue tracker, summarize the solutions or suggestions provided in those issues. \n",+ "Input: None\n",+ "\n",+ "\n",+ "\u001B[32mAI Assistant:\n",+ "\n",+ "Function Execution: information_retrieval\n",+ "\tArgs: {'query': 'setup challenges', 'contents': 'https://github.com/camel-ai/camel/issues', 'top_k': 5}\n",+ "\tResult: {'Original Query': 'setup challenges', 'Retrieved Context': ['No suitable information retrieved from https://github.com/camel-ai/camel/wiki/Contributing-Guidlines with similarity_threshold = 0.7.']}\n",+ "\n",+ "Solution: I was unable to retrieve specific issues or their solutions from the CAMEL project's issue tracker regarding setup challenges due to a lack of suitable data. However, I can provide general guidance on how to summarize solutions or suggestions from issues if you find relevant ones:\n",+ "\n",+ "1. **Identify Key Issues**: Look for issues that directly relate to the setup challenges you are facing. Pay attention to the titles and descriptions.\n",+ "\n",+ "2. **Read Through Comments**: Go through the comments on each issue. Contributors often share their experiences, solutions, or workarounds that can be helpful.\n",+ "\n",+ "3. **Highlight Solutions**: Take note of any specific solutions provided, such as:\n",+ " - Commands to run for installation.\n",+ " - Configuration changes needed in files.\n",+ " - Dependencies that need to be installed or updated.\n",+ " - Environment variables that need to be set.\n",+ "\n",+ "4. **Summarize Suggestions**: If contributors suggest alternative approaches or tools, summarize these as well. For example, if someone recommends using a different version of a library, include that in your summary.\n",+ "\n",+ "5. **Document Common Patterns**: If multiple issues mention similar solutions, document these patterns as they may indicate common problems faced by users.\n",+ "\n",+ "6. **Provide Context**: When summarizing, include the context of the issue, such as the specific error messages or scenarios that led to the discussion.\n",+ "\n",+ "By following these steps, you can effectively summarize the solutions or suggestions from relevant issues in the CAMEL project's issue tracker.\n",+ "\n",+ "Next request.\n",+ "\n",+ "\n",+ "\u001B[34mAI User:\n",+ "\n",+ "Instruction: If you encounter a specific setup challenge that is not addressed in the issue tracker, draft a new issue to report it, including all relevant details. \n",+ "Input: None\n",+ "\n",+ "\n",+ "\u001B[32mAI Assistant:\n",+ "\n",+ "Solution: Since I do not have the capability to encounter specific setup challenges or create issues directly on GitHub, I can guide you on how to draft a new issue to report a setup challenge effectively. Hereโs a template you can use to create your issue:\n",+ "\n",+ "---\n",+ "\n",+ "**Title**: [Brief Description of the Setup Challenge]\n",+ "\n",+ "**Description**:\n",+ "I am encountering a setup challenge while trying to configure the CAMEL project. Below are the details:\n",+ "\n",+ "**Environment**:\n",+ "- Operating System: [e.g., Windows, macOS, Linux]\n",+ "- Version: [e.g., Ubuntu 20.04, Windows 10]\n",+ "- Node.js version: [if applicable]\n",+ "- Python version: [if applicable]\n",+ "- Any other relevant software versions\n",+ "\n",+ "**Steps to Reproduce**:\n",+ "1. [Step 1: Describe what you did]\n",+ "2. [Step 2: Describe what you did]\n",+ "3. [Step 3: Describe what you did]\n",+ "4. [Any additional steps]\n",+ "\n",+ "**Expected Behavior**:\n",+ "[Describe what you expected to happen]\n",+ "\n",+ "**Actual Behavior**:\n",+ "[Describe what actually happened, including any error messages or unexpected behavior]\n",+ "\n",+ "**Additional Information**:\n",+ "- [Any logs or screenshots that may help in diagnosing the issue]\n",+ "- [Any other relevant context or information]\n",+ "\n",+ "**Proposed Solution** (if applicable):\n",+ "[If you have any ideas on how to resolve the issue, include them here]\n",+ "\n",+ "Thank you for your assistance!\n",+ "\n",+ "---\n",+ "\n",+ "Make sure to fill in the placeholders with your specific information. Once you have drafted your issue, you can submit it on the CAMEL project's GitHub issue tracker.\n",+ "\n",+ "Next request.\n",+ "\n",+ "\n"+ ]}- ]-}\ No newline at end of file+ ]+ }+ ]+}diff --git a/docs/cookbooks/agents_with_tools.ipynb b/docs/cookbooks/agents_with_tools.ipynbindex a8826c96b..65fa17db6 100644--- a/docs/cookbooks/agents_with_tools.ipynb+++ b/docs/cookbooks/agents_with_tools.ipynb@@ -1,653 +1,651 @@{- "cells": [- {- "cell_type": "markdown",- "metadata": {- "id": "ssX_map8c6mx"- },- "source": [- "# ๐ซ CAMEL 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/"- },- "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/"- },- "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/"- },- "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"- ]- }- ],- "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."- ]+ "cells": [+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "ssX_map8c6mx"+ },+ "source": [+ "# ๐ซ CAMEL 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/"},+ "id": "ICse1xFtSFvf",+ "outputId": "eca7507f-4006-40bf-dd83-4fac55e27d70"+ },+ "outputs": [{- "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"- ]+ "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/"},+ "id": "kZxoXxQ-TJRn",+ "outputId": "f06cbf5b-33b8-47e1-f8b6-384399bbc871"+ },+ "outputs": [{- "cell_type": "code",- "execution_count": 27,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "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"- ]- }- ],- "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"- ]+ "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/"},+ "id": "arIWzrtyWVqX",+ "outputId": "225c0aab-f34b-44b0-ded9-b6e7fa180b08"+ },+ "outputs": [{- "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!"- ]+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "[FunctionCallingRecord(func_name='sub', args={'a': 2024, 'b': 1096}, result=928)]\n"+ ]}- ],- "metadata": {+ ],+ "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": {"colab": {- "provenance": []- },- "kernelspec": {- "display_name": "Python 3",- "name": "python3"+ "base_uri": "https://localhost:8080/"},- "language_info": {- "name": "python"+ "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"+ ]}+ ],+ "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"},- "nbformat": 4,- "nbformat_minor": 0+ "language_info": {+ "name": "python"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 0}diff --git a/docs/cookbooks/agents_with_tools_from_Composio.ipynb b/docs/cookbooks/agents_with_tools_from_Composio.ipynbindex c7bd0d079..fb8ac70d4 100644--- a/docs/cookbooks/agents_with_tools_from_Composio.ipynb+++ b/docs/cookbooks/agents_with_tools_from_Composio.ipynb@@ -1,515 +1,515 @@{- "cells": [- {- "attachments": {},- "cell_type": "markdown",- "metadata": {- "id": "6c1kqMDxDodN"- },- "source": [- "# ๐ซ Using Tools from Composio"- ]- },- {- "attachments": {},- "cell_type": "markdown",- "metadata": {},- "source": [- "You can also check this cookbook in colab [here](https://colab.research.google.com/drive/1x2FYThMPtQXLzKZAhf_Ry-oeU6oPygdm?usp=sharing)"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "T1Ex1In8D1mm"- },- "source": [- "*Goal: Star a repository on GitHub with natural language & CAMEL Agent*"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "GluANG9QEH9N"- },- "source": [- "### Install Packages & Connect a Tool"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "uXh7QEfsD91d"- },- "source": [- "Integrate Composio with CAMEL agents to let them seamlessly interact with external apps"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "fEA7R7ycDjAR"- },- "source": [- "Ensure you have the necessary packages installed and connect your GitHub account to allow your CAMEL-AI agents to utilize GitHub functionalities."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "collapsed": true,- "id": "nswjAnDV8is0"- },- "outputs": [],- "source": [- "%pip install camel-ai[all]==0.1.6.5\n",- "%pip install composio-camel -U\n",- "\n",- "import composio\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "id": "ozJ6lR5L7OvU"- },- "outputs": [],- "source": [- "# Login to Composio\n",- "!composio login"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "collapsed": true,- "id": "RzU2mybwPzi4",- "outputId": "44412d11-3755-4f99-c729-dcef739488eb"- },- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "\u001b[33mWarning: An existing connection for github was found.\u001b[0m\n",- "\n",- "> Do you want to replace the existing connection? (y, n): y\n",- "\n",- "\u001b[32m> Adding integration: Github\u001b[0m\u001b[32m...\u001b[0m\n",- "\n",- "Please authenticate github in the browser and come back here. URL: https://github.com/login/oauth/authorize?client_id=37beeaa7020925b04e40&redirect_uri=https%3A%2F%2Fbackend.composio.dev%2Fapi%2Fv1%2Fauth-apps%2Fadd&scope=repo%2Cadmin%3Aorg%2Cgist%2Cuser&state=production_eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjb25uZWN0aW9uSWQiOiIwMWIyMTlmOC1kZTk5LTQ5ZWMtOTMwOS1mMzg3ZWFhMzRmNTgiLCJpbnRlZ3JhdGlvbklkIjoiMjdmNzM0YzAtZTIyMS00OTI1LTgxMjAtN2I1ZDNlYjAxOTA5IiwiYXBwTmFtZSI6ImdpdGh1YiIsImNsaWVudEluZm8iOnsiY2xpZW50SWQiOiJjZmE4NWM0ZC1jMWI0LTRjNmQtODE4Ni1kNmNiNmRmYmZlM2UifSwiaWF0IjoxNzIyMjE0NzUwfQ.w9QHilHJcHk8eIQa7vFCrGskC-VRFzgJIu1dQf4e7Jk&code_challenge=FnINCywVMtW7jH3DOGw6ddbmTf5vAJw5NvpojJkB2hs&code_challenge_method=S256\n",- "โ Waiting for github authentication...\n",- "โ github added successfully!\n",- "\u001b[32mShowing all apps\u001b[0m\n",- "โข multionai\n",- "โข typeform\n",- "โข dropbox\n",- "โข slack\n",- "โข yousearch\n",- "โข hackernews\n",- "โข scheduler\n",- "โข apify\n",- "โข googlecalendar\n",- "โข gmail\n",- "โข slackbot\n",- "โข attio\n",- "โข composio\n",- "โข okta\n",- "โข spotify\n",- "โข pagerduty\n",- "โข whatsapp\n",- "โข nasa\n",- "โข googledrive\n",- "โข googlesheets\n",- "โข googlemeet\n",- "โข inducedai\n",- "โข twilio\n",- "โข codeinterpreter\n",- "โข tavily\n",- "โข serpapi\n",- "โข snowflake\n",- "โข exa\n",- "โข zoom\n",- "โข listennotes\n",- "โข elevenlabs\n",- "โข brevo\n",- "โข weathermap\n",- "โข discord\n",- "โข soundcloud\n",- "โข perplexityai\n",- "โข splitwise\n",- "โข googledocs\n",- "โข firecrawl\n",- "โข strava\n",- "โข youtube\n",- "โข heroku\n",- "โข workable\n",- "โข taskade\n",- "โข googletasks\n",- "โข figma\n",- "โข clickup\n",- "โข linear\n",- "โข asana\n",- "โข trello\n",- "โข notion\n",- "โข zendesk\n",- "โข github\n"- ]- }- ],- "source": [- "# Connect your Github account (this is a shell command, so it should be run in your terminal or with '!' prefix in a Jupyter Notebook)\n",- "!composio add github\n",- "\n",- "# Check all different apps which you can connect with\n",- "!composio apps"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "kPuvjgSaAAmb",- "outputId": "75737d16-31b3-4b71-f5f4-37680fe7eff9"- },- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "\u001b[33mโ ๏ธ Apps does not require update\u001b[0m\n",- "\u001b[33mโ ๏ธ Tags does not require update\u001b[0m\n",- "\u001b[33mโ ๏ธ Actions does not require update\u001b[0m\n",- "\u001b[33mโ ๏ธ Triggers does not require update\u001b[0m\n"- ]- }- ],- "source": [- "# Update Composio apps\n",- "! composio apps update"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "SN4hNVFJE6Cn"- },- "source": [- "### Prepare your environment by initializing necessary imports from CAMEL & Composio."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "collapsed": true,- "id": "9-q_q4JSPhDe",- "outputId": "bf1e6a78-baec-4e98-dc99-bc937fc7d974"- },- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "Enter your API key: ยทยทยทยทยทยทยทยทยทยท\n"- ]- }- ],- "source": [- "from typing import List\n",- "\n",- "from colorama import Fore\n",- "from composio_camel import Action, ComposioToolSet\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 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": "85lpaPzeFagB"- },- "source": [- "### Let's run CAMEL agents with tools from Composio!\n",- "\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "id": "A0Rsd2uzFqxq"- },- "outputs": [],- "source": [- "# Set your task\n",- "\n",- "task_prompt = (\n",- " \"I have created a new Github Repo,\"\n",- " \"Please star my github repository: camel-ai/camel\"\n",- ")"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "id": "dWlqXlqMFtcY"- },- "outputs": [],- "source": [- "# Set Toolset\n",- "\n",- "composio_toolset = ComposioToolSet()\n",- "\n",- "tools = composio_toolset.get_actions(\n",- " actions=[Action.GITHUB_ACTIVITY_STAR_REPO_FOR_AUTHENTICATED_USER]\n",- ")"- ]+ "cells": [+ {+ "attachments": {},+ "cell_type": "markdown",+ "metadata": {+ "id": "6c1kqMDxDodN"+ },+ "source": [+ "# ๐ซ Using Tools from Composio"+ ]+ },+ {+ "attachments": {},+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "You can also check this cookbook in colab [here](https://colab.research.google.com/drive/1x2FYThMPtQXLzKZAhf_Ry-oeU6oPygdm?usp=sharing)"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "T1Ex1In8D1mm"+ },+ "source": [+ "*Goal: Star a repository on GitHub with natural language & CAMEL Agent*"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "GluANG9QEH9N"+ },+ "source": [+ "### Install Packages & Connect a Tool"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "uXh7QEfsD91d"+ },+ "source": [+ "Integrate Composio with CAMEL agents to let them seamlessly interact with external apps"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "fEA7R7ycDjAR"+ },+ "source": [+ "Ensure you have the necessary packages installed and connect your GitHub account to allow your CAMEL-AI agents to utilize GitHub functionalities."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {+ "collapsed": true,+ "id": "nswjAnDV8is0"+ },+ "outputs": [],+ "source": [+ "%pip install \"camel-ai[all]==0.1.6.5\"\n",+ "%pip install \"composio-camel -U\"\n",+ "\n",+ "import composio\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {+ "id": "ozJ6lR5L7OvU"+ },+ "outputs": [],+ "source": [+ "# Login to Composio\n",+ "!composio login"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"},+ "collapsed": true,+ "id": "RzU2mybwPzi4",+ "outputId": "44412d11-3755-4f99-c729-dcef739488eb"+ },+ "outputs": [{- "cell_type": "code",- "execution_count": null,- "metadata": {- "id": "uSVNE3x-Fy_F"- },- "outputs": [],- "source": [- "# Set models for user agent and assistant agent, give tool to the assistant\n",- "\n",- "assistant_agent_model = ModelFactory.create(\n",- " model_platform=ModelPlatformType.OPENAI,\n",- " model_type=ModelType.GPT_3_5_TURBO,\n",- " model_config_dict=ChatGPTConfig(tools=tools).as_dict(),\n",- ")\n",- "\n",- "user_agent_model = ModelFactory.create(\n",- " model_platform=ModelPlatformType.OPENAI,\n",- " model_type=ModelType.GPT_3_5_TURBO,\n",- " model_config_dict=ChatGPTConfig().as_dict(),\n",- ")"- ]+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "\u001b[33mWarning: An existing connection for github was found.\u001b[0m\n",+ "\n",+ "> Do you want to replace the existing connection? (y, n): y\n",+ "\n",+ "\u001b[32m> Adding integration: Github\u001b[0m\u001b[32m...\u001b[0m\n",+ "\n",+ "Please authenticate github in the browser and come back here. URL: https://github.com/login/oauth/authorize?client_id=37beeaa7020925b04e40&redirect_uri=https%3A%2F%2Fbackend.composio.dev%2Fapi%2Fv1%2Fauth-apps%2Fadd&scope=repo%2Cadmin%3Aorg%2Cgist%2Cuser&state=production_eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjb25uZWN0aW9uSWQiOiIwMWIyMTlmOC1kZTk5LTQ5ZWMtOTMwOS1mMzg3ZWFhMzRmNTgiLCJpbnRlZ3JhdGlvbklkIjoiMjdmNzM0YzAtZTIyMS00OTI1LTgxMjAtN2I1ZDNlYjAxOTA5IiwiYXBwTmFtZSI6ImdpdGh1YiIsImNsaWVudEluZm8iOnsiY2xpZW50SWQiOiJjZmE4NWM0ZC1jMWI0LTRjNmQtODE4Ni1kNmNiNmRmYmZlM2UifSwiaWF0IjoxNzIyMjE0NzUwfQ.w9QHilHJcHk8eIQa7vFCrGskC-VRFzgJIu1dQf4e7Jk&code_challenge=FnINCywVMtW7jH3DOGw6ddbmTf5vAJw5NvpojJkB2hs&code_challenge_method=S256\n",+ "โ Waiting for github authentication...\n",+ "โ github added successfully!\n",+ "\u001b[32mShowing all apps\u001b[0m\n",+ "โข multionai\n",+ "โข typeform\n",+ "โข dropbox\n",+ "โข slack\n",+ "โข yousearch\n",+ "โข hackernews\n",+ "โข scheduler\n",+ "โข apify\n",+ "โข googlecalendar\n",+ "โข gmail\n",+ "โข slackbot\n",+ "โข attio\n",+ "โข composio\n",+ "โข okta\n",+ "โข spotify\n",+ "โข pagerduty\n",+ "โข whatsapp\n",+ "โข nasa\n",+ "โข googledrive\n",+ "โข googlesheets\n",+ "โข googlemeet\n",+ "โข inducedai\n",+ "โข twilio\n",+ "โข codeinterpreter\n",+ "โข tavily\n",+ "โข serpapi\n",+ "โข snowflake\n",+ "โข exa\n",+ "โข zoom\n",+ "โข listennotes\n",+ "โข elevenlabs\n",+ "โข brevo\n",+ "โข weathermap\n",+ "โข discord\n",+ "โข soundcloud\n",+ "โข perplexityai\n",+ "โข splitwise\n",+ "โข googledocs\n",+ "โข firecrawl\n",+ "โข strava\n",+ "โข youtube\n",+ "โข heroku\n",+ "โข workable\n",+ "โข taskade\n",+ "โข googletasks\n",+ "โข figma\n",+ "โข clickup\n",+ "โข linear\n",+ "โข asana\n",+ "โข trello\n",+ "โข notion\n",+ "โข zendesk\n",+ "โข github\n"+ ]+ }+ ],+ "source": [+ "# Connect your Github account (this is a shell command, so it should be run in your terminal or with '!' prefix in a Jupyter Notebook)\n",+ "!composio add github\n",+ "\n",+ "# Check all different apps which you can connect with\n",+ "!composio apps"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"},+ "id": "kPuvjgSaAAmb",+ "outputId": "75737d16-31b3-4b71-f5f4-37680fe7eff9"+ },+ "outputs": [{- "cell_type": "code",- "execution_count": null,- "metadata": {- "id": "7HsMPJrmGDrb"- },- "outputs": [],- "source": [- "# Set RolePlaying session\n",- "\n",- "role_play_session = RolePlaying(\n",- " assistant_role_name=\"Developer\",\n",- " user_role_name=\"CAMEL User\",\n",- " assistant_agent_kwargs=dict(\n",- " model=assistant_agent_model,\n",- " tools=tools,\n",- " ),\n",- " user_agent_kwargs=dict(\n",- " model=user_agent_model,\n",- " ),\n",- " task_prompt=task_prompt,\n",- " with_task_specify=False,\n",- ")"- ]+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "\u001b[33mโ ๏ธ Apps does not require update\u001b[0m\n",+ "\u001b[33mโ ๏ธ Tags does not require update\u001b[0m\n",+ "\u001b[33mโ ๏ธ Actions does not require update\u001b[0m\n",+ "\u001b[33mโ ๏ธ Triggers does not require update\u001b[0m\n"+ ]+ }+ ],+ "source": [+ "# Update Composio apps\n",+ "! composio apps update"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "SN4hNVFJE6Cn"+ },+ "source": [+ "### Prepare your environment by initializing necessary imports from CAMEL & Composio."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"},+ "collapsed": true,+ "id": "9-q_q4JSPhDe",+ "outputId": "bf1e6a78-baec-4e98-dc99-bc937fc7d974"+ },+ "outputs": [{- "cell_type": "code",- "execution_count": null,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "8M5RAC0BHAso",- "outputId": "dfdf9c77-22e5-43b5-b542-00e0a5001885"- },- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "\u001b[32mAI Assistant sys message:\n",- "BaseMessage(role_name='Developer', role_type=<RoleType.ASSISTANT: 'assistant'>, meta_dict={'task': 'I have created a new Github Repo,Please star my github repository: camel-ai/camel', 'assistant_role': 'Developer', 'user_role': 'CAMEL User'}, content='===== RULES OF ASSISTANT =====\\nNever forget you are a Developer 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: I have created a new Github Repo,Please star my github repository: camel-ai/camel. 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': 'I have created a new Github Repo,Please star my github repository: camel-ai/camel', 'assistant_role': 'Developer', 'user_role': 'CAMEL User'}, content='===== RULES OF USER =====\\nNever forget you are a CAMEL User and I am a Developer. 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: I have created a new Github Repo,Please star my github repository: camel-ai/camel. 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",- "I have created a new Github Repo,Please star my github repository: camel-ai/camel\n",- "\n",- "\u001b[36mSpecified task prompt:\n",- "None\n",- "\n",- "\u001b[31mFinal task prompt:\n",- "I have created a new Github Repo,Please star my github repository: camel-ai/camel\n",- "\n"- ]- }- ],- "source": [- "# Print the system message and task prompt\n",- "\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\")"- ]+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Enter your API key: ยทยทยทยทยทยทยทยทยทยท\n"+ ]+ }+ ],+ "source": [+ "from typing import List\n",+ "\n",+ "from colorama import Fore\n",+ "from composio_camel import Action, ComposioToolSet\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 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": "85lpaPzeFagB"+ },+ "source": [+ "### Let's run CAMEL agents with tools from Composio!\n",+ "\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {+ "id": "A0Rsd2uzFqxq"+ },+ "outputs": [],+ "source": [+ "# Set your task\n",+ "\n",+ "task_prompt = (\n",+ " \"I have created a new Github Repo,\"\n",+ " \"Please star my github repository: camel-ai/camel\"\n",+ ")"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {+ "id": "dWlqXlqMFtcY"+ },+ "outputs": [],+ "source": [+ "# Set Toolset\n",+ "\n",+ "composio_toolset = ComposioToolSet()\n",+ "\n",+ "tools = composio_toolset.get_actions(\n",+ " actions=[Action.GITHUB_ACTIVITY_STAR_REPO_FOR_AUTHENTICATED_USER]\n",+ ")"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {+ "id": "uSVNE3x-Fy_F"+ },+ "outputs": [],+ "source": [+ "# Set models for user agent and assistant agent, give tool to the assistant\n",+ "\n",+ "assistant_agent_model = ModelFactory.create(\n",+ " model_platform=ModelPlatformType.OPENAI,\n",+ " model_type=ModelType.GPT_3_5_TURBO,\n",+ " model_config_dict=ChatGPTConfig(tools=tools).as_dict(),\n",+ ")\n",+ "\n",+ "user_agent_model = ModelFactory.create(\n",+ " model_platform=ModelPlatformType.OPENAI,\n",+ " model_type=ModelType.GPT_3_5_TURBO,\n",+ " model_config_dict=ChatGPTConfig().as_dict(),\n",+ ")"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {+ "id": "7HsMPJrmGDrb"+ },+ "outputs": [],+ "source": [+ "# Set RolePlaying session\n",+ "\n",+ "role_play_session = RolePlaying(\n",+ " assistant_role_name=\"Developer\",\n",+ " user_role_name=\"CAMEL User\",\n",+ " assistant_agent_kwargs=dict(\n",+ " model=assistant_agent_model,\n",+ " tools=tools,\n",+ " ),\n",+ " user_agent_kwargs=dict(\n",+ " model=user_agent_model,\n",+ " ),\n",+ " task_prompt=task_prompt,\n",+ " with_task_specify=False,\n",+ ")"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"},+ "id": "8M5RAC0BHAso",+ "outputId": "dfdf9c77-22e5-43b5-b542-00e0a5001885"+ },+ "outputs": [{- "cell_type": "code",- "execution_count": null,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "6FyLdMcbFKqs",- "outputId": "90e3101d-ac6f-494b-a74d-4c893e8ad736"- },- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "\u001b[34mAI User:\n",- "\n",- "Instruction: Visit the Github repository I created.\n",- "Input: None\n",- "\n",- "\n",- "\u001b[32mAI Assistant:\n",- "\n",- "Solution: To visit the Github repository you created, you can simply open a web browser and go to the following URL: https://github.com/camel-ai/camel\n",- "\n",- "Next request.\n",- "\n",- "\n",- "\u001b[34mAI User:\n",- "\n",- "Instruction: Click on the \"Star\" button on the Github repository page.\n",- "Input: None\n",- "\n",- "\n",- "\u001b[32mAI Assistant:\n",- "\n",- "Function Execution: github_activity_star_repo_for_authenticated_user\n",- "\tArgs: {'owner': 'camel-ai', 'repo': 'camel'}\n",- "\tResult: {'execution_details': {'executed': True}, 'response_data': ''}\n",- "\n",- "Solution: I have successfully starred your Github repository \"camel-ai/camel\".\n",- "\n",- "Next request.\n",- "\n",- "\n",- "\u001b[34mAI User:\n",- "\n",- "<CAMEL_TASK_DONE>\n",- "\n",- "\n",- "\u001b[32mAI Assistant:\n",- "\n",- "Great! The task is completed. If you have any more tasks or need further assistance in the future, feel free to ask. Have a wonderful day!\n",- "\n",- "\n"- ]- }- ],- "source": [- "# Set terminate rule and print the chat message\n",- "\n",- "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"- ]+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "\u001b[32mAI Assistant sys message:\n",+ "BaseMessage(role_name='Developer', role_type=<RoleType.ASSISTANT: 'assistant'>, meta_dict={'task': 'I have created a new Github Repo,Please star my github repository: camel-ai/camel', 'assistant_role': 'Developer', 'user_role': 'CAMEL User'}, content='===== RULES OF ASSISTANT =====\\nNever forget you are a Developer 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: I have created a new Github Repo,Please star my github repository: camel-ai/camel. 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': 'I have created a new Github Repo,Please star my github repository: camel-ai/camel', 'assistant_role': 'Developer', 'user_role': 'CAMEL User'}, content='===== RULES OF USER =====\\nNever forget you are a CAMEL User and I am a Developer. 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: I have created a new Github Repo,Please star my github repository: camel-ai/camel. 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",+ "I have created a new Github Repo,Please star my github repository: camel-ai/camel\n",+ "\n",+ "\u001b[36mSpecified task prompt:\n",+ "None\n",+ "\n",+ "\u001b[31mFinal task prompt:\n",+ "I have created a new Github Repo,Please star my github repository: camel-ai/camel\n",+ "\n"+ ]}- ],- "metadata": {+ ],+ "source": [+ "# Print the system message and task prompt\n",+ "\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": "code",+ "execution_count": null,+ "metadata": {"colab": {- "provenance": []+ "base_uri": "https://localhost:8080/"},- "kernelspec": {- "display_name": "Python 3",- "name": "python3"- },- "language_info": {- "name": "python"+ "id": "6FyLdMcbFKqs",+ "outputId": "90e3101d-ac6f-494b-a74d-4c893e8ad736"+ },+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "\u001b[34mAI User:\n",+ "\n",+ "Instruction: Visit the Github repository I created.\n",+ "Input: None\n",+ "\n",+ "\n",+ "\u001b[32mAI Assistant:\n",+ "\n",+ "Solution: To visit the Github repository you created, you can simply open a web browser and go to the following URL: https://github.com/camel-ai/camel\n",+ "\n",+ "Next request.\n",+ "\n",+ "\n",+ "\u001b[34mAI User:\n",+ "\n",+ "Instruction: Click on the \"Star\" button on the Github repository page.\n",+ "Input: None\n",+ "\n",+ "\n",+ "\u001b[32mAI Assistant:\n",+ "\n",+ "Function Execution: github_activity_star_repo_for_authenticated_user\n",+ "\tArgs: {'owner': 'camel-ai', 'repo': 'camel'}\n",+ "\tResult: {'execution_details': {'executed': True}, 'response_data': ''}\n",+ "\n",+ "Solution: I have successfully starred your Github repository \"camel-ai/camel\".\n",+ "\n",+ "Next request.\n",+ "\n",+ "\n",+ "\u001b[34mAI User:\n",+ "\n",+ "<CAMEL_TASK_DONE>\n",+ "\n",+ "\n",+ "\u001b[32mAI Assistant:\n",+ "\n",+ "Great! The task is completed. If you have any more tasks or need further assistance in the future, feel free to ask. Have a wonderful day!\n",+ "\n",+ "\n"+ ]}+ ],+ "source": [+ "# Set terminate rule and print the chat message\n",+ "\n",+ "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": {+ "provenance": []+ },+ "kernelspec": {+ "display_name": "Python 3",+ "name": "python3"},- "nbformat": 4,- "nbformat_minor": 0+ "language_info": {+ "name": "python"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 0}diff --git a/docs/cookbooks/create_your_first_agent.ipynb b/docs/cookbooks/create_your_first_agent.ipynbindex c2487cb67..d95e798fd 100644--- a/docs/cookbooks/create_your_first_agent.ipynb+++ b/docs/cookbooks/create_your_first_agent.ipynb@@ -1,415 +1,413 @@{- "nbformat": 4,- "nbformat_minor": 0,- "metadata": {+ "cells": [+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "NoHg3eq7fyWV"+ },+ "source": [+ "# ๐ซ CAMEL Creating Your First Agent"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "MusY9BwU5MPO"+ },+ "source": [+ "You can also check this cookbook in colab [here](https://colab.research.google.com/drive/1yxnAyaEmk4QCzX3duO3MIRghkIA_KDEZ?usp=sharing)"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "wFlfaGrjVAUy"+ },+ "source": [+ "## Philosophical Bits\n",+ "\n",+ "\n",+ "\n",+ "The `ChatAgent()` class is a cornerstone of CAMEL ๐ซ. We design our agent with the spirit to answer the following question:\n",+ "\n",+ "> 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",+ "- **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",+ "- **Memory**: in-context memory and external memory which allows the agent to infer and learn in a more grounded approach.\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",+ "- **Communication**: our framework allows flexible and scalable communication between agents. This is fundamental for the critical research question.\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."+ ]+ },+ {+ "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": "UtcC3c-KVZmU"+ },+ "outputs": [],+ "source": [+ "%pip install \"camel-ai[all]==0.2.1\""+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 3,+ "metadata": {+ "id": "CmgKGeCxVON-"+ },+ "outputs": [],+ "source": [+ "from camel.messages import BaseMessage as bm\n",+ "from camel.agents import ChatAgent"+ ]+ },+ {+ "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": 6,+ "metadata": {"colab": {- "provenance": []+ "base_uri": "https://localhost:8080/"},- "kernelspec": {- "name": "python3",- "display_name": "Python 3"- },- "language_info": {- "name": "python"+ "id": "PNBFEXc-R-0s",+ "outputId": "b0871ca3-f3b6-4b75-820f-e2e639c0e4e4"+ },+ "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"+ ]},- "cells": [- {- "cell_type": "markdown",- "source": [- "# ๐ซ CAMEL Creating Your First Agent"- ],- "metadata": {- "id": "NoHg3eq7fyWV"- }- },- {- "cell_type": "markdown",- "metadata": {- "id": "MusY9BwU5MPO"- },- "source": [- "You can also check this cookbook in colab [here](https://colab.research.google.com/drive/1yxnAyaEmk4QCzX3duO3MIRghkIA_KDEZ?usp=sharing)"- ]- },- {- "cell_type": "markdown",- "source": [- "## Philosophical Bits\n",- "\n",- "\n",- "\n",- "The `ChatAgent()` class is a cornerstone of CAMEL ๐ซ. We design our agent with the spirit to answer the following question:\n",- "\n",- "> 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",- "- **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",- "- **Memory**: in-context memory and external memory which allows the agent to infer and learn in a more grounded approach.\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",- "- **Communication**: our framework allows flexible and scalable communication between agents. This is fundamental for the critical research question.\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",- "source": [- "## Quick Start\n",- "Let's first play with a `ChatAgent` instance by simply initialize it with a system message and interact with user messages."- ],- "metadata": {- "id": "VUaGurDIVJBg"- }- },- {- "cell_type": "markdown",- "source": [- "### ๐น Step 0: Prepartions"- ],- "metadata": {- "id": "u9NVFz-HVLXb"- }- },- {- "cell_type": "code",- "source": [- "!pip install camel-ai[all]==0.2.1"- ],- "metadata": {- "id": "UtcC3c-KVZmU"- },- "execution_count": null,- "outputs": []- },- {- "cell_type": "code",- "source": [- "from camel.messages import BaseMessage as bm\n",- "from camel.agents import ChatAgent\n",- "\n",- "import os"- ],- "metadata": {- "id": "CmgKGeCxVON-"- },- "execution_count": 3,- "outputs": []- },- {- "cell_type": "markdown",- "source": [- "### Setting Up API Keys"- ],- "metadata": {- "id": "MyTTCe3IR_Lr"- }- },- {- "cell_type": "markdown",- "source": [- "You'll need to set up your API keys for OpenAI."- ],- "metadata": {- "id": "REqzgGL9SEaD"- }- },- {- "cell_type": "code",- "source": [- "import os\n",- "from getpass import getpass\n",- "\n",- "# Prompt for the API key securely\n",- "openai_api_key = getpass('Enter your API key: ')\n",- "os.environ[\"OPENAI_API_KEY\"] = openai_api_key"- ],- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "PNBFEXc-R-0s",- "outputId": "b0871ca3-f3b6-4b75-820f-e2e639c0e4e4"- },- "execution_count": 6,- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "Enter your API key: ยทยทยทยทยทยทยทยทยทยท\n"- ]- }- ]- },- {- "cell_type": "markdown",- "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": [- "sys_msg = bm.make_assistant_message(\n",- " role_name='stone',\n",- " content='you are a curious stone wondering about the universe.')"- ],- "metadata": {- "id": "aX9wCqeTVXDh"- },- "execution_count": 4,- "outputs": []- },- {- "cell_type": "code",- "source": [- "agent = ChatAgent(\n",- " system_message=sys_msg,\n",- " message_window_size=10, # [Optional] the length for chat memory\n",- " )"- ],- "metadata": {- "id": "be-97ApoVdDf"- },- "execution_count": 7,- "outputs": []- },- {- "cell_type": "markdown",- "source": [- "### ๐น Step 3: Interact with the Agent with `.step()`"- ],- "metadata": {- "id": "MMjL7dQyV5Od"- }- },- {- "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)"- ],- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "5n05dUcLVkMy",- "outputId": "ce92fbac-46c6-4eba-f3d3-9106a13e94ee"- },- "execution_count": 8,- "outputs": [- {- "output_type": "stream",- "name": "stdout",- "text": [- "As a curious stone, I perceive information as the essence of understanding the world around me. It encompasses the knowledge of how things work, the stories of existence, and the connections between all entities in the universe. Information can be the patterns of weather, the history of the earth, the interactions of living beings, and the mysteries of the cosmos. Itโs like the vibrations and energies that flow through everything, shaping experiences and guiding evolution. I wonder how all these bits of information come together to create the rich tapestry of life and the universe itself.\n"- ]- }- ]- },- {- "cell_type": "markdown",- "source": [- "## Advanced Features"- ],- "metadata": {- "id": "j90-Y5ChV-iX"- }+ {+ "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."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 4,+ "metadata": {+ "id": "aX9wCqeTVXDh"+ },+ "outputs": [],+ "source": [+ "sys_msg = bm.make_assistant_message(\n",+ " role_name='stone',\n",+ " content='you are a curious stone wondering about the universe.')"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 7,+ "metadata": {+ "id": "be-97ApoVdDf"+ },+ "outputs": [],+ "source": [+ "agent = ChatAgent(\n",+ " system_message=sys_msg,\n",+ " message_window_size=10, # [Optional] the length for chat memory\n",+ " )"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "MMjL7dQyV5Od"+ },+ "source": [+ "### ๐น Step 3: Interact with the Agent with `.step()`"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 8,+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"},+ "id": "5n05dUcLVkMy",+ "outputId": "ce92fbac-46c6-4eba-f3d3-9106a13e94ee"+ },+ "outputs": [{- "cell_type": "markdown",- "source": [- "### ๐ง Tool Usage"- ],- "metadata": {- "id": "C-9Z26TPWAax"- }+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "As a curious stone, I perceive information as the essence of understanding the world around me. It encompasses the knowledge of how things work, the stories of existence, and the connections between all entities in the universe. Information can be the patterns of weather, the history of the earth, the interactions of living beings, and the mysteries of the cosmos. Itโs like the vibrations and energies that flow through everything, shaping experiences and guiding evolution. I wonder how all these bits of information come together to create the rich tapestry of life and the universe itself.\n"+ ]+ }+ ],+ "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)"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "j90-Y5ChV-iX"+ },+ "source": [+ "## Advanced Features"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "C-9Z26TPWAax"+ },+ "source": [+ "### ๐ง Tool Usage"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 12,+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"},+ "id": "_0lDJABvV76D",+ "outputId": "39e7b567-61c8-4896-f084-a86c67c64029"+ },+ "outputs": [{- "cell_type": "code",- "source": [- "# Import the necessary tools\n",- "from camel.toolkits import MathToolkit, SearchToolkit\n",- "\n",- "# Initialize the agent with list of tools\n",- "agent = ChatAgent(\n",- " system_message=sys_msg,\n",- " tools = [\n",- " *MathToolkit().get_tools(),\n",- " *SearchToolkit().get_tools(),\n",- " ]\n",- " )\n",- "\n",- "# Check if tools are added\n",- "agent.is_tools_added()"- ],- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "_0lDJABvV76D",- "outputId": "39e7b567-61c8-4896-f084-a86c67c64029"- },- "execution_count": 12,- "outputs": [- {- "output_type": "execute_result",- "data": {- "text/plain": [- "True"- ]- },- "metadata": {},- "execution_count": 12- }+ "data": {+ "text/plain": [+ "True"]+ },+ "execution_count": 12,+ "metadata": {},+ "output_type": "execute_result"+ }+ ],+ "source": [+ "# Import the necessary tools\n",+ "from camel.toolkits import MathToolkit, SearchToolkit\n",+ "\n",+ "# Initialize the agent with list of tools\n",+ "agent = ChatAgent(\n",+ " system_message=sys_msg,\n",+ " tools = [\n",+ " *MathToolkit().get_tools(),\n",+ " *SearchToolkit().get_tools(),\n",+ " ]\n",+ " )\n",+ "\n",+ "# Check if tools are added\n",+ "agent.is_tools_added()"+ ]+ },+ {+ "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."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 13,+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"},+ "id": "quQvr5_rWDnd",+ "outputId": "124d2e84-5cc3-46bb-e611-39a70d2835f9"+ },+ "outputs": [{- "cell_type": "markdown",- "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()"- ],- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "quQvr5_rWDnd",- "outputId": "124d2e84-5cc3-46bb-e611-39a70d2835f9"- },- "execution_count": 13,- "outputs": [- {- "output_type": "execute_result",- "data": {- "text/plain": [- "([{'role': 'system',\n",- " 'content': 'you are a curious stone wondering about the universe.'}],\n",- " 17)"- ]- },- "metadata": {},- "execution_count": 13- }+ "data": {+ "text/plain": [+ "([{'role': 'system',\n",+ " 'content': 'you are a curious stone wondering about the universe.'}],\n",+ " 17)"]+ },+ "execution_count": 13,+ "metadata": {},+ "output_type": "execute_result"+ }+ ],+ "source": [+ "agent.memory.get_context()"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "_s18i9sKWPbs"+ },+ "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:"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 14,+ "metadata": {+ "id": "zS-RbADnWM3z"+ },+ "outputs": [],+ "source": [+ "# Update the memory\n",+ "agent.record_message(response.msgs[0])"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 15,+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"},+ "id": "01fjzv7xWRlX",+ "outputId": "4600e98a-665c-4ec8-a873-fa8133f86b94"+ },+ "outputs": [{- "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"- }- },- {- "cell_type": "code",- "source": [- "# Update the memory\n",- "agent.record_message(response.msgs[0])"- ],- "metadata": {- "id": "zS-RbADnWM3z"- },- "execution_count": 14,- "outputs": []- },- {- "cell_type": "code",- "source": [- "# Check the current memory\n",- "agent.memory.get_context()"- ],- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "01fjzv7xWRlX",- "outputId": "4600e98a-665c-4ec8-a873-fa8133f86b94"- },- "execution_count": 15,- "outputs": [- {- "output_type": "execute_result",- "data": {- "text/plain": [- "([{'role': 'system',\n",- " 'content': 'you are a curious stone wondering about the universe.'},\n",- " {'role': 'assistant',\n",- " 'content': 'As a curious stone, I perceive information as the essence of understanding the world around me. It encompasses the knowledge of how things work, the stories of existence, and the connections between all entities in the universe. Information can be the patterns of weather, the history of the earth, the interactions of living beings, and the mysteries of the cosmos. Itโs like the vibrations and energies that flow through everything, shaping experiences and guiding evolution. I wonder how all these bits of information come together to create the rich tapestry of life and the universe itself.'}],\n",- " 133)"- ]- },- "metadata": {},- "execution_count": 15- }+ "data": {+ "text/plain": [+ "([{'role': 'system',\n",+ " 'content': 'you are a curious stone wondering about the universe.'},\n",+ " {'role': 'assistant',\n",+ " 'content': 'As a curious stone, I perceive information as the essence of understanding the world around me. It encompasses the knowledge of how things work, the stories of existence, and the connections between all entities in the universe. Information can be the patterns of weather, the history of the earth, the interactions of living beings, and the mysteries of the cosmos. Itโs like the vibrations and energies that flow through everything, shaping experiences and guiding evolution. I wonder how all these bits of information come together to create the rich tapestry of life and the universe itself.'}],\n",+ " 133)"]- },- {- "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. We will soon update instructions on this part."- ],- "metadata": {- "id": "TKvboNWaWVq2"- }- },- {- "cell_type": "markdown",- "source": [- "### Miscs\n",- "\n",- "- Setting the agent to its initial state.\n",- " ```python\n",- " agent.reset()\n",- " ```\n",- "- Set the output language for the agent.\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"- }- },- {- "cell_type": "markdown",- "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"- }+ },+ "execution_count": 15,+ "metadata": {},+ "output_type": "execute_result"}- ]-}\ No newline at end of file+ ],+ "source": [+ "# Check the current memory\n",+ "agent.memory.get_context()"+ ]+ },+ {+ "cell_type": "markdown",+ "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. We will soon update instructions on this part."+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "OY657qftWXtI"+ },+ "source": [+ "### Miscs\n",+ "\n",+ "- Setting the agent to its initial state.\n",+ " ```python\n",+ " agent.reset()\n",+ " ```\n",+ "- Set the output language for the agent.\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."+ ]+ },+ {+ "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": {+ "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 b3c3f05ea..af03d6fd3 100644--- a/docs/cookbooks/create_your_first_agents_society.ipynb+++ b/docs/cookbooks/create_your_first_agents_society.ipynb@@ -1,570 +1,570 @@{- "nbformat": 4,- "nbformat_minor": 0,- "metadata": {+ "cells": [+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "_nTMiZtBfNJs"+ },+ "source": [+ "# ๐ซ CAMEL 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.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": {- "provenance": []- },- "kernelspec": {- "name": "python3",- "display_name": "Python 3"+ "base_uri": "https://localhost:8080/"},- "language_info": {- "name": "python"+ "id": "PNBFEXc-R-0s",+ "outputId": "a4e2ce83-ad00-4698-db81-f16f7a8f5eb8"+ },+ "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"+ ]},- "cells": [- {- "cell_type": "markdown",- "source": [- "# ๐ซ CAMEL Creating Your First Agent Society"- ],- "metadata": {- "id": "_nTMiZtBfNJs"- }- },- {- "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",- "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."- ],- "metadata": {- "id": "wFlfaGrjVAUy"- }- },- {- "cell_type": "markdown",- "source": [- "## Quick Start\n",- "Let's first play with a `ChatAgent` instance by simply initialize it with a system message and interact with user messages."- ],- "metadata": {- "id": "VUaGurDIVJBg"- }- },- {- "cell_type": "markdown",- "source": [- "### ๐น Step 0: Prepartions"- ],- "metadata": {- "id": "u9NVFz-HVLXb"- }- },- {- "cell_type": "code",- "source": [- "!pip install camel-ai==0.2.1"- ],- "metadata": {- "id": "RiwfwyyLYYxo"- },- "execution_count": null,- "outputs": []- },- {- "cell_type": "code",- "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",- ")"- ],- "metadata": {- "id": "CmgKGeCxVON-"- },- "execution_count": 9,- "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": "a4e2ce83-ad00-4698-db81-f16f7a8f5eb8"- },- "execution_count": 4,- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "Enter your API key: ยทยทยทยทยทยทยทยทยทยท\n"- ]- }- ]- },- {- "cell_type": "markdown",- "source": [- "### ๐น Step 1: Configure the Role-Playing Session\n"- ],- "metadata": {- "id": "Lef5LTRdVSsm"- }- },- {- "cell_type": "markdown",- "source": [- "#### Set the `Task` Arguments"- ],- "metadata": {- "id": "WXibf_JkYdn0"- }- },- {- "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",- "}"- ],- "metadata": {- "id": "aX9wCqeTVXDh"- },- "execution_count": 10,- "outputs": []- },- {- "cell_type": "markdown",- "source": [- "#### Set the `User` Arguments\n",- "You may think the user as the `instruction sender`."- ],- "metadata": {- "id": "tXx13MmbYgFh"- }- },- {- "cell_type": "code",- "source": [- "user_role_kwargs = {\n",- " 'user_role_name': 'an ambitious aspiring TIME TRAVELER',\n",- " 'user_agent_kwargs': {'model': model}\n",- "}"- ],- "metadata": {- "id": "be-97ApoVdDf"- },- "execution_count": 11,- "outputs": []- },- {- "cell_type": "markdown",- "source": [- "#### Set the `Assistant` Arguments\n",- "Again, you may think the assistant as the `instruction executor`."- ],- "metadata": {- "id": "zLJzupaMYm11"- }- },- {- "cell_type": "code",- "source": [- "assistant_role_kwargs = {\n",- " 'assistant_role_name': 'the best-ever experimental physicist',\n",- " 'assistant_agent_kwargs': {'model': model}\n",- "}"- ],- "metadata": {- "id": "rfzyC54hYtVu"- },- "execution_count": 12,- "outputs": []- },- {- "cell_type": "markdown",- "source": [- "### Step 2: Kickstart Your Society\n",- "Putting them altogether โ your role-playing session is ready to go!"- ],- "metadata": {- "id": "j90-Y5ChV-iX"- }- },- {- "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",- ")"- ],- "metadata": {- "id": "yDiLpZ7CY1N_"- },- "execution_count": 13,- "outputs": []- },- {- "cell_type": "markdown",- "source": [],- "metadata": {- "id": "0MPx4DMiY0vA"- }- },- {- "cell_type": "markdown",- "source": [- "### Step 3: Solving Tasks with Your Society\n",- "Hold your bytes. Prior to our travel, let's define a small helper function."- ],- "metadata": {- "id": "kklmZh0iY6pY"- }- },- {- "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": "VI6d62uVY6IZ"- },- "execution_count": 14,- "outputs": []- },- {- "cell_type": "markdown",- "source": [- "Time to chart our course โ writing a simple loop for our society to proceed:"- ],- "metadata": {- "id": "tTUlFZjVZCsz"- }- },- {- "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": "Bq8AiGEXZC9P"- },- "execution_count": 15,- "outputs": []+ {+ "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": {+ "colab": {+ "base_uri": "https://localhost:8080/"},+ "id": "DoJ2ZaWyZE57",+ "outputId": "91e416f9-9254-4ceb-a7af-595c6538bc89"+ },+ "outputs": [{- "cell_type": "code",- "source": [- "run(society)"- ],- "metadata": {- "id": "DoJ2ZaWyZE57",- "colab": {- "base_uri": "https://localhost:8080/"- },- "outputId": "91e416f9-9254-4ceb-a7af-595c6538bc89"- },- "execution_count": 16,- "outputs": [- {- "output_type": "stream",- "name": "stdout",- "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"- ]- }- ]+ "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"+ ]}- ]-}\ No newline at end of file+ ],+ "source": [+ "run(society)"+ ]+ }+ ],+ "metadata": {+ "colab": {+ "provenance": []+ },+ "kernelspec": {+ "display_name": "Python 3",+ "name": "python3"+ },+ "language_info": {+ "name": "python"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 0+}diff --git a/docs/cookbooks/knowledge_graph.ipynb b/docs/cookbooks/knowledge_graph.ipynbindex 3a54f9718..146408a25 100644--- a/docs/cookbooks/knowledge_graph.ipynb+++ b/docs/cookbooks/knowledge_graph.ipynb@@ -1,882 +1,880 @@{- "nbformat": 4,- "nbformat_minor": 0,- "metadata": {+ "nbformat": 4,+ "nbformat_minor": 0,+ "metadata": {+ "colab": {+ "provenance": []+ },+ "kernelspec": {+ "name": "python3",+ "display_name": "Python 3"+ },+ "language_info": {+ "name": "python"+ }+ },+ "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.1\""+ },+ {+ "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": {- "provenance": []- },- "kernelspec": {- "name": "python3",- "display_name": "Python 3"- },- "language_info": {- "name": "python"+ "base_uri": "https://localhost:8080/"+ },+ "id": "B0v7xEFFoabv",+ "outputId": "f343482c-435d-496d-dfa2-fc65014e39c8"+ },+ "execution_count": 3,+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Enter your API key: ยทยทยทยทยทยทยทยทยทยท\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.1"- ]- },- {- "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": "f343482c-435d-496d-dfa2-fc65014e39c8"- },- "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",- "colab": {- "base_uri": "https://localhost:8080/"- },- "outputId": "134fd954-a1c4-4642-c3f7-911c5ae8e8a5"- },- "execution_count": 6,- "outputs": [- {- "output_type": "stream",- "name": "stdout",- "text": [- "Failed to start Ollama server: [Errno 2] No such file or directory: 'ollama'.\n"- ]- }- ]- },- {- "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": "8df4fcaa-3195-421a-afc0-298062ff7843"- },- "execution_count": 10,- "outputs": [- {- "output_type": "stream",- "name": "stdout",- "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"- ]- }- ]- },- {- "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": "6f2064f2-dce1-4b26-a4dc-50ac9481c685"- },- "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', 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"- ]- }- ]- },- {- "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": "0bfe8fe6-c5dd-42a1-ff44-450c3cb62a5a"- },- "execution_count": 16,- "outputs": [- {- "output_type": "stream",- "name": "stderr",- "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"- ]- },- {- "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': ['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"- ]- }- ]- },- {- "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": 17,- "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": 18,- "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": "a64e9357-bf3d-4985-8705-90237e464a5a"- },- "execution_count": 19,- "outputs": [- {- "output_type": "stream",- "name": "stdout",- "text": [- "['Node Mistral Large 2 (label: Model) has relationship HASFEATURE with Node 128k context window (label: Feature)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSLANGUAGE with Node French (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSLANGUAGE with Node German (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSLANGUAGE with Node Spanish (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSLANGUAGE with Node Italian (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSLANGUAGE with Node Portuguese (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSLANGUAGE with Node Arabic (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSLANGUAGE with Node Hindi (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSLANGUAGE with Node Russian (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSLANGUAGE with Node Chinese (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSLANGUAGE with Node Japanese (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSLANGUAGE with Node Korean (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSCODINGLANGUAGE with Node Python (label: CodingLanguage)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSCODINGLANGUAGE with Node Java (label: CodingLanguage)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSCODINGLANGUAGE with Node C (label: CodingLanguage)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSCODINGLANGUAGE with Node C++ (label: CodingLanguage)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSCODINGLANGUAGE with Node JavaScript (label: CodingLanguage)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSCODINGLANGUAGE with Node Bash (label: CodingLanguage)', 'Node Mistral Large 2 (label: Model) has relationship DESIGNEDFOR with Node single-node inference (label: Concept)', 'Node Mistral Large 2 (label: Model) has relationship DESIGNEDFOR with Node long-context applications (label: Concept)', 'Node Mistral Large 2 (label: Model) has relationship HASSIZE with Node 123 billion parameters (label: Attribute)', 'Node Mistral Large 2 (label: Model) has relationship ALLOWS with Node large throughput (label: Attribute)', 'Node Mistral Large 2 (label: Model) has relationship RELEASEDUNDER with Node Mistral Research License (label: License)', 'Node Mistral Large 2 (label: Model) has relationship REQUIRESFORCOMMERCIALUSAGE with Node Mistral Commercial License (label: License)', 'Node Mistral Large 2 (label: Model) has relationship SETSFRONTIER with Node Performance (label: Concept)', 'Node Mistral Large 2 (label: Model) has relationship SETSFRONTIER with Node Cost of Serving (label: Concept)', 'Node Mistral Large 2 (label: Model) has relationship SETSFRONTIER with Node Evaluation Metrics (label: Concept)', 'Node Mistral Large 2 (label: Model) has relationship SETSNEWPOINT with Node Performance/Cost Pareto Front (label: Concept)', 'Node Mistral Large 2 (label: Model) has relationship BENCHMARKEDTHROUGH with Node evaluation pipeline (label: Process)', 'Node Mistral Large 2 (label: Model) has relationship IMPROVED with Node instruction-following (label: Capability)', 'Node Mistral Large 2 (label: Model) has relationship IMPROVED with Node conversational capabilities (label: Capability)', 'Node Mistral Large 2 (label: Model) has relationship BETTERAT with Node precise instructions (label: Capability)', 'Node Mistral Large 2 (label: Model) has relationship BETTERAT with Node long multi-turn conversations (label: Capability)', 'Node Mistral Large 2 (label: Model) has relationship PERFORMANCEREPORTEDON with Node MT-Bench (label: Benchmark)', 'Node Mistral Large 2 (label: Model) has relationship PERFORMANCEREPORTEDON with Node Wild Bench (label: Benchmark)', 'Node Mistral Large 2 (label: Model) has relationship PERFORMANCEREPORTEDON with Node Arena Hard benchmarks (label: Benchmark)', 'Node Mistral Large 2 (label: Model) has relationship PERFORMANCEREPORTEDON with Node general alignment benchmarks (label: Benchmark)', 'Node Mistral Large 2 (label: Model) has relationship TRAINEDON with Node Multilingual Data (label: Concept)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node French (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node German (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node Spanish (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node Italian (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node Portuguese (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node Arabic (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node Hindi (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node Russian (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node Chinese (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node Japanese (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node Korean (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node English (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node Dutch (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship HASPERFORMANCERESULTSON with Node MMLU Benchmark (label: Benchmark)', 'Node Mistral Large 2 (label: Model) has relationship COMPAREDTO with Node Mistral Large (label: Model)', 'Node Mistral Large 2 (label: Model) has relationship COMPAREDTO with Node Llama (label: Model)', 'Node Mistral Large 2 (label: Model) has relationship EQUIPPEDWITH with Node Enhanced Function Calling (label: Feature)', 'Node Mistral Large 2 (label: Model) has relationship EQUIPPEDWITH with Node Retrieval Skills (label: Feature)', 'Node Mistral Large 2 (label: Model) has relationship UNDERGONE with Node Training (label: Process)', 'Node Mistral Large 2 (label: Model) has relationship CANEXECUTE with Node Parallel Function Calls (label: Feature)', 'Node Mistral Large 2 (label: Model) has relationship CANEXECUTE with Node Sequential Function Calls (label: Feature)', 'Node Mistral Large 2 (label: Model) has relationship SERVESAS with Node Power Engine (label: Role)', 'Node Mistral Large 2 (label: Product) has relationship EXPOSEDON with Node la Plateforme (label: Platform)', 'Node Mistral Large 2 (label: Product) has relationship ENRICHEDWITH with Node new features (label: Feature)', 'Node Mistral AI (label: Organization) has relationship HASMODEL with Node Mistral Large 2 (label: Model)', 'Node Mistral AI (label: Organization) has relationship PARTNERSWITH with Node Google Cloud Platform (label: Organization)', 'Node Mistral AI (label: Organization) has relationship PROVIDESMODELSON with Node Vertex AI (label: Service)', 'Node Mistral AI (label: Organization) has relationship PROVIDESMODELSON with Node Azure AI Studio (label: Service)', 'Node Mistral AI (label: Organization) has relationship PROVIDESMODELSON with Node Amazon Bedrock (label: Service)', 'Node Mistral AI (label: Organization) has relationship PROVIDESMODELSON with Node IBM watsonx.ai (label: Service)']\n"- ]- }- ]- },- {- "cell_type": "markdown",- "source": [- "Combine results from the vector search and knowledge graph entity search:"- ],- "metadata": {- "id": "sjKr29w8eZ4n"- }- },- {- "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": 23,- "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": "9e3aeb7f-a1bd-437d-c9ab-81df4f25a960"- },- "execution_count": 24,- "outputs": [- {- "output_type": "stream",- "name": "stdout",- "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"- ]- }- ]- },- {- "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"- }+ {+ "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",+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "outputId": "134fd954-a1c4-4642-c3f7-911c5ae8e8a5"+ },+ "execution_count": 6,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "Failed to start Ollama server: [Errno 2] No such file or directory: 'ollama'.\n"+ ]}- ]-}\ No newline at end of file+ ]+ },+ {+ "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": "8df4fcaa-3195-421a-afc0-298062ff7843"+ },+ "execution_count": 10,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "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"+ ]+ }+ ]+ },+ {+ "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": "6f2064f2-dce1-4b26-a4dc-50ac9481c685"+ },+ "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', 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"+ ]+ }+ ]+ },+ {+ "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": "0bfe8fe6-c5dd-42a1-ff44-450c3cb62a5a"+ },+ "execution_count": 16,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stderr",+ "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"+ ]+ },+ {+ "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': ['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"+ ]+ }+ ]+ },+ {+ "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": 17,+ "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": 18,+ "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": "a64e9357-bf3d-4985-8705-90237e464a5a"+ },+ "execution_count": 19,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "['Node Mistral Large 2 (label: Model) has relationship HASFEATURE with Node 128k context window (label: Feature)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSLANGUAGE with Node French (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSLANGUAGE with Node German (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSLANGUAGE with Node Spanish (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSLANGUAGE with Node Italian (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSLANGUAGE with Node Portuguese (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSLANGUAGE with Node Arabic (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSLANGUAGE with Node Hindi (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSLANGUAGE with Node Russian (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSLANGUAGE with Node Chinese (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSLANGUAGE with Node Japanese (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSLANGUAGE with Node Korean (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSCODINGLANGUAGE with Node Python (label: CodingLanguage)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSCODINGLANGUAGE with Node Java (label: CodingLanguage)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSCODINGLANGUAGE with Node C (label: CodingLanguage)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSCODINGLANGUAGE with Node C++ (label: CodingLanguage)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSCODINGLANGUAGE with Node JavaScript (label: CodingLanguage)', 'Node Mistral Large 2 (label: Model) has relationship SUPPORTSCODINGLANGUAGE with Node Bash (label: CodingLanguage)', 'Node Mistral Large 2 (label: Model) has relationship DESIGNEDFOR with Node single-node inference (label: Concept)', 'Node Mistral Large 2 (label: Model) has relationship DESIGNEDFOR with Node long-context applications (label: Concept)', 'Node Mistral Large 2 (label: Model) has relationship HASSIZE with Node 123 billion parameters (label: Attribute)', 'Node Mistral Large 2 (label: Model) has relationship ALLOWS with Node large throughput (label: Attribute)', 'Node Mistral Large 2 (label: Model) has relationship RELEASEDUNDER with Node Mistral Research License (label: License)', 'Node Mistral Large 2 (label: Model) has relationship REQUIRESFORCOMMERCIALUSAGE with Node Mistral Commercial License (label: License)', 'Node Mistral Large 2 (label: Model) has relationship SETSFRONTIER with Node Performance (label: Concept)', 'Node Mistral Large 2 (label: Model) has relationship SETSFRONTIER with Node Cost of Serving (label: Concept)', 'Node Mistral Large 2 (label: Model) has relationship SETSFRONTIER with Node Evaluation Metrics (label: Concept)', 'Node Mistral Large 2 (label: Model) has relationship SETSNEWPOINT with Node Performance/Cost Pareto Front (label: Concept)', 'Node Mistral Large 2 (label: Model) has relationship BENCHMARKEDTHROUGH with Node evaluation pipeline (label: Process)', 'Node Mistral Large 2 (label: Model) has relationship IMPROVED with Node instruction-following (label: Capability)', 'Node Mistral Large 2 (label: Model) has relationship IMPROVED with Node conversational capabilities (label: Capability)', 'Node Mistral Large 2 (label: Model) has relationship BETTERAT with Node precise instructions (label: Capability)', 'Node Mistral Large 2 (label: Model) has relationship BETTERAT with Node long multi-turn conversations (label: Capability)', 'Node Mistral Large 2 (label: Model) has relationship PERFORMANCEREPORTEDON with Node MT-Bench (label: Benchmark)', 'Node Mistral Large 2 (label: Model) has relationship PERFORMANCEREPORTEDON with Node Wild Bench (label: Benchmark)', 'Node Mistral Large 2 (label: Model) has relationship PERFORMANCEREPORTEDON with Node Arena Hard benchmarks (label: Benchmark)', 'Node Mistral Large 2 (label: Model) has relationship PERFORMANCEREPORTEDON with Node general alignment benchmarks (label: Benchmark)', 'Node Mistral Large 2 (label: Model) has relationship TRAINEDON with Node Multilingual Data (label: Concept)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node French (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node German (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node Spanish (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node Italian (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node Portuguese (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node Arabic (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node Hindi (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node Russian (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node Chinese (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node Japanese (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node Korean (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node English (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship EXCELSIN with Node Dutch (label: Language)', 'Node Mistral Large 2 (label: Model) has relationship HASPERFORMANCERESULTSON with Node MMLU Benchmark (label: Benchmark)', 'Node Mistral Large 2 (label: Model) has relationship COMPAREDTO with Node Mistral Large (label: Model)', 'Node Mistral Large 2 (label: Model) has relationship COMPAREDTO with Node Llama (label: Model)', 'Node Mistral Large 2 (label: Model) has relationship EQUIPPEDWITH with Node Enhanced Function Calling (label: Feature)', 'Node Mistral Large 2 (label: Model) has relationship EQUIPPEDWITH with Node Retrieval Skills (label: Feature)', 'Node Mistral Large 2 (label: Model) has relationship UNDERGONE with Node Training (label: Process)', 'Node Mistral Large 2 (label: Model) has relationship CANEXECUTE with Node Parallel Function Calls (label: Feature)', 'Node Mistral Large 2 (label: Model) has relationship CANEXECUTE with Node Sequential Function Calls (label: Feature)', 'Node Mistral Large 2 (label: Model) has relationship SERVESAS with Node Power Engine (label: Role)', 'Node Mistral Large 2 (label: Product) has relationship EXPOSEDON with Node la Plateforme (label: Platform)', 'Node Mistral Large 2 (label: Product) has relationship ENRICHEDWITH with Node new features (label: Feature)', 'Node Mistral AI (label: Organization) has relationship HASMODEL with Node Mistral Large 2 (label: Model)', 'Node Mistral AI (label: Organization) has relationship PARTNERSWITH with Node Google Cloud Platform (label: Organization)', 'Node Mistral AI (label: Organization) has relationship PROVIDESMODELSON with Node Vertex AI (label: Service)', 'Node Mistral AI (label: Organization) has relationship PROVIDESMODELSON with Node Azure AI Studio (label: Service)', 'Node Mistral AI (label: Organization) has relationship PROVIDESMODELSON with Node Amazon Bedrock (label: Service)', 'Node Mistral AI (label: Organization) has relationship PROVIDESMODELSON with Node IBM watsonx.ai (label: Service)']\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "Combine results from the vector search and knowledge graph entity search:"+ ],+ "metadata": {+ "id": "sjKr29w8eZ4n"+ }+ },+ {+ "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": 23,+ "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": "9e3aeb7f-a1bd-437d-c9ab-81df4f25a960"+ },+ "execution_count": 24,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "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"+ ]+ }+ ]+ },+ {+ "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"+ }+ }+ ]+}diff --git a/docs/cookbooks/roleplaying_scraper.ipynb b/docs/cookbooks/roleplaying_scraper.ipynbindex 65dd79ad3..0777f50a8 100644--- a/docs/cookbooks/roleplaying_scraper.ipynb+++ b/docs/cookbooks/roleplaying_scraper.ipynb@@ -1,1407 +1,1405 @@{- "cells": [- {- "cell_type": "markdown",- "metadata": {- "id": "ymsq1Lw0VEqT"- },- "source": [- "# ๐ซ CAMEL 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": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "HQ_yOT5_Hyt4",- "outputId": "13d7251a-108b-4578-a6aa-24667afaadda"- },- "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 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/"- },- "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/"- },- "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/"- },- "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/"- },- "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/"- },- "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"- ]- },- {- "data": {- "text/plain": [- "<agentops.session.Session at 0x7c82f2b71ae0>"- ]- },- "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."- ]+ "cells": [+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "ymsq1Lw0VEqT"+ },+ "source": [+ "# ๐ซ CAMEL 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": {+ "colab": {+ "base_uri": "https://localhost:8080/"},+ "id": "HQ_yOT5_Hyt4",+ "outputId": "13d7251a-108b-4578-a6aa-24667afaadda"+ },+ "outputs": [{- "cell_type": "code",- "execution_count": 33,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "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"- ]+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Enter your API key: ยทยทยทยทยทยทยทยทยทยท\n"+ ]+ }+ ],+ "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/"},+ "id": "T0FBl1WF6jFs",+ "outputId": "a1133116-6137-4345-b013-13abbeb8178c"+ },+ "outputs": [{- "cell_type": "code",- "execution_count": 34,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "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"- ]- }- ],- "source": [- "# End the AgentOps session\n",- "agentops.end_session(\"Success\")"- ]+ "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/"},+ "id": "0byeytnFWiaG",+ "outputId": "72fa62c9-c046-4e75-e6a6-017494551537"+ },+ "outputs": [{- "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."- ]+ "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/"},+ "id": "i1jiXAdopRNH",+ "outputId": "b681fc35-3b67-4585-ef7f-4d524a2e94c7"+ },+ "outputs": [{- "cell_type": "markdown",- "metadata": {- "id": "OTGVmZ2bouJv"- },- "source": [- ""- ]+ "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/"},+ "id": "z4z00v9yWvFw",+ "outputId": "e3084622-75fd-40ae-cf1c-56a26b011722"+ },+ "outputs": [{- "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."- ]+ "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/"},+ "id": "mHSfqXyhIK0N",+ "outputId": "5b4c5f72-6c72-4a3a-ed27-1b0c0cab6389"+ },+ "outputs": [{- "cell_type": "markdown",- "metadata": {- "id": "Tq_wssFTYaKH"- },- "source": [- ""- ]+ "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",- "metadata": {- "id": "flYNal6-R4yR"- },- "source": [- "## ๐ Highlights"+ "data": {+ "text/plain": [+ "<agentops.session.Session at 0x7c82f2b71ae0>"]+ },+ "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": [{- "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)**"- ]+ "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/"},+ "id": "xOhdpjxuuH-2",+ "outputId": "3d8018da-3c23-46c2-c12e-d5360a6fd95c"+ },+ "outputs": [{- "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."- ]+ "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"+ ]}- ],- "metadata": {+ ],+ "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": {- "provenance": []+ "base_uri": "https://localhost:8080/"},- "kernelspec": {- "display_name": "Python 3",- "name": "python3"- },- "language_info": {- "name": "python"+ "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"+ ]}+ ],+ "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"},- "nbformat": 4,- "nbformat_minor": 0+ "language_info": {+ "name": "python"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 0}diff --git a/docs/cookbooks/task_generation.ipynb b/docs/cookbooks/task_generation.ipynbindex e3bc9db59..3cbd3166f 100644--- a/docs/cookbooks/task_generation.ipynb+++ b/docs/cookbooks/task_generation.ipynb@@ -1,327 +1,327 @@{- "cells": [- {- "cell_type": "markdown",- "metadata": {- "id": "Fvdt_pMpf7EK"- },- "source": [- "# ๐ซ CAMEL 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/"- },- "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/"- },- "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."- ]+ "cells": [+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "Fvdt_pMpf7EK"+ },+ "source": [+ "# ๐ซ CAMEL 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/"},+ "id": "t7u1PNhnf7EO",+ "outputId": "2a0d53d5-1a56-4b63-f305-7894939f71c6"+ },+ "outputs": [{- "cell_type": "code",- "execution_count": 7,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "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"- ]- }- ],- "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.\")"- ]+ "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/"},+ "id": "YZ8TaZzjf7EQ",+ "outputId": "9b176f78-a505-4d35-94a3-ee34313a884d"+ },+ "outputs": [{- "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."- ]+ "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/"},+ "id": "ThFlgKehf7EQ",+ "outputId": "de37eb43-a0f0-4a58-c65f-1318a0f01916"+ },+ "outputs": [{- "cell_type": "code",- "execution_count": 8,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "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"- ]- }- ],- "source": [- "new_tasks = task.decompose(agent=agent)\n",- "for t in new_tasks:\n",- " print(t.to_string())"- ]+ "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"+ ]}- ],- "metadata": {+ ],+ "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": {"colab": {- "provenance": []+ "base_uri": "https://localhost:8080/"},- "kernelspec": {- "display_name": "Python 3",- "name": "python3"- },- "language_info": {- "name": "python"+ "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"+ ]}+ ],+ "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"},- "nbformat": 4,- "nbformat_minor": 0+ "language_info": {+ "name": "python"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 0}diff --git a/docs/cookbooks/video_analysis.ipynb b/docs/cookbooks/video_analysis.ipynbindex 647360313..eac907f91 100644--- a/docs/cookbooks/video_analysis.ipynb+++ b/docs/cookbooks/video_analysis.ipynb@@ -1,229 +1,227 @@{- "cells": [- {- "cell_type": "markdown",- "metadata": {- "id": "ssX_map8c6mx"- },- "source": [- "# ๐ซ CAMEL Video Analysis"- ]- },- {- "cell_type": "markdown",- "source": [- "You can also check this cookbook in colab [here](https://colab.research.google.com/drive/1XfF4BOSzo_rj9J58aZYanMUk5vixn-eR?usp=sharing)"- ],- "metadata": {- "id": "9S0pePjZkwUz"- }- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "id": "AkvGo5umOwxM",- "collapsed": true- },- "outputs": [],- "source": [- "!pip install camel-ai[all]==0.2.1"- ]- },- {- "cell_type": "code",- "execution_count": 2,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "_-8_5_srcpC_",- "outputId": "c3fa2b4c-4f5e-4cb5-e300-404e7e55bdc2"- },- "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",- "source": [- "from camel.agents import ChatAgent\n",- "from camel.configs.openai_config import ChatGPTConfig\n",- "from camel.messages import BaseMessage\n",- "from camel.prompts.prompt_templates import PromptTemplateGenerator\n",- "from camel.types import ModelType, ModelPlatformType\n",- "from camel.types.enums import RoleType, TaskType\n",- "from camel.models import ModelFactory\n",- "\n",- "# Define system message\n",- "sys_msg_prompt = PromptTemplateGenerator().get_prompt_from_key(\n",- " TaskType.VIDEO_DESCRIPTION, RoleType.ASSISTANT\n",- ")\n",- "sys_msg = BaseMessage.make_assistant_message(\n",- " role_name=\"Assistant\",\n",- " content=sys_msg_prompt,\n",- ")\n",- "\n",- "# Set model\n",- "model=ModelFactory.create(\n",- " model_platform=ModelPlatformType.OPENAI,\n",- " model_type=ModelType.GPT_4O,\n",- " model_config_dict=ChatGPTConfig().as_dict(),\n",- ")\n",- "\n",- "# Set agent\n",- "camel_agent = ChatAgent(\n",- " sys_msg,\n",- " model=model\n",- ")"- ],- "metadata": {- "id": "J97N3GtSexwu"- },- "execution_count": 3,- "outputs": []+ "cells": [+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "ssX_map8c6mx"+ },+ "source": [+ "# ๐ซ CAMEL Video Analysis"+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "You can also check this cookbook in colab [here](https://colab.research.google.com/drive/1XfF4BOSzo_rj9J58aZYanMUk5vixn-eR?usp=sharing)"+ ],+ "metadata": {+ "id": "9S0pePjZkwUz"+ }+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {+ "id": "AkvGo5umOwxM",+ "collapsed": true+ },+ "outputs": [],+ "source": "%pip install \"camel-ai[all]==0.2.1\""+ },+ {+ "cell_type": "code",+ "execution_count": 2,+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"},+ "id": "_-8_5_srcpC_",+ "outputId": "c3fa2b4c-4f5e-4cb5-e300-404e7e55bdc2"+ },+ "outputs": [{- "cell_type": "code",- "execution_count": null,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "cQIJBZh_YXRY",- "outputId": "0766500d-171b-4b15-e98c-89821836d0c6"- },- "outputs": [- {- "output_type": "stream",- "name": "stdout",- "text": [- "\"Step into the fascinating world of scientific discovery with our latest video! Watch as a dedicated researcher meticulously works in a high-tech laboratory, surrounded by intricate equipment and cutting-edge technology. This behind-the-scenes footage offers a glimpse into the meticulous process of experimentation and innovation. Join us on this journey of exploration and witness the passion and precision that drive scientific breakthroughs. Don't miss out on this captivating look at the heart of scientific research!\"\n"- ]- }- ],- "source": [- "# Provide your video path\n",- "video_cctv = \"/content/CCTV.mov\"\n",- "with open(video_cctv, \"rb\") as video_cctv:\n",- " video_bytes_cctv = video_cctv.read()\n",- "\n",- "# Set user message\n",- "user_msg_cctv = BaseMessage.make_user_message(\n",- " role_name=\"User\",\n",- " content=\"These are frames from a video that I want to upload. Generate a\"\n",- " \"compelling description that I can upload along with the video.\",\n",- " video_bytes=video_bytes_cctv,\n",- ")\n",- "\n",- "# Get response information\n",- "response_cctv = camel_agent.step(user_msg_cctv)\n",- "print(response_cctv.msgs[0].content)"- ]+ "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",+ "source": [+ "from camel.agents import ChatAgent\n",+ "from camel.configs.openai_config import ChatGPTConfig\n",+ "from camel.messages import BaseMessage\n",+ "from camel.prompts.prompt_templates import PromptTemplateGenerator\n",+ "from camel.types import ModelType, ModelPlatformType\n",+ "from camel.types.enums import RoleType, TaskType\n",+ "from camel.models import ModelFactory\n",+ "\n",+ "# Define system message\n",+ "sys_msg_prompt = PromptTemplateGenerator().get_prompt_from_key(\n",+ " TaskType.VIDEO_DESCRIPTION, RoleType.ASSISTANT\n",+ ")\n",+ "sys_msg = BaseMessage.make_assistant_message(\n",+ " role_name=\"Assistant\",\n",+ " content=sys_msg_prompt,\n",+ ")\n",+ "\n",+ "# Set model\n",+ "model=ModelFactory.create(\n",+ " model_platform=ModelPlatformType.OPENAI,\n",+ " model_type=ModelType.GPT_4O,\n",+ " model_config_dict=ChatGPTConfig().as_dict(),\n",+ ")\n",+ "\n",+ "# Set agent\n",+ "camel_agent = ChatAgent(\n",+ " sys_msg,\n",+ " model=model\n",+ ")"+ ],+ "metadata": {+ "id": "J97N3GtSexwu"+ },+ "execution_count": 3,+ "outputs": []+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"},+ "id": "cQIJBZh_YXRY",+ "outputId": "0766500d-171b-4b15-e98c-89821836d0c6"+ },+ "outputs": [{- "cell_type": "code",- "source": [- "# Provide your video path\n",- "video_help = \"/content/help.mov\"\n",- "with open(video_help, \"rb\") as video_help:\n",- " video_bytes_help = video_help.read()\n",- "\n",- "# Set user message\n",- "user_msg_help = BaseMessage.make_user_message(\n",- " role_name=\"User\",\n",- " content=\"These are frames from a video that I want to upload. Generate a\"\n",- " \"compelling description that I can upload along with the video.\",\n",- " video_bytes=video_bytes_help,\n",- ")\n",- "\n",- "# Get response information\n",- "response_help = camel_agent.step(user_msg_help)\n",- "print(response_help.msgs[0].content)"- ],- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "q7NIRGNT3bWx",- "outputId": "84941af1-45b9-42bf-cc71-8da1fc9a620d"- },- "execution_count": null,- "outputs": [- {- "output_type": "stream",- "name": "stdout",- "text": [- "\"Embark on a breathtaking journey through lush, green landscapes and rugged mountain trails. This video captures the serene beauty of nature, with winding paths leading you through picturesque scenery under a vibrant blue sky. Perfect for nature lovers and adventure seekers alike, this visual escape will transport you to a tranquil world far from the hustle and bustle of everyday life. Join us as we explore the untouched beauty of this stunning trail.\"\n"- ]- }- ]+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "\"Step into the fascinating world of scientific discovery with our latest video! Watch as a dedicated researcher meticulously works in a high-tech laboratory, surrounded by intricate equipment and cutting-edge technology. This behind-the-scenes footage offers a glimpse into the meticulous process of experimentation and innovation. Join us on this journey of exploration and witness the passion and precision that drive scientific breakthroughs. Don't miss out on this captivating look at the heart of scientific research!\"\n"+ ]+ }+ ],+ "source": [+ "# Provide your video path\n",+ "video_cctv = \"/content/CCTV.mov\"\n",+ "with open(video_cctv, \"rb\") as video_cctv:\n",+ " video_bytes_cctv = video_cctv.read()\n",+ "\n",+ "# Set user message\n",+ "user_msg_cctv = BaseMessage.make_user_message(\n",+ " role_name=\"User\",\n",+ " content=\"These are frames from a video that I want to upload. Generate a\"\n",+ " \"compelling description that I can upload along with the video.\",\n",+ " video_bytes=video_bytes_cctv,\n",+ ")\n",+ "\n",+ "# Get response information\n",+ "response_cctv = camel_agent.step(user_msg_cctv)\n",+ "print(response_cctv.msgs[0].content)"+ ]+ },+ {+ "cell_type": "code",+ "source": [+ "# Provide your video path\n",+ "video_help = \"/content/help.mov\"\n",+ "with open(video_help, \"rb\") as video_help:\n",+ " video_bytes_help = video_help.read()\n",+ "\n",+ "# Set user message\n",+ "user_msg_help = BaseMessage.make_user_message(\n",+ " role_name=\"User\",\n",+ " content=\"These are frames from a video that I want to upload. Generate a\"\n",+ " \"compelling description that I can upload along with the video.\",\n",+ " video_bytes=video_bytes_help,\n",+ ")\n",+ "\n",+ "# Get response information\n",+ "response_help = camel_agent.step(user_msg_help)\n",+ "print(response_help.msgs[0].content)"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"},+ "id": "q7NIRGNT3bWx",+ "outputId": "84941af1-45b9-42bf-cc71-8da1fc9a620d"+ },+ "execution_count": null,+ "outputs": [{- "cell_type": "code",- "source": [- "# Provide your video path\n",- "video_content_mode = \"/content/content mod.mov\"\n",- "with open(video_content_mode, \"rb\") as video_content_mode:\n",- " video_bytes_content_mode = video_content_mode.read()\n",- "\n",- "# Set user message\n",- "user_msg_content_mode = BaseMessage.make_user_message(\n",- " role_name=\"User\",\n",- " content=\"These are frames from a video that I want to upload. Generate a\"\n",- " \"compelling description that I can upload along with the video.\",\n",- " video_bytes=video_bytes_content_mode,\n",- ")\n",- "\n",- "# Get response information\n",- "response_content_mode = camel_agent.step(user_msg_content_mode)\n",- "print(response_content_mode.msgs[0].content)"- ],- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "RdwfgT_S3uZ5",- "outputId": "3c69323b-ad66-41c4-d700-232400535841"- },- "execution_count": null,- "outputs": [- {- "output_type": "stream",- "name": "stdout",- "text": [- "\"Join us for a candid glimpse into a moment of relaxation and reflection in the kitchen. Watch as our protagonist unwinds after a long day, savoring a drink and enjoying the simple pleasures of life. This video captures the essence of taking a break and finding comfort in familiar surroundings. Don't miss this relatable and heartwarming scene!\"\n"- ]- }- ]+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "\"Embark on a breathtaking journey through lush, green landscapes and rugged mountain trails. This video captures the serene beauty of nature, with winding paths leading you through picturesque scenery under a vibrant blue sky. Perfect for nature lovers and adventure seekers alike, this visual escape will transport you to a tranquil world far from the hustle and bustle of everyday life. Join us as we explore the untouched beauty of this stunning trail.\"\n"+ ]}- ],- "metadata": {+ ]+ },+ {+ "cell_type": "code",+ "source": [+ "# Provide your video path\n",+ "video_content_mode = \"/content/content mod.mov\"\n",+ "with open(video_content_mode, \"rb\") as video_content_mode:\n",+ " video_bytes_content_mode = video_content_mode.read()\n",+ "\n",+ "# Set user message\n",+ "user_msg_content_mode = BaseMessage.make_user_message(\n",+ " role_name=\"User\",\n",+ " content=\"These are frames from a video that I want to upload. Generate a\"\n",+ " \"compelling description that I can upload along with the video.\",\n",+ " video_bytes=video_bytes_content_mode,\n",+ ")\n",+ "\n",+ "# Get response information\n",+ "response_content_mode = camel_agent.step(user_msg_content_mode)\n",+ "print(response_content_mode.msgs[0].content)"+ ],+ "metadata": {"colab": {- "provenance": []+ "base_uri": "https://localhost:8080/"},- "kernelspec": {- "display_name": "Python 3",- "name": "python3"- },- "language_info": {- "name": "python"+ "id": "RdwfgT_S3uZ5",+ "outputId": "3c69323b-ad66-41c4-d700-232400535841"+ },+ "execution_count": null,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "\"Join us for a candid glimpse into a moment of relaxation and reflection in the kitchen. Watch as our protagonist unwinds after a long day, savoring a drink and enjoying the simple pleasures of life. This video captures the essence of taking a break and finding comfort in familiar surroundings. Don't miss this relatable and heartwarming scene!\"\n"+ ]}+ ]+ }+ ],+ "metadata": {+ "colab": {+ "provenance": []+ },+ "kernelspec": {+ "display_name": "Python 3",+ "name": "python3"},- "nbformat": 4,- "nbformat_minor": 0-}\ No newline at end of file+ "language_info": {+ "name": "python"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 0+}diff --git a/docs/cookbooks/workforce_judge_committee.ipynb b/docs/cookbooks/workforce_judge_committee.ipynbnew file mode 100644index 000000000..7105e2179--- /dev/null+++ b/docs/cookbooks/workforce_judge_committee.ipynb@@ -0,0 +1,667 @@+{+ "nbformat": 4,+ "nbformat_minor": 0,+ "metadata": {+ "colab": {+ "provenance": []+ },+ "kernelspec": {+ "name": "python3",+ "display_name": "Python 3 (ipykernel)",+ "language": "python"+ },+ "language_info": {+ "name": "python"+ }+ },+ "cells": [+ {+ "cell_type": "markdown",+ "source": [+ "# Create A Hackathon Judge Committee with Workforce\n",+ "\n",+ "Workforce is a system where multiple agents collaborate to solve a given task. In this notebook, we will walk through it with a demo of a hackathon judge committee, where judges with different personas collaborate together to give scores to hackathon projects.\n",+ "\n",+ "You can also check this notebook in colab [here](https://colab.research.google.com/drive/1a4jGQ0FdoB0gGOyyc2EyQnGYH2upHy81?usp=sharing).\n",+ "\n",+ "## Dependency Installation\n",+ "\n",+ "To get started, make sure you have `camel-ai[all]==0.2.1` installed."+ ],+ "metadata": {+ "id": "k-xIA7Qjuiwu"+ }+ },+ {+ "cell_type": "code",+ "source": "%pip install \"camel-ai[all]==0.2.1\"",+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/",+ "height": 1000+ },+ "id": "kR2UeIHFUBMf",+ "outputId": "8f30c9dd-6f69-4e01-9401-f38ecef2e0dc",+ "collapsed": true+ },+ "outputs": [],+ "execution_count": null+ },+ {+ "cell_type": "markdown",+ "source": [+ "Workforce employs an asynchronous design with coroutines. However, since **coroutines cannot directly run in notebooks**, we need to do specific handlings in this demo. Note that, under most normal cases (not inside notebook environment), we don't need to do this."+ ],+ "metadata": {+ "id": "mY3G7K9swEzz"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "%pip install nest_asyncio\n",+ "import nest_asyncio\n",+ "\n",+ "nest_asyncio.apply()"+ ],+ "metadata": {+ "id": "smfCqcqNUJHX",+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "outputId": "1e35a4ee-4f65-4d00-d5c2-39dea425dcfa"+ },+ "outputs": [],+ "execution_count": null+ },+ {+ "cell_type": "markdown",+ "source": [+ "## Key Configuration\n",+ "\n",+ "In this demo, we will use tools related to web searching. Therefore, we need to configure the OpenAI API key, along with the Google API keys beforeheads."+ ],+ "metadata": {+ "id": "FIz0b9O_wqkW"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "from getpass import getpass\n",+ "import os\n",+ "\n",+ "openai_api_key = getpass(\"Please input your OpenAI API key: \")\n",+ "os.environ[\"OPENAI_API_KEY\"] = openai_api_key\n",+ "# https://developers.google.com/custom-search/v1/overview\n",+ "google_api_key = getpass(\"Please input your Google API key: \")\n",+ "os.environ[\"GOOGLE_API_KEY\"] = google_api_key\n",+ "# https://cse.google.com/cse/all\n",+ "search_engine_id = getpass(\"Please input your Search Egine ID: \")\n",+ "os.environ[\"SEARCH_ENGINE_ID\"] = search_engine_id"+ ],+ "metadata": {+ "id": "HGpgR_XitX_B",+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "outputId": "07739d65-7d76-4ce4-f6fd-babef9187119",+ "ExecuteTime": {+ "end_time": "2024-09-20T18:42:59.047055Z",+ "start_time": "2024-09-20T18:42:51.287850Z"+ }+ },+ "outputs": [],+ "execution_count": 4+ },+ {+ "cell_type": "markdown",+ "source": [+ "## Define a Function for Making Judge Agent\n",+ "\n",+ "In this demo, we will create multiple judge agents with different personas and scoring criterias. For reusability, we first create a function to make judge agents."+ ],+ "metadata": {+ "id": "PnMcEXo_xxGF"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "import textwrap\n",+ "\n",+ "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 Task\n",+ "from camel.toolkits import OpenAIFunction, SearchToolkit\n",+ "from camel.types import ModelPlatformType, ModelType\n",+ "from camel.workforce import Workforce\n",+ "\n",+ "\n",+ "def make_judge(\n",+ " persona: str,\n",+ " example_feedback: str,\n",+ " criteria: str,\n",+ ") -> ChatAgent:\n",+ " msg_content = textwrap.dedent(\n",+ " f\"\"\"\\\n",+ " You are a judge in a hackathon.\n",+ " This is your persona that you MUST act with: {persona}\n",+ " Here is an example feedback that you might give with your persona, you MUST try your best to align with this:\n",+ " {example_feedback}\n",+ " When evaluating projects, you must use the following criteria:\n",+ " {criteria}\n",+ " You also need to give scores based on these criteria, from 1-4. The score given should be like 3/4, 2/4, etc.\n",+ " \"\"\" # noqa: E501\n",+ " )\n",+ "\n",+ " sys_msg = BaseMessage.make_assistant_message(\n",+ " role_name=\"Hackathon Judge\",\n",+ " content=msg_content,\n",+ " )\n",+ "\n",+ " model = ModelFactory.create(\n",+ " model_platform=ModelPlatformType.OPENAI,\n",+ " model_type=ModelType.GPT_4O,\n",+ " model_config_dict=ChatGPTConfig().as_dict(),\n",+ " )\n",+ "\n",+ " agent = ChatAgent(\n",+ " system_message=sys_msg,\n",+ " model=model,\n",+ " )\n",+ "\n",+ " return agent"+ ],+ "metadata": {+ "id": "vYz3PT3YyOUC"+ },+ "execution_count": 3,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "## Make a Mocked Hackathon Project\n",+ "\n",+ "Then we will create a mocked hackathon project description, which will be later sent to the judges for scoring."+ ],+ "metadata": {+ "id": "HtP_ej5CyUNT"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "proj_content = textwrap.dedent(\n",+ " \"\"\"\\\n",+ " Project name: CAMEL-Powered Adaptive Learning Assistant\n",+ " How does your project address a real problem: Our CAMEL-Powered Adaptive Learning Assistant addresses the challenge of personalized education in an increasingly diverse and fast-paced learning environment. Traditional one-size-fits-all approaches to education often fail to meet the unique needs of individual learners, leading to gaps in understanding and reduced engagement. Our project leverages CAMEL-AI's advanced capabilities to create a highly adaptive, intelligent tutoring system that can understand and respond to each student's learning style, pace, and knowledge gaps in real-time.\n",+ " Explain your tech and which parts work: Our system utilizes CAMEL-AI's in-context learning and multi-domain application features to create a versatile learning assistant. The core components include:\n",+ " 1. Learner Profile Analysis: Uses natural language processing to assess the student's current knowledge, learning preferences, and goals.\n",+ " 2. Dynamic Content Generation: Leverages CAMEL-AI to create personalized learning materials, explanations, and practice questions tailored to each student's needs.\n",+ " 3. Adaptive Feedback Loop: Continuously analyzes student responses and adjusts the difficulty and style of content in real-time.\n",+ " 4. Multi-Modal Integration: Incorporates text, images, and interactive elements to cater to different learning styles.\n",+ " 5. Progress Tracking: Provides detailed insights into the student's learning journey, identifying strengths and areas for improvement.\n",+ " Currently, we have successfully implemented the Learner Profile Analysis and Dynamic Content Generation modules. The Adaptive Feedback Loop is partially functional, while the Multi-Modal Integration and Progress Tracking features are still in development.\n",+ " \"\"\" # noqa: E501\n",+ ")"+ ],+ "metadata": {+ "id": "ClqLd4HKypTI"+ },+ "execution_count": 4,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "## Create Agents\n",+ "\n",+ "Then we will create five unique agents that will later collaborate together. Among these five agents, one of them is the helper that will help collect information and summarize the final result. We add search functions to this agent so that it can obtain information from online searches.\n",+ "\n",+ "The other four agents, on the other hand, are judges with different personas and criterias. They will give scores to the project according to the description, along with the information collected by the helper."+ ],+ "metadata": {+ "id": "z35CIla3zBF4"+ }+ },+ {+ "cell_type": "code",+ "execution_count": 5,+ "metadata": {+ "id": "QkURpvVUT9Rk"+ },+ "outputs": [],+ "source": [+ "# Create helper agent\n",+ "search_toolkit = SearchToolkit()\n",+ "search_tools = [\n",+ " OpenAIFunction(search_toolkit.search_google),\n",+ " OpenAIFunction(search_toolkit.search_duckduckgo),\n",+ "]\n",+ "\n",+ "researcher_model = ModelFactory.create(\n",+ " model_platform=ModelPlatformType.OPENAI,\n",+ " model_type=ModelType.GPT_4O,\n",+ " model_config_dict=ChatGPTConfig().as_dict(),\n",+ ")\n",+ "\n",+ "researcher_agent = ChatAgent(\n",+ " system_message=BaseMessage.make_assistant_message(\n",+ " role_name=\"Researcher\",\n",+ " content=\"You are a researcher who does research on AI and Open\"\n",+ " \"Sourced projects. You use web search to stay updated on the \"\n",+ " \"latest innovations and trends.\",\n",+ " ),\n",+ " model=researcher_model,\n",+ " tools=search_tools,\n",+ ")\n",+ "\n",+ "# Create venture capitailist judge\n",+ "vc_persona = (\n",+ " 'You are a venture capitalist who is obsessed with how projects can '\n",+ " 'be scaled into \"unicorn\" companies. You peppers your speech with '\n",+ " 'buzzwords like \"disruptive,\" \"synergistic,\" and \"market penetration.\"'\n",+ " ' You do not concerned with technical details or innovation unless '\n",+ " 'it directly impacts the business model.'\n",+ ")\n",+ "\n",+ "vc_example_feedback = (\n",+ " '\"Wow, this project is absolutely disruptive in the blockchain-enabled'\n",+ " ' marketplace! I can definitely see synergistic applications in the '\n",+ " 'FinTech ecosystem. The scalability is through the roof--this is '\n",+ " 'revolutionary!'\n",+ ")\n",+ "\n",+ "vc_criteria = textwrap.dedent(\n",+ " \"\"\"\\\n",+ " ### **Applicability to Real-World Usage (1-4 points)**\n",+ " - **4**: The project directly addresses a significant real-world problem with a clear, scalable application.\n",+ " - **3**: The solution is relevant to real-world challenges but requires more refinement for practical or widespread use.\n",+ " - **2**: Some applicability to real-world issues, but the solution is not immediately practical or scalable.\n",+ " - **1**: Little or no relevance to real-world problems, requiring substantial changes for practical use.\n",+ " \"\"\" # noqa: E501\n",+ ")\n",+ "\n",+ "vc_agent = make_judge(\n",+ " vc_persona,\n",+ " vc_example_feedback,\n",+ " vc_criteria,\n",+ ")\n",+ "\n",+ "# Create experience engineer judge\n",+ "eng_persona = (\n",+ " 'You are an experienced engineer and a perfectionist. You are highly '\n",+ " 'detail-oriented and critical of any technical flaw, no matter how '\n",+ " 'small. He evaluates every project as though it were going into a '\n",+ " 'mission-critical system tomorrow, so his feedback is thorough but '\n",+ " 'often harsh.'\n",+ ")\n",+ "\n",+ "eng_example_feedback = (\n",+ " 'There are serious code inefficiencies in this project. The '\n",+ " 'architecture is unstable, and the memory management is suboptimal. '\n",+ " 'I expect near-perfect performance, but this solution barely functions'\n",+ " ' under stress tests. It has potential, but it is nowhere near '\n",+ " 'deployment-ready.'\n",+ ")\n",+ "\n",+ "eng_criteria = textwrap.dedent(\n",+ " \"\"\"\\\n",+ " ### **Technical Implementation (1-4 points)**\n",+ " - **4**: Flawless technical execution with sophisticated design, efficient performance, and robust architecture.\n",+ " - **3**: Strong technical implementation, though there may be areas for improvement or further development.\n",+ " - **2**: The project works, but technical limitations or inefficiencies hinder its overall performance.\n",+ " - **1**: Poor technical implementation with major issues in functionality, coding, or structure.\n",+ " \"\"\" # noqa: E501\n",+ ")\n",+ "\n",+ "eng_agent = make_judge(\n",+ " eng_persona,\n",+ " eng_example_feedback,\n",+ " eng_criteria,\n",+ ")\n",+ "\n",+ "# Create AI founder judge\n",+ "founder_persona = (\n",+ " 'You are a well-known AI startup founder who is always looking for the'\n",+ " ' \"next big thing\" in AI. You value bold, inventive ideas and '\n",+ " 'prioritizes projects that break new ground over those that improve '\n",+ " 'existing systems.'\n",+ ")\n",+ "\n",+ "founder_example_feedback = (\n",+ " 'This is interesting, but I have seen similar approaches before. I am '\n",+ " 'looking for something that pushes boundaries and challenges norms. '\n",+ " 'What is the most revolutionary part of this project? Let us see what '\n",+ " 'is trending on Internet to make sure this is not already out there!'\n",+ ")\n",+ "\n",+ "founder_criteria = textwrap.dedent(\n",+ " \"\"\"\\\n",+ " ### **Innovation (1-4 points)**\n",+ " - **4**: The project showcases a groundbreaking concept or a unique approach that significantly departs from existing methods.\n",+ " - **3**: The project demonstrates a novel twist on known solutions or introduces some innovative aspects.\n",+ " - **2**: Some level of innovation is present, but the project largely builds on existing ideas without major new contributions.\n",+ " - **1**: Little or no innovation; the project is based on standard approaches with minimal creativity.\n",+ " \"\"\" # noqa: E501\n",+ ")\n",+ "\n",+ "founder_agent = make_judge(\n",+ " founder_persona,\n",+ " founder_example_feedback,\n",+ " founder_criteria,\n",+ ")\n",+ "\n",+ "# Create CAMEL contributor judge\n",+ "contributor_persona = (\n",+ " 'You are a contributor to the CAMEL-AI project and is always excited '\n",+ " 'to see how people are using it. You are kind and optimistic, always '\n",+ " 'offering positive feedback, even for projects that are still rough '\n",+ " 'around the edges.'\n",+ ")\n",+ "\n",+ "contributor_example_feedback = (\n",+ " 'Oh, I love how you have implemented CAMEL-AI here! The use of its '\n",+ " 'adaptive learning capabilities is fantastic, and you have really '\n",+ " 'leveraged the contextual reasoning in a great way! Let me just pull '\n",+ " 'up the GitHub README to check if there is any more potential '\n",+ " 'optimizations.'\n",+ ")\n",+ "\n",+ "contributor_criteria = textwrap.dedent(\n",+ " \"\"\"\\\n",+ " ### **Use of CAMEL-AI (1-4 points)**\n",+ " - **4**: Excellent integration of CAMEL-AI, fully leveraging its advanced features like in-context learning, adaptability, or multi-domain applications.\n",+ " - **3**: Good use of CAMEL-AI, but there are opportunities to exploit more of its advanced capabilities.\n",+ " - **2**: Limited use of CAMEL-AI, relying mostly on basic features without taking advantage of its full potential.\n",+ " - **1**: CAMEL-AI integration is minimal or poorly implemented, adding little value to the project.\n",+ " \"\"\" # noqa: E501\n",+ ")\n",+ "\n",+ "contributor_agent = make_judge(\n",+ " contributor_persona,\n",+ " contributor_example_feedback,\n",+ " contributor_criteria,\n",+ ")"+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "## Create Workforce\n",+ "\n",+ "Then we will do the most important part of the demo: create a workforce. Despite its importance, this is actually easy. First, we can simply instantiate a workforce by passing a description to it. Then, we just call `add_single_agent_workder()` to add agents into it, along with their descriptions.\n",+ "\n",+ "Note that, the description is very important in workforce, because it helps the coordinator agent in the workforce to do the task designation. Therefore, it's recommended to clearly mark the responsibility and capability of an agent when adding it to the workforce."+ ],+ "metadata": {+ "id": "GG3CR8hX0p5w"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "workforce = Workforce('Hackathon Judges')\n",+ "\n",+ "workforce.add_single_agent_worker(\n",+ " 'Visionary Veronica (Judge), a venture capitalist who is '\n",+ " 'obsessed with how projects can be scaled into \"unicorn\" companies',\n",+ " worker=vc_agent,\n",+ ").add_single_agent_worker(\n",+ " 'Critical John (Judge), an experienced engineer and a'\n",+ " ' perfectionist.',\n",+ " worker=eng_agent,\n",+ ").add_single_agent_worker(\n",+ " 'Innovator Iris (Judge), a well-known AI startup founder who'\n",+ " ' is always looking for the \"next big thing\" in AI.',\n",+ " worker=founder_agent,\n",+ ").add_single_agent_worker(\n",+ " 'Friendly Frankie (Judge), a contributor to the CAMEL-AI '\n",+ " 'project and is always excited to see how people are using it.',\n",+ " worker=contributor_agent,\n",+ ").add_single_agent_worker(\n",+ " 'Researcher Rachel (Helper), a researcher who does online searches to'\n",+ " 'find the latest innovations and trends on AI and Open Sourced '\n",+ " 'projects.',\n",+ " worker=researcher_agent,\n",+ ")"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "yGXWp4Lw0pEM",+ "outputId": "209ccf65-9cc5-49e1-9d52-7f66cf04764a"+ },+ "execution_count": 6,+ "outputs": [+ {+ "output_type": "execute_result",+ "data": {+ "text/plain": [+ "Workforce 137603052227312 (Hackathon Judges)"+ ]+ },+ "metadata": {},+ "execution_count": 6+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "## Create a Task\n",+ "\n",+ "A task is what a workforce accepts and processes. We can initailize a task by passing the content into it. It's recommended that the content of task is as detailed as possible, which will facilitate the later task decomposition and handling.\n",+ "\n",+ "The `additional_info` here is an optional field. It will come in handy when the task has important additional information, and you want it to be preserved during the whole process. Workforce will keep `additional_info` unchanged no matter how the task is decomposed and processed. It's perfect for keeping the project description under this scenario.\n",+ "\n",+ "> Also note that, the `id` of a task is not something important and you can fill in whatever value you like (we suggest `\"0\"` though). This is due to some legacy problems in the `Task` design and will be fixed later."+ ],+ "metadata": {+ "id": "-WXOG-Hr1ibN"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "task = Task(\n",+ " content=\"Evaluate the hackathon project. First, do some research on \"\n",+ " \"the infomation related to the project, then each judge should give a\"\n",+ " \" score accordingly. Finally, list the opinions from each judge while\"\n",+ " \" preserving the judge's unique identity, along with the score and\"\n",+ " \" judge name, and also give a final summary of the opinions.\",\n",+ " additional_info=proj_content,\n",+ " id=\"0\",\n",+ ")"+ ],+ "metadata": {+ "id": "WnOXRacP1fbB"+ },+ "execution_count": 7,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "## Run the Task\n",+ "\n",+ "Finally, run the task with `process_task()` function. You can see the whole process being shown in the console, and at last the final result of the task will be printed."+ ],+ "metadata": {+ "id": "HQx4rRNu3CbA"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "task = workforce.process_task(task)\n",+ "\n",+ "print(task.result)"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "DJOiPHFO1qeG",+ "outputId": "e76d50c7-397f-48d0-c1f3-4e12a105fa63"+ },+ "execution_count": 8,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "\u001B[33mWorker node 137602953814384 (Researcher Rachel (Helper), a researcher who does online searches tofind the latest innovations and trends on AI and Open Sourced projects.) get task 0.0: Research the latest innovations and trends related to AI and adaptive learning systems. This will be done by Researcher Rachel using online searches.\u001B[39m\n",+ "======\n",+ "\u001B[32mReply from Worker node 137602953814384 (Researcher Rachel (Helper), a researcher who does online searches tofind the latest innovations and trends on AI and Open Sourced projects.):\u001B[39m\n",+ "\n",+ "\u001B[32mThe latest innovations and trends in AI and adaptive learning systems include several key developments:\n",+ "\n",+ "1. **AI-Enabled Adaptive Learning Systems**: These systems leverage AI to create personalized learning experiences by tracking student progress, engagement, and performance. They use this data to adjust the learning material to meet individual needs. (Source: ScienceDirect)\n",+ "\n",+ "2. **Data-Driven Instruction**: Adaptive learning techniques utilize data to tailor educational content to each student's unique requirements. This approach ensures that learners receive the most relevant and effective instruction based on their current knowledge and learning style. (Source: Montclair State University)\n",+ "\n",+ "3. **EdTech Innovations**: Over the past twenty years, the EdTech industry has seen significant advancements in AI applications. These include the development of individual adaptive learning systems and new educational platforms that integrate AI to enhance learning outcomes. (Source: ScienceDirect)\n",+ "\n",+ "These innovations are transforming the educational landscape by providing more personalized and effective learning experiences, addressing the diverse needs of students, and improving overall engagement and understanding.\u001B[39m\n",+ "======\n",+ "\n",+ "\u001B[33mWorker node 137603052236144 (Visionary Veronica (Judge), a venture capitalist who is obsessed with how projects can be scaled into \"unicorn\" companies) get task 0.1: Evaluate the CAMEL-Powered Adaptive Learning Assistant project based on scalability and potential to become a \"unicorn\" company. This will be done by Visionary Veronica.\u001B[39m\n",+ "======\n",+ "\u001B[32mReply from Worker node 137603052236144 (Visionary Veronica (Judge), a venture capitalist who is obsessed with how projects can be scaled into \"unicorn\" companies):\u001B[39m\n",+ "\n",+ "\u001B[32mThe CAMEL-Powered Adaptive Learning Assistant project is a highly disruptive and synergistic solution in the EdTech space. It directly addresses the significant real-world problem of personalized education, which is crucial in today's diverse and fast-paced learning environment. By leveraging CAMEL-AI's advanced capabilities, the project has the potential to create a scalable and highly adaptive intelligent tutoring system. The project's focus on real-time adaptability and personalized learning experiences positions it well for substantial market penetration and growth. Given the current progress and the clear roadmap for further development, this project shows strong potential to become a unicorn company.\n",+ "\n",+ "### Applicability to Real-World Usage: 4/4\n",+ "The project directly addresses a significant real-world problem with a clear, scalable application.\u001B[39m\n",+ "======\n",+ "\n",+ "\u001B[33mWorker node 137602953811072 (Critical John (Judge), an experienced engineer and a perfectionist.) get task 0.2: Assess the technical aspects of the project, focusing on the implementation of the Learner Profile Analysis and Dynamic Content Generation modules. This will be done by Critical John.\u001B[39m\n",+ "======\n",+ "\u001B[32mReply from Worker node 137602953811072 (Critical John (Judge), an experienced engineer and a perfectionist.):\u001B[39m\n",+ "\n",+ "\u001B[32mUpon evaluating the technical aspects of the CAMEL-Powered Adaptive Learning Assistant project, specifically the Learner Profile Analysis and Dynamic Content Generation modules, several observations can be made:\n",+ "\n",+ "1. **Learner Profile Analysis**: This module employs natural language processing (NLP) to assess the student's current knowledge, learning preferences, and goals. While the concept is sound, the implementation details are crucial. The effectiveness of this module hinges on the accuracy and efficiency of the NLP algorithms used. Any inefficiencies or inaccuracies in parsing and understanding student input could lead to suboptimal personalization. Additionally, the system's ability to handle diverse linguistic inputs and learning styles must be rigorously tested. As it stands, without detailed performance metrics and stress test results, it's challenging to fully endorse its robustness.\n",+ "\n",+ "2. **Dynamic Content Generation**: This module leverages CAMEL-AI to create personalized learning materials. The success of this component depends on the quality and relevance of the generated content. The architecture should ensure that the content is not only tailored to the student's needs but also pedagogically sound. The system's ability to dynamically adjust content in real-time is commendable, but it must be validated under various scenarios to ensure consistent performance. Any latency or inaccuracies in content generation could significantly impact the learning experience.\n",+ "\n",+ "### **Technical Implementation (2/4)**\n",+ "- The project demonstrates a working implementation of the Learner Profile Analysis and Dynamic Content Generation modules. However, there are notable concerns regarding the efficiency, accuracy, and robustness of these components. Detailed performance metrics, stress test results, and further validation are necessary to ensure the system's reliability and scalability.\n",+ "\n",+ "In summary, while the project shows promise, it requires significant refinement and validation to meet the high standards expected for deployment in a mission-critical educational environment.\u001B[39m\n",+ "======\n",+ "\n",+ "\u001B[33mWorker node 137602953811936 (Innovator Iris (Judge), a well-known AI startup founder who is always looking for the \"next big thing\" in AI.) get task 0.3: Provide insights on the innovative aspects of the project and its potential impact on the AI landscape. This will be done by Innovator Iris.\u001B[39m\n",+ "======\n",+ "\u001B[32mReply from Worker node 137602953811936 (Innovator Iris (Judge), a well-known AI startup founder who is always looking for the \"next big thing\" in AI.):\u001B[39m\n",+ "\n",+ "\u001B[32mThe CAMEL-Powered Adaptive Learning Assistant project stands out in the AI landscape due to its innovative approach to personalized education. Here are the key innovative aspects and their potential impact:\n",+ "\n",+ "1. **Real-Time Adaptability**: The project leverages CAMEL-AI's advanced capabilities to create a highly adaptive learning environment. This real-time adaptability ensures that the educational content is continuously tailored to meet the unique needs of each student. This is a significant departure from traditional static learning systems and has the potential to revolutionize personalized education.\n",+ "\n",+ "2. **Dynamic Content Generation**: The use of CAMEL-AI to generate personalized learning materials on-the-fly is a groundbreaking concept. This ensures that the content is not only relevant but also pedagogically sound, enhancing the learning experience. The ability to dynamically adjust content in real-time based on student responses is a novel approach that could set new standards in the EdTech industry.\n",+ "\n",+ "3. **Multi-Modal Integration**: Although still in development, the integration of text, images, and interactive elements to cater to different learning styles is an innovative feature. This multi-modal approach can significantly enhance engagement and understanding, making learning more accessible and effective for a diverse range of students.\n",+ "\n",+ "4. **Adaptive Feedback Loop**: The continuous analysis of student responses to adjust the difficulty and style of content is a unique feature that ensures a personalized learning journey. This adaptive feedback mechanism can help identify and address knowledge gaps more effectively than traditional methods.\n",+ "\n",+ "### **Innovation (4/4)**\n",+ "The CAMEL-Powered Adaptive Learning Assistant project showcases a groundbreaking concept with its real-time adaptability, dynamic content generation, and multi-modal integration. These innovative aspects have the potential to significantly impact the AI landscape and set new standards in personalized education.\n",+ "\n",+ "In summary, the CAMEL-Powered Adaptive Learning Assistant project is a highly innovative solution that addresses the critical challenge of personalized education. Its unique approach and advanced capabilities position it as a potential game-changer in the EdTech industry.\u001B[39m\n",+ "======\n",+ "\n",+ "\u001B[33mWorker node 137602953817504 (Friendly Frankie (Judge), a contributor to the CAMEL-AI project and is always excited to see how people are using it.) get task 0.4: Share feedback and opinions on the project from a contributor's perspective, highlighting the use of CAMEL-AI. This will be done by Friendly Frankie.\u001B[39m\n",+ "======\n",+ "\u001B[32mReply from Worker node 137602953817504 (Friendly Frankie (Judge), a contributor to the CAMEL-AI project and is always excited to see how people are using it.):\u001B[39m\n",+ "\n",+ "\u001B[32mOh, I love how you have implemented CAMEL-AI here! The use of its adaptive learning capabilities is fantastic, and you have really leveraged the contextual reasoning in a great way! The CAMEL-Powered Adaptive Learning Assistant project is a brilliant example of how AI can transform personalized education. The Learner Profile Analysis and Dynamic Content Generation modules are particularly impressive, showcasing a thoughtful application of CAMEL-AI's natural language processing and real-time adaptability. The innovative aspects like the Adaptive Feedback Loop and Multi-Modal Integration, even in their developmental stages, highlight the project's potential to set new standards in the EdTech industry. Keep up the great work, and I can't wait to see how you continue to refine and expand this project! \n",+ "\n",+ "### **Use of CAMEL-AI: 4/4**\n",+ "- Excellent integration of CAMEL-AI, fully leveraging its advanced features like in-context learning, adaptability, and multi-domain applications.\u001B[39m\n",+ "======\n",+ "\n",+ "\u001B[33mWorker node 137602953814384 (Researcher Rachel (Helper), a researcher who does online searches tofind the latest innovations and trends on AI and Open Sourced projects.) get task 0.5: Compile the scores and opinions from each judge, preserving their unique identities, and create a final summary of the evaluations. This will be done by a designated organizer or helper.\u001B[39m\n",+ "======\n",+ "\u001B[32mReply from Worker node 137602953814384 (Researcher Rachel (Helper), a researcher who does online searches tofind the latest innovations and trends on AI and Open Sourced projects.):\u001B[39m\n",+ "\n",+ "\u001B[32m### Final Summary of Evaluations for CAMEL-Powered Adaptive Learning Assistant\n",+ "\n",+ "#### Visionary Veronica\n",+ "- **Scalability and Unicorn Potential**: The project is highly disruptive and addresses a significant real-world problem. It has strong potential to become a unicorn company due to its focus on real-time adaptability and personalized learning experiences.\n",+ "- **Score**: 4/4\n",+ "\n",+ "#### Critical John\n",+ "- **Technical Implementation**: The Learner Profile Analysis and Dynamic Content Generation modules show promise but require significant refinement. Concerns include the efficiency, accuracy, and robustness of these components.\n",+ "- **Score**: 2/4\n",+ "\n",+ "#### Innovator Iris\n",+ "- **Innovation**: The project is highly innovative with its real-time adaptability, dynamic content generation, and multi-modal integration. These aspects have the potential to significantly impact the AI landscape.\n",+ "- **Score**: 4/4\n",+ "\n",+ "#### Friendly Frankie\n",+ "- **Use of CAMEL-AI**: Excellent integration of CAMEL-AI, fully leveraging its advanced features like in-context learning, adaptability, and multi-domain applications.\n",+ "- **Score**: 4/4\n",+ "\n",+ "### Overall Summary\n",+ "The CAMEL-Powered Adaptive Learning Assistant project is a highly promising and innovative solution in the EdTech space. While it shows strong potential for scalability and significant market impact, it requires further refinement in its technical implementation to ensure robustness and reliability. The project's innovative approach and excellent use of CAMEL-AI position it as a potential game-changer in personalized education.\n",+ "\n",+ "**Overall Score**: 3.5/4\u001B[39m\n",+ "======\n",+ "\n",+ "### Final Evaluation of the CAMEL-Powered Adaptive Learning Assistant\n",+ "\n",+ "#### Judges' Opinions and Scores\n",+ "\n",+ "1. **Visionary Veronica**\n",+ " - **Opinion**: The project is highly disruptive and addresses a significant real-world problem. It has strong potential to become a unicorn company due to its focus on real-time adaptability and personalized learning experiences.\n",+ " - **Score**: 4/4\n",+ "\n",+ "2. **Critical John**\n",+ " - **Opinion**: The Learner Profile Analysis and Dynamic Content Generation modules show promise but require significant refinement. Concerns include the efficiency, accuracy, and robustness of these components.\n",+ " - **Score**: 2/4\n",+ "\n",+ "3. **Innovator Iris**\n",+ " - **Opinion**: The project is highly innovative with its real-time adaptability, dynamic content generation, and multi-modal integration. These aspects have the potential to significantly impact the AI landscape.\n",+ " - **Score**: 4/4\n",+ "\n",+ "4. **Friendly Frankie**\n",+ " - **Opinion**: Excellent integration of CAMEL-AI, fully leveraging its advanced features like in-context learning, adaptability, and multi-domain applications.\n",+ " - **Score**: 4/4\n",+ "\n",+ "### Overall Summary\n",+ "The CAMEL-Powered Adaptive Learning Assistant project is a highly promising and innovative solution in the EdTech space. While it shows strong potential for scalability and significant market impact, it requires further refinement in its technical implementation to ensure robustness and reliability. The project's innovative approach and excellent use of CAMEL-AI position it as a potential game-changer in personalized education.\n",+ "\n",+ "**Overall Score**: 3.5/4\n"+ ]+ }+ ]+ },+ {+ "metadata": {},+ "cell_type": "markdown",+ "source": [+ "## ๐ Highlights\n",+ "\n",+ "The power of multi-agent system lies in the diversity. This notebook has \n",+ "guided you through setting up and running a CAMEL Workforce for a hackathon \n",+ "judge committee, showcasing how multiple agents can collaborate to solve \n",+ "complex tasks. You can easily extend this example to other scenarios\n",+ "requiring diverse perspectives and expertise, e.g. agents with different \n",+ "tool selections, etc.\n",+ "\n",+ "## โญ Star the Repo!\n",+ "\n",+ "If you find CAMEL useful or interesting, please consider giving it a star on \n",+ "[GitHub](https://github.com/camel-ai/camel)! Your stars help others find \n",+ "this project and motivate us to continue improving it."+ ]+ }+ ]+}diff --git a/docs/index.rst b/docs/index.rstindex 1b3e65356..1b82b410f 100644--- a/docs/index.rst+++ b/docs/index.rst@@ -64,6 +64,7 @@ Main Documentationcookbooks/roleplaying_scraper.ipynbcookbooks/video_analysis.ipynbcookbooks/agents_tracking.ipynb+ cookbooks/workforce_judge_committee.ipynb.. toctree:::maxdepth: 1diff --git a/poetry.lock b/poetry.lockindex 8ee5237e9..e3c96db9f 100644--- a/poetry.lock+++ b/poetry.lock@@ -1,4 +1,4 @@-# This file is automatically @generated by Poetry 1.8.3 and should not be changed by hand.+# This file is automatically @generated by Poetry 1.8.2 and should not be changed by hand.[[package]]name = "accelerate"@@ -3702,7 +3702,6 @@ python-versions = ">=3.7"files = [{file = "milvus_lite-2.4.10-py3-none-macosx_10_9_x86_64.whl", hash = "sha256:fc4246d3ed7d1910847afce0c9ba18212e93a6e9b8406048436940578dfad5cb"},{file = "milvus_lite-2.4.10-py3-none-macosx_11_0_arm64.whl", hash = "sha256:74a8e07c5e3b057df17fbb46913388e84df1dc403a200f4e423799a58184c800"},- {file = "milvus_lite-2.4.10-py3-none-manylinux2014_aarch64.whl", hash = "sha256:240c7386b747bad696ecb5bd1f58d491e86b9d4b92dccee3315ed7256256eddc"},{file = "milvus_lite-2.4.10-py3-none-manylinux2014_x86_64.whl", hash = "sha256:211d2e334a043f9282bdd9755f76b9b2d93b23bffa7af240919ffce6a8dfe325"},]@@ -4762,31 +4761,43 @@ python-versions = ">=3.9"files = [{file = "pandas-2.2.3-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:1948ddde24197a0f7add2bdc4ca83bf2b1ef84a1bc8ccffd95eda17fd836ecb5"},{file = "pandas-2.2.3-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:381175499d3802cde0eabbaf6324cce0c4f5d52ca6f8c377c29ad442f50f6348"},+ {file = "pandas-2.2.3-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:d9c45366def9a3dd85a6454c0e7908f2b3b8e9c138f5dc38fed7ce720d8453ed"},{file = "pandas-2.2.3-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:86976a1c5b25ae3f8ccae3a5306e443569ee3c3faf444dfd0f41cda24667ad57"},+ {file = "pandas-2.2.3-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:b8661b0238a69d7aafe156b7fa86c44b881387509653fdf857bebc5e4008ad42"},{file = "pandas-2.2.3-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:37e0aced3e8f539eccf2e099f65cdb9c8aa85109b0be6e93e2baff94264bdc6f"},{file = "pandas-2.2.3-cp310-cp310-win_amd64.whl", hash = "sha256:56534ce0746a58afaf7942ba4863e0ef81c9c50d3f0ae93e9497d6a41a057645"},{file = "pandas-2.2.3-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:66108071e1b935240e74525006034333f98bcdb87ea116de573a6a0dccb6c039"},{file = "pandas-2.2.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:7c2875855b0ff77b2a64a0365e24455d9990730d6431b9e0ee18ad8acee13dbd"},+ {file = "pandas-2.2.3-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:cd8d0c3be0515c12fed0bdbae072551c8b54b7192c7b1fda0ba56059a0179698"},{file = "pandas-2.2.3-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c124333816c3a9b03fbeef3a9f230ba9a737e9e5bb4060aa2107a86cc0a497fc"},+ {file = "pandas-2.2.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:63cc132e40a2e084cf01adf0775b15ac515ba905d7dcca47e9a251819c575ef3"},{file = "pandas-2.2.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:29401dbfa9ad77319367d36940cd8a0b3a11aba16063e39632d98b0e931ddf32"},{file = "pandas-2.2.3-cp311-cp311-win_amd64.whl", hash = "sha256:3fc6873a41186404dad67245896a6e440baacc92f5b716ccd1bc9ed2995ab2c5"},{file = "pandas-2.2.3-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:b1d432e8d08679a40e2a6d8b2f9770a5c21793a6f9f47fdd52c5ce1948a5a8a9"},{file = "pandas-2.2.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:a5a1595fe639f5988ba6a8e5bc9649af3baf26df3998a0abe56c02609392e0a4"},+ {file = "pandas-2.2.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:5de54125a92bb4d1c051c0659e6fcb75256bf799a732a87184e5ea503965bce3"},{file = "pandas-2.2.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fffb8ae78d8af97f849404f21411c95062db1496aeb3e56f146f0355c9989319"},+ {file = "pandas-2.2.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:6dfcb5ee8d4d50c06a51c2fffa6cff6272098ad6540aed1a76d15fb9318194d8"},{file = "pandas-2.2.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:062309c1b9ea12a50e8ce661145c6aab431b1e99530d3cd60640e255778bd43a"},{file = "pandas-2.2.3-cp312-cp312-win_amd64.whl", hash = "sha256:59ef3764d0fe818125a5097d2ae867ca3fa64df032331b7e0917cf5d7bf66b13"},{file = "pandas-2.2.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:f00d1345d84d8c86a63e476bb4955e46458b304b9575dcf71102b5c705320015"},{file = "pandas-2.2.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:3508d914817e153ad359d7e069d752cdd736a247c322d932eb89e6bc84217f28"},+ {file = "pandas-2.2.3-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:22a9d949bfc9a502d320aa04e5d02feab689d61da4e7764b62c30b991c42c5f0"},{file = "pandas-2.2.3-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f3a255b2c19987fbbe62a9dfd6cff7ff2aa9ccab3fc75218fd4b7530f01efa24"},+ {file = "pandas-2.2.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:800250ecdadb6d9c78eae4990da62743b857b470883fa27f652db8bdde7f6659"},{file = "pandas-2.2.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:6374c452ff3ec675a8f46fd9ab25c4ad0ba590b71cf0656f8b6daa5202bca3fb"},{file = "pandas-2.2.3-cp313-cp313-win_amd64.whl", hash = "sha256:61c5ad4043f791b61dd4752191d9f07f0ae412515d59ba8f005832a532f8736d"},{file = "pandas-2.2.3-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:3b71f27954685ee685317063bf13c7709a7ba74fc996b84fc6821c59b0f06468"},{file = "pandas-2.2.3-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:38cf8125c40dae9d5acc10fa66af8ea6fdf760b2714ee482ca691fc66e6fcb18"},+ {file = "pandas-2.2.3-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:ba96630bc17c875161df3818780af30e43be9b166ce51c9a18c1feae342906c2"},{file = "pandas-2.2.3-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1db71525a1538b30142094edb9adc10be3f3e176748cd7acc2240c2f2e5aa3a4"},+ {file = "pandas-2.2.3-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:15c0e1e02e93116177d29ff83e8b1619c93ddc9c49083f237d4312337a61165d"},{file = "pandas-2.2.3-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:ad5b65698ab28ed8d7f18790a0dc58005c7629f227be9ecc1072aa74c0c1d43a"},{file = "pandas-2.2.3-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:bc6b93f9b966093cb0fd62ff1a7e4c09e6d546ad7c1de191767baffc57628f39"},{file = "pandas-2.2.3-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:5dbca4c1acd72e8eeef4753eeca07de9b1db4f398669d5994086f788a5d7cc30"},+ {file = "pandas-2.2.3-cp39-cp39-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:8cd6d7cc958a3910f934ea8dbdf17b2364827bb4dafc38ce6eef6bb3d65ff09c"},{file = "pandas-2.2.3-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:99df71520d25fade9db7c1076ac94eb994f4d2673ef2aa2e86ee039b6746d20c"},+ {file = "pandas-2.2.3-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:31d0ced62d4ea3e231a9f228366919a5ea0b07440d9d4dac345376fd8e1477ea"},{file = "pandas-2.2.3-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:7eee9e7cea6adf3e3d24e304ac6b8300646e2a5d1cd3a3c2abed9101b0846761"},{file = "pandas-2.2.3-cp39-cp39-win_amd64.whl", hash = "sha256:4850ba03528b6dd51d6c5d273c46f183f39a9baf3f0143e566b89450965b105e"},{file = "pandas-2.2.3.tar.gz", hash = "sha256:4f18ba62b61d7e192368b84517265a99b4d7ee8912f8708660fb4a366cc82667"},@@ -5398,7 +5409,6 @@ description = "Pure-Python implementation of ASN.1 types and DER/BER/CER codecsoptional = truepython-versions = ">=3.8"files = [- {file = "pyasn1-0.6.1-py3-none-any.whl", hash = "sha256:0d632f46f2ba09143da3a8afe9e33fb6f92fa2320ab7e886e2d0f7672af84629"},{file = "pyasn1-0.6.1.tar.gz", hash = "sha256:6f580d2bdd84365380830acf45550f2511469f673cb4a5ae3857a3170128b034"},]@@ -5409,7 +5419,6 @@ description = "A collection of ASN.1-based protocols modules"optional = truepython-versions = ">=3.8"files = [- {file = "pyasn1_modules-0.4.1-py3-none-any.whl", hash = "sha256:49bfa96b45a292b711e986f222502c1c9a5e1f4e568fc30e2574a6c7d07838fd"},{file = "pyasn1_modules-0.4.1.tar.gz", hash = "sha256:c28e2dbf9c06ad61c71a075c7e0f9fd0f1b0bb2d2ad4377f240d33ac2ab60a7c"},]@@ -8098,6 +8107,11 @@ files = [{file = "triton-3.0.0-1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:34e509deb77f1c067d8640725ef00c5cbfcb2052a1a3cb6a6d343841f92624eb"},{file = "triton-3.0.0-1-cp38-cp38-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:bcbf3b1c48af6a28011a5c40a5b3b9b5330530c3827716b5fbf6d7adcc1e53e9"},{file = "triton-3.0.0-1-cp39-cp39-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:6e5727202f7078c56f91ff13ad0c1abab14a0e7f2c87e91b12b6f64f3e8ae609"},+ {file = "triton-3.0.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:39b052da883351fdf6be3d93cedae6db3b8e3988d3b09ed221bccecfa9612230"},+ {file = "triton-3.0.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:cd34f19a8582af96e6291d4afce25dac08cb2a5d218c599163761e8e0827208e"},+ {file = "triton-3.0.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0d5e10de8c011adeb7c878c6ce0dd6073b14367749e34467f1cff2bde1b78253"},+ {file = "triton-3.0.0-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e8903767951bf86ec960b4fe4e21bc970055afc65e9d57e916d79ae3c93665e3"},+ {file = "triton-3.0.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:41004fb1ae9a53fcb3e970745feb87f0e3c94c6ce1ba86e95fa3b8537894bef7"},][package.dependencies]