Skip to content

armgit / camel

Public Imported from GitHub
0

🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org

22.2 KB
Raw Blame
{
  "cells": [
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "SQMBlxsBv1cH"
      },
      "source": [
        "# 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).\n",
        "\n",
        "<div class=\"align-center\">\n",
        "  <a href=\"https://www.camel-ai.org/\"><img src=\"https://i.postimg.cc/KzQ5rfBC/button.png\"width=\"150\"></a>\n",
        "  <a href=\"https://discord.camel-ai.org\"><img src=\"https://i.postimg.cc/L4wPdG9N/join-2.png\"  width=\"150\"></a></a>\n",
        "  \n",
        "⭐ <i>Star us on [*Github*](https://github.com/camel-ai/camel), join our [*Discord*](https://discord.camel-ai.org) or follow our [*X*](https://x.com/camelaiorg)\n",
        "</div>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "This notebook demonstrates how to set up and leverage CAMEL's ability to use **Prompt** module. \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",
        "\n",
        "* **Prompt**: Interface to communicate with models with various 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.16\""
      ]
    },
    {
      "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": "781a8745-1042-4d30-d5b0-25da839667bd"
      },
      "outputs": [],
      "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": {},
      "source": [
        "Alternatively, if running on Colab, you could save your API keys and tokens as **Colab Secrets**,\n",
        "\n",
        "and use them across notebooks.\n",
        "\n",
        "To do so, **comment out** the above **manual** API key prompt code block(s),\n",
        "\n",
        "and **uncomment** the following codeblock.\n",
        "\n",
        "⚠️ Don't forget granting access to the API key you would be using to the current notebook."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# import os\n",
        "# from google.colab import userdata\n",
        "\n",
        "# os.environ[\"OPENAI_API_KEY\"] = userdata.get(\"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": 3,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "754A8R7X2rnP",
        "outputId": "c4daf659-df39-4fb5-8e2b-10e01f75f505"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Specified task prompt:\n",
            "Develop a captivating 5-minute solo performance that incorporates dynamic movement, audience interaction, and emotional storytelling. Focus on mastering vocal projection, facial expressions, and body language to enhance stage presence. Rehearse in front of a small audience for feedback, refining your act to create a memorable and engaging experience.\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",
        ")\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": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "uJJQD0LV3DSB",
        "outputId": "5e8a7922-2e7d-4643-f004-152829194d47"
      },
      "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",
            "1. **Identify Promotion Criteria:**\n",
            "   - Research your company's promotion criteria and understand the skills, experiences, and accomplishments required for the next level.\n",
            "\n",
            "2. **Set a Timeline:**\n",
            "   - Establish a timeline for when you want to achieve the promotion (e.g., within the next 6-12 months).\n",
            "\n",
            "3. **Skill Development:**\n",
            "   - List specific technical and soft skills you need to improve or acquire (e.g., leadership, project management, advanced programming languages).\n",
            "   - Enroll in relevant courses or workshops to develop these skills.\n",
            "\n",
            "4. **Project Contributions:**\n",
            "   - Identify key projects or initiatives within your team or organization where you can take on more responsibility or leadership roles.\n",
            "   - Set a goal to lead at least one significant project in the next quarter.\n",
            "\n",
            "5. **Seek Feedback:**\n",
            "   - Schedule regular check-ins with your manager to discuss your performance and areas for improvement.\n",
            "   - Ask for constructive feedback on your work and how you can align better with promotion expectations.\n",
            "\n",
            "6. **Build Relationships:**\n",
            "   - Network with colleagues and leaders in your organization to gain visibility and mentorship.\n",
            "   - Attend company events or join cross-functional teams to expand your influence.\n",
            "\n",
            "7. **Document Achievements:**\n",
            "   - Keep a record of your accomplishments, contributions, and any positive feedback you receive.\n",
            "   - Prepare a summary of your achievements to present during performance reviews or promotion discussions.\n",
            "\n",
            "8. **Prepare for the Promotion Discussion:**\n",
            "   - Plan a meeting with your manager to discuss your career goals and express your interest in promotion.\n",
            "   - Be ready to present your documented achievements and how they align with the promotion criteria.\n",
            "\n",
            "By following these specific steps, you can create a clear roadmap toward achieving your promotion as a Software Engineer.\n"
          ]
        }
      ],
      "source": [
        "from camel.agents import TaskSpecifyAgent\n",
        "from camel.configs import ChatGPTConfig\n",
        "from camel.models import ModelFactory\n",
        "from camel.prompts import TextPrompt\n",
        "from camel.types import ModelPlatformType, ModelType\n",
        "\n",
        "# Set up the model\n",
        "model = ModelFactory.create(\n",
        "    model_platform=ModelPlatformType.OPENAI,\n",
        "    model_type=ModelType.GPT_4O_MINI,\n",
        ")\n",
        "\n",
        "# Create a custom prompt template\n",
        "my_prompt_template = TextPrompt(\n",
        "    'Here is a task: I\\'m a {occupation} and I want to {task}. Help me to make this task more specific.'\n",
        ")\n",
        "\n",
        "# Create a task specify agent with the custom prompt\n",
        "task_specify_agent = TaskSpecifyAgent(\n",
        "    model=model, task_specify_prompt=my_prompt_template\n",
        ")\n",
        "\n",
        "# Run the agent with a task prompt\n",
        "response = task_specify_agent.run(\n",
        "    task_prompt=\"get promotion\",\n",
        "    meta_dict=dict(occupation=\"Software Engineer\"),\n",
        ")\n",
        "\n",
        "print(response)"
      ]
    },
    {
      "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": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "xdQdjQzy3f9u",
        "outputId": "dcc7446b-e4c3-4e91-d70b-cda2814d8e7c"
      },
      "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"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "f-Q-gZAi3nbR",
        "outputId": "f670ef3f-dcdc-4285-b4a2-280806dd779c"
      },
      "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\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "sq3fTArB3qEx"
      },
      "source": [
        "### 3. Object Recognition with ObjectRecognitionPromptTemplateDict"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "5XTQuohX3sOk",
        "outputId": "e0557d9d-3c9f-4c45-aab8-a96bb5b3204f"
      },
      "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\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "OxgxXQBt3uRt"
      },
      "source": [
        "### 4. Translation with TranslationPromptTemplateDict"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "w1k00XLu3xIk",
        "outputId": "5f09d70a-4095-496d-cfae-c7fe05dbc7a7"
      },
      "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": {},
      "source": [
        "## 🌟 Highlights"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "This notebook has guided you through setting up and use **Prompt** module. 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.\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",
        "*   **Prompt**: Interface to communicate with models with various 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": {},
      "source": [
        "That's everything: Got questions about 🐫 CAMEL-AI? Join us on [Discord](https://discord.camel-ai.org)! Whether you want to share feedback, explore the latest in multi-agent systems, get support, or connect with others on exciting projects, we’d love to have you in the community! 🤝\n",
        "\n",
        "Check out some of our other work:\n",
        "\n",
        "1. 🐫 Creating Your First CAMEL Agent [free Colab](https://docs.camel-ai.org/cookbooks/create_your_first_agent.html)\n",
        "\n",
        "2.  Graph RAG Cookbook [free Colab](https://colab.research.google.com/drive/1uZKQSuu0qW6ukkuSv9TukLB9bVaS1H0U?usp=sharing)\n",
        "\n",
        "3. 🧑‍⚖️ Create A Hackathon Judge Committee with Workforce [free Colab](https://colab.research.google.com/drive/18ajYUMfwDx3WyrjHow3EvUMpKQDcrLtr?usp=sharing)\n",
        "\n",
        "4. 🔥 3 ways to ingest data from websites with Firecrawl & CAMEL [free Colab](https://colab.research.google.com/drive/1lOmM3VmgR1hLwDKdeLGFve_75RFW0R9I?usp=sharing)\n",
        "\n",
        "5. 🦥 Agentic SFT Data Generation with CAMEL and Mistral Models, Fine-Tuned with Unsloth [free Colab](https://colab.research.google.com/drive/1lYgArBw7ARVPSpdwgKLYnp_NEXiNDOd-?usp=sharingg)\n",
        "\n",
        "Thanks from everyone at 🐫 CAMEL-AI\n",
        "\n",
        "\n",
        "<div class=\"align-center\">\n",
        "  <a href=\"https://www.camel-ai.org/\"><img src=\"https://i.postimg.cc/KzQ5rfBC/button.png\"width=\"150\"></a>\n",
        "  <a href=\"https://discord.camel-ai.org\"><img src=\"https://i.postimg.cc/L4wPdG9N/join-2.png\"  width=\"150\"></a></a>\n",
        "  \n",
        "⭐ <i>Star us on [*Github*](https://github.com/camel-ai/camel), join our [*Discord*](https://discord.camel-ai.org) or follow our [*X*](https://x.com/camelaiorg)\n",
        "</div>\n"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "display_name": "camel-ai-bO_GxOlJ-py3.11",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.11.4"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}