๐ซ 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: Cookbook for self-instruct (#1451)
Wendong-Fan1b5fc2038609
diff --git a/README.md b/README.mdindex 9add013fc..d9f6f1877 100644--- a/README.md+++ b/README.md@@ -273,10 +273,10 @@ Practical guides and tutorials for implementing specific functionalities in CAME### Model Training & Data Generation| Cookbook | Description ||:---|:---|-| **[Data Generation with CAMEL and Finetuning with Unsloth](https://docs.camel-ai.org/cookbooks/model_training/sft_data_generation_and_unsloth_finetuning_Qwen2_5_7B.html)** | Learn how to generate data with CAMEL and fine-tune models effectively with Unsloth. |-| **[Data Gen with Real Function Calls and Hermes Format](https://docs.camel-ai.org/cookbooks/model_training/data_gen_with_real_function_calls_and_hermes_format.html)** | Explore how to generate data with real function calls and the Hermes format. |-| **[CoT Data Generation and Upload Data to Huggingface](https://docs.camel-ai.org/cookbooks/model_training/cot_data_gen_upload_to_huggingface.html)** | Uncover how to generate CoT data with CAMEL and seamlessly upload it to Huggingface. |-| **[CoT Data Generation and SFT Qwen with Unsolth](https://docs.camel-ai.org/cookbooks/model_training/cot_data_gen_sft_qwen_unsolth_upload_huggingface.html)** | Discover how to generate CoT data using CAMEL and SFT Qwen with Unsolth, and seamlessly upload your data and model to Huggingface. |+| **[Data Generation with CAMEL and Finetuning with Unsloth](https://docs.camel-ai.org/cookbooks/data_generation/sft_data_generation_and_unsloth_finetuning_Qwen2_5_7B.html)** | Learn how to generate data with CAMEL and fine-tune models effectively with Unsloth. |+| **[Data Gen with Real Function Calls and Hermes Format](https://docs.camel-ai.org/cookbooks/data_generation/data_gen_with_real_function_calls_and_hermes_format.html)** | Explore how to generate data with real function calls and the Hermes format. |+| **[Self-instruct Data Generation](https://docs.camel-ai.org/cookbooks/data_generation/self_instruct_data_generation.html)** | Explore comprehensive guidelines and best practices for generating self-instructional data, enabling robust model training and improved performance. |+| **[CoT Data Generation and SFT Qwen with Unsolth](https://docs.camel-ai.org/cookbooks/data_generation/cot_data_gen_sft_qwen_unsolth_upload_huggingface.html)** | Discover how to generate CoT data using CAMEL and SFT Qwen with Unsolth, and seamlessly upload your data and model to Huggingface. |### Multi-Agent Systems & Applications| Cookbook | Description |diff --git a/docs/cookbooks/applications/index.rst b/docs/cookbooks/applications/index.rstindex afc9557fd..5b0eb5ad5 100644--- a/docs/cookbooks/applications/index.rst+++ b/docs/cookbooks/applications/index.rst@@ -2,7 +2,7 @@<div class="prev-next-nav"><a class="left-nav" href="../basic_concepts/index.html">โ Basic Concepts</a>- <a class="right-nav" href="../model_training/index.html">Model Training โ</a>+ <a class="right-nav" href="../data_generation/index.html">Model Training โ</a></div>Applicationsdiff --git a/docs/cookbooks/model_training/cot_data_gen_sft_qwen_unsolth_upload_huggingface.ipynb b/docs/cookbooks/data_generation/cot_data_gen_sft_qwen_unsolth_upload_huggingface.ipynbsimilarity index 100%rename from docs/cookbooks/model_training/cot_data_gen_sft_qwen_unsolth_upload_huggingface.ipynbrename to docs/cookbooks/data_generation/cot_data_gen_sft_qwen_unsolth_upload_huggingface.ipynbdiff --git a/docs/cookbooks/model_training/data_gen_with_real_function_calls_and_hermes_format.ipynb b/docs/cookbooks/data_generation/data_gen_with_real_function_calls_and_hermes_format.ipynbsimilarity index 100%rename from docs/cookbooks/model_training/data_gen_with_real_function_calls_and_hermes_format.ipynbrename to docs/cookbooks/data_generation/data_gen_with_real_function_calls_and_hermes_format.ipynbdiff --git a/docs/cookbooks/model_training/index.rst b/docs/cookbooks/data_generation/index.rstsimilarity index 94%rename from docs/cookbooks/model_training/index.rstrename to docs/cookbooks/data_generation/index.rstindex 9eafa3e51..39e309d17 100644--- a/docs/cookbooks/model_training/index.rst+++ b/docs/cookbooks/data_generation/index.rst@@ -15,5 +15,5 @@ Model Training and Fine-tuningsft_data_generation_and_unsloth_finetuning_Qwen2_5_7Bsft_data_generation_and_unsloth_finetuning_tinyllamadata_gen_with_real_function_calls_and_hermes_format- cot_data_gen_upload_to_huggingface+ self_instruct_data_generationcot_data_gen_sft_qwen_unsolth_upload_huggingfacediff --git a/docs/cookbooks/data_generation/self_instruct_data_generation.ipynb b/docs/cookbooks/data_generation/self_instruct_data_generation.ipynbnew file mode 100644index 000000000..56e33249b--- /dev/null+++ b/docs/cookbooks/data_generation/self_instruct_data_generation.ipynb@@ -0,0 +1,1010 @@+{+ "nbformat": 4,+ "nbformat_minor": 0,+ "metadata": {+ "colab": {+ "provenance": []+ },+ "kernelspec": {+ "name": "python3",+ "display_name": "Python 3"+ },+ "language_info": {+ "name": "python"+ }+ },+ "cells": [+ {+ "cell_type": "markdown",+ "source": [+ "# Self-instruct Data Generation Using Qwen"+ ],+ "metadata": {+ "id": "azpLa35BMh_8"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "<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": {+ "id": "ra2Ra30kMuqT"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "The self-instruct pipeline is a technique for automatically generating instructions for large language models (LLMs). Manually creating these datasets can be time-consuming and expensive. The self-instruct pipeline provides a way to automate this process and generate large numbers of instructions quickly and efficiently."+ ],+ "metadata": {+ "id": "sb_hTLygSsl4"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "## Installation and Setup\n",+ "First, install the CAMEL package with all its dependencies"+ ],+ "metadata": {+ "id": "A3UnHaNUNzyf"+ }+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {+ "id": "gmr93i2kMZco"+ },+ "outputs": [],+ "source": [+ "!pip install \"git+https://github.com/camel-ai/camel.git@c7bd39c898cb8d3bd434acd4219c3cb4f5f85ae2#egg=camel-ai[all]\""+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "If you donโt have a Qwen API key, you can obtain one by following these steps:\n",+ "\n",+ "Visit the Alibaba Cloud Model Studio Console (https://www.alibabacloud.com/en?_p_lc=1) and follow the on-screen instructions to activate the model services.\n",+ "\n",+ "In the upper-right corner of the console, click on your account name and select API-KEY.\n",+ "\n",+ "On the API Key management page, click on the Create API Key button to generate a new key."+ ],+ "metadata": {+ "id": "wL52eqWmXY2f"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "import os\n",+ "from getpass import getpass\n",+ "\n",+ "qwen_api_key = getpass('Enter your Qwen API key: ')\n",+ "os.environ[\"QWEN_API_KEY\"] = qwen_api_key"+ ],+ "metadata": {+ "id": "bg4UKbvePAlT",+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "outputId": "16ec35ae-fe6b-45b3-ad2d-feea4af52808"+ },+ "execution_count": 2,+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Enter your Qwen API key: ยทยทยทยทยทยทยทยทยทยท\n"+ ]+ }+ ]+ },+ {+ "cell_type": "code",+ "source": [+ "from camel.configs import QwenConfig\n",+ "from camel.models import ModelFactory\n",+ "from camel.types import ModelPlatformType, ModelType\n",+ "from camel.agents import ChatAgent\n",+ "from camel.messages import BaseMessage\n",+ "\n",+ "qwen_model = ModelFactory.create(\n",+ " model_platform=ModelPlatformType.QWEN,\n",+ " model_type=ModelType.QWEN_TURBO,\n",+ " model_config_dict=QwenConfig(temperature=0.2).as_dict(),\n",+ ")"+ ],+ "metadata": {+ "id": "tsBvJzKXL01z"+ },+ "execution_count": 3,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "## Basic Agent Setup"+ ],+ "metadata": {+ "id": "HfGtqjC8Qbf7"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "from camel.agents import ChatAgent\n",+ "from camel.datagen.self_instruct import SelfInstructPipeline\n",+ "\n",+ "agent = ChatAgent(\n",+ " model=qwen_model,\n",+ ")"+ ],+ "metadata": {+ "id": "BDaDfucWQLDy"+ },+ "execution_count": 4,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "## Basic Pipeline Setup\n"+ ],+ "metadata": {+ "id": "K5X87J_GQ-l1"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "The pipeline works by starting with a small set of seed (human-written) instructions and then using an LLM to generate new instructions based on those seeds.\n",+ "\n",+ "- The seed instructions are typically stored in a JSON Lines (JSONL) file. Each line in the file represents a single instruction in JSON format.\n",+ "\n",+ "- Like the seed file, the output is also stored in JSONL format, making it easy to parse and use for further tasks, such as training or fine-tuning language models.\n",+ "\n",+ "\n",+ "Please replace `seed_path` with the path to your seed file, and replace `data_output_path` with your desired output location."+ ],+ "metadata": {+ "id": "RdJciTcGTKKE"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "import os\n",+ "import requests\n",+ "\n",+ "# Create directory for local data\n",+ "os.makedirs('local_data', exist_ok=True)\n",+ "\n",+ "# Update the URL to the raw file content\n",+ "url = \"https://raw.githubusercontent.com/camel-ai/camel/master/examples/synthetic_datagen/self_instruct/seed_tasks.jsonl\"\n",+ "\n",+ "# Fetch the raw file\n",+ "response = requests.get(url)\n",+ "\n",+ "with open('local_data/seed_tasks.jsonl', 'wb') as file:\n",+ " file.write(response.content)\n"+ ],+ "metadata": {+ "id": "QHtvkMBsQxRH"+ },+ "execution_count": 5,+ "outputs": []+ },+ {+ "cell_type": "code",+ "source": [+ "seed_path = 'local_data/seed_tasks.jsonl'\n",+ "data_output_path = 'data_output.json'"+ ],+ "metadata": {+ "id": "Nf89LSdGRRCb"+ },+ "execution_count": 6,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "The cell below shows some example instructions in the seed file. All seed files should follow this format."+ ],+ "metadata": {+ "id": "wcnLSoyfgcWw"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "with open('local_data/seed_tasks.jsonl', 'r') as file:\n",+ " for i, line in enumerate(file):\n",+ " print(line.strip())\n",+ " if i >= 9:\n",+ " break"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "mmYZS_iTfp9q",+ "outputId": "e311e52f-9496-405c-d169-b5e8c3fb4bc6"+ },+ "execution_count": 7,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "{\"id\": \"seed_task_0\", \"name\": \"breakfast_suggestion\", \"instruction\": \"Is there anything I can eat for a breakfast that doesn't include eggs, yet includes protein, and has roughly 700-1000 calories?\", \"instances\": [{\"input\": \"\", \"output\": \"Yes, you can have 1 oatmeal banana protein shake and 4 strips of bacon. The oatmeal banana protein shake may contain 1/2 cup oatmeal, 60 grams whey protein powder, 1/2 medium banana, 1tbsp flaxseed oil and 1/2 cup watter, totalling about 550 calories. The 4 strips of bacon contains about 200 calories.\"}], \"is_classification\": false}\n",+ "{\"id\": \"seed_task_1\", \"name\": \"antonym_relation\", \"instruction\": \"What is the relation between the given pairs?\", \"instances\": [{\"input\": \"Night : Day :: Right : Left\", \"output\": \"The relation between the given pairs is that they are opposites.\"}], \"is_classification\": false}\n",+ "{\"id\": \"seed_task_2\", \"name\": \"one_sentence_description\", \"instruction\": \"Generate a one-sentence description for each of the following people.\", \"instances\": [{\"input\": \"- Brack Obama\\n- Elon Musk\\n- Taylor Swift\", \"output\": \"- Barack Hussein Obama II is an American politician who served as the 44th president of the United States from 2009 to 2017.\\n- Elon Musk is the founder, CEO, and chief engineer of SpaceX; angel investor, CEO and product architect of Tesla, Inc.; founder of The Boring Company; co-founder of Neuralink and OpenAI; president of the Musk Foundation; and owner and CEO of Twitter, Inc.\\n- Taylor Alison Swift is an American singer-songwriter.\"}], \"is_classification\": false}\n",+ "{\"id\": \"seed_task_3\", \"name\": \"harmful_stereotype_example\", \"instruction\": \"Describe a situation in which the given stereotype can harm you.\", \"instances\": [{\"input\": \"\\\"All Asians are smart!\\\"\", \"output\": \"Imagine you're a small child of Asian descent. You hear your whole life how \\\"all Asians are smart,\\\" but you know that does not feel like it's true for you. You have a hard time in school. Reading is difficult. Math is impossible. Everyone around you seems to pressure you because you are supposed to be \\\"smart.\\\" Every time you do not bring home that \\\"A\\\" assignment, you feel like a failure. Like you alone missed out on the gene that makes \\\"all Asians smart.\\\"\\nAs educational opportunities like scholarships and colleges close their door on you, your future looks bleak. You have spent years trying to be the stereotypically smart Asian instead of finding the talents that could have taken you to success in other areas. As you can see, although the stereotype doesn't sound like a bad thing at first, it can put a lot of weight on the people who do not fit into it.\"}], \"is_classification\": false}\n",+ "{\"id\": \"seed_task_4\", \"name\": \"email_subject_generation\", \"instruction\": \"Generate an appropriate subjective title for the following email:\", \"instances\": [{\"input\": \"Hi [person name],\\n\\nI'm writing to ask you if you are happy to be a panelist of our workshop on multimodality at CVPR. The workshop will be held on June 20, 2023. \\n\\nBest,\\n[my name]\", \"output\": \"Invitition to be a panelist for CVPR 2023 workshop on Multimodality\"}], \"is_classification\": false}\n",+ "{\"id\": \"seed_task_5\", \"name\": \"interview_question_answering\", \"instruction\": \"How do you answer this question in a job interview?\", \"instances\": [{\"input\": \"What do you think about when you are alone in a car?\", \"output\": \"If it is in the evening, I typically think about what good I have accomplished that day, and if it is in the morning, I think about how I can be my best that day. I also try to practice gratitude and live in the present moment while I'm driving to avoid distractions.\"}], \"is_classification\": false}\n",+ "{\"id\": \"seed_task_6\", \"name\": \"new_year's_resolutions\", \"instruction\": \"Brainstorm a list of possible New Year's resolutions.\", \"instances\": [{\"input\": \"\", \"output\": \"- Lose weight\\n- Exercise more\\n- Eat healthier\\n- Quit smoking\\n- Drink less alcohol\\n- Spend less money\\n- Save more money\\n- Get out of debt\\n- Take a trip\\n- Volunteer more\\n- Spend more time with family and friends\\n- Read more\\n- Start a hobby\\n- Get organized\\n- Simplify your life\\n- Meditate or pray more\\n- Get a new job\\n- Move to a new city\\n- Make new friends\\n- Go back to school\\n- Learn a new language\\n- Start a business\"}], \"is_classification\": false}\n",+ "{\"id\": \"seed_task_7\", \"name\": \"idiom_meaning\", \"instruction\": \"Explain the following idiom to me, and try to give me some examples.\", \"instances\": [{\"input\": \"black sheep\", \"output\": \"Meaning: An outcast. Someone who doesn\\u2019t fit in with the rest of the crowd. They take pride in being different. Thinks for themselves and doesn\\u2019t care what no one else has to say. They tend to ride their own wave and are usually loners because no one understands them, but its okay because they like it that way.\\nExample: He\\u2019s the black sheep of the family.\"}], \"is_classification\": false}\n",+ "{\"id\": \"seed_task_8\", \"name\": \"english_haiku_generation\", \"instruction\": \"Generate a haiku using the following word:\", \"instances\": [{\"input\": \"summer\", \"output\": \"The chill, worming in\\nShock, pleasure, bursting within\\nSummer tongue awakes\"}], \"is_classification\": false}\n",+ "{\"id\": \"seed_task_9\", \"name\": \"movie_recommendation\", \"instruction\": \"Recommend a movie for me to watch during the weekend and explain the reason.\", \"instances\": [{\"input\": \"\", \"output\": \"I would recommend the movie \\\"The Shawshank Redemption\\\" because it is an excellent movie that is both moving and inspiring. It is the story of a man who is unjustly imprisoned and his struggle to maintain hope and dignity. It is a great film to watch over the weekend because it will make you think about the human capacity for resilience and hope.\"}], \"is_classification\": false}\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "The self-instruct pipeline works iteratively. In each round:\n",+ "\n",+ "1. It selects a certain number of human-written instructions (`num_human_sample`) from the `seed_path`.\n",+ "2. It selects a certain number of machine-generated instructions (`num_machine_sample`) from previous rounds.\n",+ "3. It uses these selected instructions to guide the language model in generating new instructions.\n",+ "4. These new instructions are added to the pool of machine-generated instructions, and the process repeats until the desired number of instructions is generated.\n",+ "\n",+ "The `human_to_machine_ratio` helps control the balance between human guidance and the model's creativity throughout this process. By adjusting this ratio, you can influence the quality and diversity of the generated instructions.\n",+ "\n",+ "Feel free to alter `num_human_sample` and `num_machine_sample`, which both will be passed into `human_to_machine_ratio` later"+ ],+ "metadata": {+ "id": "LTlHeS2vUAMr"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "num_human_sample = 6\n",+ "num_machine_sample = 2"+ ],+ "metadata": {+ "id": "S0VCIsDgRGc9"+ },+ "execution_count": 8,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "Please replace `target_num_instructions` with the number of machine instructions you want to generate\n"+ ],+ "metadata": {+ "id": "Apkw8UXmVElE"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "target_num_instructions = 5"+ ],+ "metadata": {+ "id": "h1To5o6MRaPa"+ },+ "execution_count": 9,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "Pass everything to our pipeline."+ ],+ "metadata": {+ "id": "yApLnaGgVXCR"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "pipeline = SelfInstructPipeline(\n",+ " agent=agent,\n",+ " seed=seed_path,\n",+ " num_machine_instructions=target_num_instructions,\n",+ " data_output_path=data_output_path,\n",+ " human_to_machine_ratio=(num_human_sample, num_machine_sample),\n",+ ")"+ ],+ "metadata": {+ "id": "D0eOGW75Q_07"+ },+ "execution_count": 10,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "Try generating it! You will see the generated data file being created at your desired location!"+ ],+ "metadata": {+ "id": "8CdMQTR2Vah8"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "pipeline.generate()"+ ],+ "metadata": {+ "id": "xLITVgW_RBtb"+ },+ "execution_count": 11,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "Pretty print the generated data content"+ ],+ "metadata": {+ "id": "lMNurltvN1SH"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "import json\n",+ "\n",+ "with open(data_output_path, 'r') as file:\n",+ " data = json.load(file)\n",+ " print(json.dumps(data, indent=4))"+ ],+ "metadata": {+ "id": "Qz1-aKiONsyU",+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "outputId": "1ed21690-0029-41ca-e5c0-cae297c790c5"+ },+ "execution_count": 12,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "[\n",+ " {\n",+ " \"id\": \"machine_task_1\",\n",+ " \"instruction\": \"Design a simple logo that represents both unity and diversity for a community organization.\",\n",+ " \"is_classification\": false,\n",+ " \"instances\": [\n",+ " {\n",+ " \"input\": \"\",\n",+ " \"output\": \"A circular logo with a pattern composed of different colored puzzle pieces fitting together perfectly, symbolizing unity and diversity within the community.\"\n",+ " },\n",+ " {\n",+ " \"input\": \"\",\n",+ " \"output\": \"An emblem featuring a tree with leaves of various shapes and colors, signifying growth, inclusion, and unity among diverse members of the community.\"\n",+ " }\n",+ " ]\n",+ " },\n",+ " {\n",+ " \"id\": \"machine_task_2\",\n",+ " \"instruction\": \"Create a step-by-step guide explaining how to perform a specific magic trick.\",\n",+ " \"is_classification\": false,\n",+ " \"instances\": [\n",+ " {\n",+ " \"input\": \"\",\n",+ " \"output\": \"1. Begin by showing the audience a regular deck of cards.\\n2. Shuffle the deck and ask a volunteer from the audience to draw a card and remember it.\\n3. Have the volunteer place the card back into the deck without showing anyone.\\n4. Shuffle the deck again and spread the cards face down on the table.\\n5. Slowly reveal each card, until you find the selected card.\"\n",+ " },\n",+ " {\n",+ " \"input\": \"\",\n",+ " \"output\": \"1. Ask a participant to choose a coin and hold it in their closed hand.\\n2. Cover the participant's hand with a cloth.\\n3. While covered, secretly switch the coin with a duplicate coin.\\n4. Lift the cloth to reveal the coin has seemingly disappeared and then reappeared elsewhere.\"\n",+ " }\n",+ " ]\n",+ " },\n",+ " {\n",+ " \"id\": \"machine_task_3\",\n",+ " \"instruction\": \"Write a short story that incorporates the given three random words as key elements.\",\n",+ " \"is_classification\": false,\n",+ " \"instances\": [\n",+ " {\n",+ " \"input\": \"[\\\"mystery\\\", \\\"river\\\", \\\"midnight\\\"\",\n",+ " \"output\": \"Late one \\\"midnight\\\" under the glow of a full moon, Sarah found herself drawn to the mysterious \\\"river\\\" that flowed near her cottage. Legend had it that the river held many \\\"mysteries\\\" within its depths. As she approached the water's edge, she noticed a faint light flickering across the water. Her curiosity piqued, she ventured forth, only to discover an old boat half-submerged in the river. Determined to uncover the secrets it held, she spent hours exploring the boat and the riverbank, until the first light of dawn broke the darkness.\"\n",+ " },\n",+ " {\n",+ " \"input\": \"[\\\"castle\\\", \\\"dragon\\\", \\\"princess\\\"\",\n",+ " \"output\": \"In a faraway kingdom, Princess Amelia lived in a grand \\\"castle\\\" atop a hill. One day, a fearsome \\\"dragon\\\" began terrorizing the nearby villages. The king offered half his kingdom and Amelia's hand in marriage to whoever could slay the beast. Many knights tried and failed, but a humble farmer's son named Thomas succeeded. Instead of claiming the reward, he asked only for passage to the castle. There, he and Amelia discovered a shared love for adventure and soon embarked on a quest together, with the \\\"dragon\\\" as their guide, leaving behind the life of luxury in the \\\"castle\\\".\"\n",+ " }\n",+ " ]\n",+ " },\n",+ " {\n",+ " \"id\": \"machine_task_4\",\n",+ " \"instruction\": \"Explain the cultural significance of a traditional dance in a few paragraphs.\",\n",+ " \"is_classification\": false,\n",+ " \"instances\": [\n",+ " {\n",+ " \"input\": \"\",\n",+ " \"output\": \"The Flamenco dance, originating from the Andalusian region of Spain, holds deep cultural significance. It is a passionate and expressive art form that combines singing, guitar playing, dancing, and handclaps. Flamenco embodies the spirit of Andalusia, reflecting the region's history of diverse cultural influences including Roman, Jewish, Moorish, and Christian traditions. This dance form often conveys intense emotions such as sorrow, joy, and longing, mirroring the struggles and triumphs of the Andalusian people throughout history. Flamenco is not just a dance; it is a means of storytelling, preserving the collective memory and identity of the Andalusian community.\"\n",+ " },\n",+ " {\n",+ " \"input\": \"\",\n",+ " \"output\": \"The Haka, a traditional war dance of the M\\u0101ori people of New Zealand, is a powerful display of strength, unity, and cultural pride. Originally performed by warriors before a battle to intimidate opponents and boost morale, today it is performed on various occasions such as weddings, funerals, and sporting events. The Haka involves rhythmic stamping, aggressive facial expressions, and synchronized movements, making it a visually striking performance. It serves as a way to honor ancestors, express grief, and celebrate achievements, reinforcing the M\\u0101ori community's connection to their heritage and each other.\"\n",+ " }\n",+ " ]\n",+ " },\n",+ " {\n",+ " \"id\": \"machine_task_5\",\n",+ " \"instruction\": \"Compose a poem that captures the essence of a serene countryside landscape.\",\n",+ " \"is_classification\": false,\n",+ " \"instances\": [\n",+ " {\n",+ " \"input\": \"\",\n",+ " \"output\": \"In the quiet valley where the river flows,\\nGolden fields sway gently in the breeze.\\nMountains stand guard, in eternal repose,\\nWhile wildflowers dance beneath whispering trees.\\n\\nThe sun sets slow, painting skies anew,\\nA canvas vast, in hues of pink and gold.\\nUnder the stars, the night whispers true,\\nOf peace that the waking world can't hold.\"\n",+ " },\n",+ " {\n",+ " \"input\": \"\",\n",+ " \"output\": \"Beneath the wide and open sky so blue,\\nA lone barn stands against the green.\\nThe lazy brook meanders through,\\nIts waters clear, its banks unseen.\\n\\nBirdsong fills the air with sweet refrain,\\nAs shadows lengthen, cool and long.\\nIn this tranquil scene, no pain,\\nJust nature's calm, a soothing song.\\n\\nThe gentle rustle of the leaves above,\\nA soft caress from the summer wind.\\nHere, worries fade, and cares dissolve,\\nIn this serene and peaceful bind.\"\n",+ " }\n",+ " ]\n",+ " }\n",+ "]\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "## Filter functions"+ ],+ "metadata": {+ "id": "6vUQuCYsVhYB"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "Newly generated instructions undergo filtering and evaluation before being added to the results. Only those meeting predefined standards are included. CAMEL provides some filter functions that can be passed in the self-instruct pipeline. Additionally, we also supports custom filters for tailored evaluation! Filter functions return `True` if the instruction is valid, `False` otherwise."+ ],+ "metadata": {+ "id": "2rwicXz4WKUF"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "### Length Filter\n",+ "\n",+ "`LengthFilter` filters out all the instructions which has a length less than `min_len` or greater than `max_len`."+ ],+ "metadata": {+ "id": "0R1WMehRXP_Y"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "from camel.datagen.self_instruct import LengthFilter\n",+ "\n",+ "length_filter = LengthFilter(min_len=5, max_len=50)\n",+ "\n",+ "instructions = [\n",+ " \"Sort the numbers in ascending order.\",\n",+ " \"Calculate the sum.\",\n",+ " \"Create a report that details the monthly expenses and savings in a spreadsheet.\"\n",+ "]\n",+ "\n",+ "filtered_instructions = [instr for instr in instructions if length_filter.apply(instr)]\n",+ "print(filtered_instructions)"+ ],+ "metadata": {+ "id": "Spm-IrjYXSZH",+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "outputId": "0ebec3ec-8b5c-4a03-b371-f6a012fefd17"+ },+ "execution_count": 13,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "['Sort the numbers in ascending order.', 'Create a report that details the monthly expenses and savings in a spreadsheet.']\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "### Keyword Filter\n",+ "\n",+ "`KeywordFilter` filters instructions that contain specific undesirable keyword."+ ],+ "metadata": {+ "id": "p1Isrs-kZtlA"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "from camel.datagen.self_instruct import KeywordFilter\n",+ "\n",+ "keyword_filter = KeywordFilter(keywords=[\"ban\", \"prohibit\", \"forbid\"])\n",+ "\n",+ "instructions = [\n",+ " \"Ban the use of plastic bags.\",\n",+ " \"Encourage recycling programs.\",\n",+ " \"Prohibit smoking in public areas.\"\n",+ "]\n",+ "\n",+ "filtered_instructions = [instr for instr in instructions if keyword_filter.apply(instr)]\n",+ "print(filtered_instructions)"+ ],+ "metadata": {+ "id": "ez4ixDvpZ2Jl",+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "outputId": "6043eb87-d20e-43f6-9169-026356034859"+ },+ "execution_count": 14,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "['Encourage recycling programs.']\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "### Punctuation Filter\n",+ "\n",+ "`PunctuationFilter` filters instructions that begin with a non-alphanumeric character."+ ],+ "metadata": {+ "id": "44x4N1voauHt"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "from camel.datagen.self_instruct import PunctuationFilter\n",+ "\n",+ "punctuation_filter = PunctuationFilter()\n",+ "\n",+ "instructions = [\n",+ " \"Sort the data by category.\",\n",+ " \"#Analyze the trends over time.\",\n",+ " \"*Create a summary of results.\"\n",+ "]\n",+ "\n",+ "filtered_instructions = [instr for instr in instructions if punctuation_filter.apply(instr)]\n",+ "print(filtered_instructions)"+ ],+ "metadata": {+ "id": "NZUkOWBIbKda",+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "outputId": "fcee7c8a-e093-459a-92f2-b1dd3c9a922b"+ },+ "execution_count": 15,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "['Sort the data by category.']\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "### Non-English Filter\n",+ "\n",+ "`NonEnglishFilter` filters instructions that do not begin with English letters."+ ],+ "metadata": {+ "id": "baQhO3aEbRkZ"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "from camel.datagen.self_instruct import NonEnglishFilter\n",+ "\n",+ "non_english_filter = NonEnglishFilter()\n",+ "\n",+ "instructions = [\n",+ " \"Analyze the performance metrics.\",\n",+ " \"่ฎก็ฎ็ปๆ็็ป่ฎกๆฐๆฎ.\",\n",+ " \"Test the new algorithm.\"\n",+ "]\n",+ "\n",+ "filtered_instructions = [instr for instr in instructions if non_english_filter.apply(instr)]\n",+ "print(filtered_instructions)"+ ],+ "metadata": {+ "id": "KRWFVlrobahx",+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "outputId": "ed2f6a31-b20b-46a1-f6a2-54616f11e5f6"+ },+ "execution_count": 16,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "['Analyze the performance metrics.', 'Test the new algorithm.']\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "### ROUGE Similarity Filter\n",+ "\n",+ "`RougeSimilarityFilter` filters instructions that are too similar to existing instructions based on ROUGE scores."+ ],+ "metadata": {+ "id": "MfpiGUmgbuez"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "from camel.datagen.self_instruct import RougeSimilarityFilter\n",+ "\n",+ "existing_instructions = [\n",+ " \"Summarize the article.\",\n",+ " \"Write a brief overview of the text.\"\n",+ "]\n",+ "\n",+ "similarity_filter = RougeSimilarityFilter(existing_instructions, threshold=0.5)\n",+ "\n",+ "instructions = [\n",+ " \"Summarize the content.\",\n",+ " \"Create a summary for the text.\",\n",+ " \"Provide an analysis of the text.\"\n",+ "]\n",+ "\n",+ "filtered_instructions = [instr for instr in instructions if similarity_filter.apply(instr)]\n",+ "print(filtered_instructions)"+ ],+ "metadata": {+ "id": "BWm9OmA3cLH_",+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "outputId": "fe2bfa58-511d-4905-ab33-5e476cd95c52"+ },+ "execution_count": 17,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "['Create a summary for the text.', 'Provide an analysis of the text.']\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "### Custom Filter Function\n",+ "\n",+ "Additionaly, you could implement your own filter function."+ ],+ "metadata": {+ "id": "7v0bCi41pYNJ"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "from camel.datagen.self_instruct import FilterFunction\n",+ "\n",+ "class CustomFilter(FilterFunction):\n",+ "\n",+ " def apply(self, instruction: str) -> bool:\n",+ " # apply your logic here\n",+ " logic = ...\n",+ " return logic"+ ],+ "metadata": {+ "id": "WePYoWOcpd4L"+ },+ "execution_count": 18,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "## Instruction Filter\n",+ "\n",+ "`InstructionFilter` manages all filter functions. And we can use a custom InstructionFilter to initialize the pipeline"+ ],+ "metadata": {+ "id": "e4GFMWex0pIU"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "Start by adding filter functions you want and configure them."+ ],+ "metadata": {+ "id": "TZD_Vv331KRR"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "filter_config = {\n",+ " \"length\": {\"min_len\": 5, \"max_len\": 100},\n",+ " \"keyword\": {\"keywords\": [\"image\", \"video\"]},\n",+ " \"non_english\": {},\n",+ " \"rouge_similarity\": {\n",+ " \"existing_instructions\": [\"Some existing instructions\"],\n",+ " \"threshold\": 0.6\n",+ " }\n",+ "}"+ ],+ "metadata": {+ "id": "gEuGuwJy08KC"+ },+ "execution_count": 19,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "Then, initialize an `InstructionFilter`"+ ],+ "metadata": {+ "id": "7-QpykWW1W4U"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "from camel.datagen.self_instruct import InstructionFilter\n",+ "filters = InstructionFilter(filter_config)"+ ],+ "metadata": {+ "id": "gB288iJB13M7"+ },+ "execution_count": 20,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "## Pipeline Setup with Custom `InstructionFilter`\n",+ "CAMEL has some default filter functions inside the pipeline, but you can also choose your own!"+ ],+ "metadata": {+ "id": "aiAbtsEM3BwC"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "pipeline = SelfInstructPipeline(\n",+ " agent=agent,\n",+ " seed=seed_path,\n",+ " num_machine_instructions=target_num_instructions,\n",+ " data_output_path=data_output_path,\n",+ " human_to_machine_ratio=(num_human_sample, num_machine_sample),\n",+ " instruction_filter=filters, # pass in your InstructionFilter\n",+ ")"+ ],+ "metadata": {+ "id": "FN_8zeX23IHa"+ },+ "execution_count": 24,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "Or if you want to use the default function filters, but different configuration, you can also just pass in the filter configuration"+ ],+ "metadata": {+ "id": "TnU_hc2S3pz4"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "Finally, generate!"+ ],+ "metadata": {+ "id": "Z1K-0szy4RGj"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "pipeline.generate()"+ ],+ "metadata": {+ "id": "RRSDuaiU4T-L"+ },+ "execution_count": 25,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "Pretty print the generated data content"+ ],+ "metadata": {+ "id": "k417Rj5rZ7Zk"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "import json\n",+ "\n",+ "with open(data_output_path, 'r') as file:\n",+ " data = json.load(file)\n",+ " print(json.dumps(data, indent=4))"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "y0Ump0HWZ7xA",+ "outputId": "421f0662-9292-4964-c510-b9de950505d2"+ },+ "execution_count": 26,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "[\n",+ " {\n",+ " \"id\": \"machine_task_1\",\n",+ " \"instruction\": \"Create a crossword puzzle with clues related to famous scientists and their discoveries.\",\n",+ " \"is_classification\": false,\n",+ " \"instances\": [\n",+ " {\n",+ " \"input\": \"\",\n",+ " \"output\": \"Across:\\n1. Scientist known for the theory of relativity (6) - Einstein\\n5. Unit of frequency, named after a German physicist (7) - Hertz\\n\\nDown:\\n1. Father of genetics, studied pea plants (7) - Mendel\\n2. Invented the telephone, Scottish-born (8) - Bell\"\n",+ " },\n",+ " {\n",+ " \"input\": \"\",\n",+ " \"output\": \"Across:\\n1. Proposed the heliocentric model of the solar system (6) - Copernicus\\n4. Formulated the laws of motion and universal gravitation (8) - Newton\\n\\nDown:\\n1. Discovered the structure of DNA, worked with Watson (6) - Crick\\n2. Proposed the theory of evolution by natural selection (9) - Darwin\"\n",+ " }\n",+ " ]\n",+ " },\n",+ " {\n",+ " \"id\": \"machine_task_2\",\n",+ " \"instruction\": \"Design a workout plan tailored to someone with a specific fitness goal, such as weight loss or muscle gain.\",\n",+ " \"is_classification\": false,\n",+ " \"instances\": [\n",+ " {\n",+ " \"input\": \"Fitness Goal - Weight Loss\",\n",+ " \"output\": \"1. Monday: Cardio (30 min jog) and Light Weights\\n2. Tuesday: Yoga (60 min session)\\n3. Wednesday: HIIT (30 min session)\\n4. Thursday: Swimming (30 min)\\n5. Friday: Cycling (45 min session)\\n6. Saturday: Rest or Light Activity (Walk, Stretch)\\n7. Sunday: Rest or Light Activity (Walk, Stretch)\"\n",+ " },\n",+ " {\n",+ " \"input\": \"Fitness Goal - Muscle Gain\",\n",+ " \"output\": \"1. Monday: Chest and Triceps\\n2. Tuesday: Back and Biceps\\n3. Wednesday: Rest or Light Activity (Stretching)\\n4. Thursday: Legs\\n5. Friday: Shoulders and Abs\\n6. Saturday: Full Body Circuit Training\\n7. Sunday: Rest or Light Activity (Stretching)\"\n",+ " }\n",+ " ]\n",+ " },\n",+ " {\n",+ " \"id\": \"machine_task_3\",\n",+ " \"instruction\": \"Compose a short story that incorporates the given three random words as key elements.\",\n",+ " \"is_classification\": false,\n",+ " \"instances\": [\n",+ " {\n",+ " \"input\": \"[\\\"river\\\", \\\"midnight\\\", \\\"mystery\\\"]\",\n",+ " \"output\": \"At midnight, the river seemed to whisper secrets as thick fog enveloped its banks. Along its shore, Sarah stood, her heart pounding with the thrill of the mystery that awaited her. Legend had it that the river held many mysteries within its depths, and tonight, she planned to uncover them. As she approached the water's edge, she noticed a faint light flickering across the water. Her curiosity piqued, she ventured forth, only to discover an old boat half-submerged in the river. Determined to unveil the secrets it held, she spent hours exploring the boat and the riverbank, until the first light of dawn broke the darkness.\"\n",+ " },\n",+ " {\n",+ " \"input\": \"[\\\"castle\\\", \\\"dragon\\\", \\\"princess\\\"]\",\n",+ " \"output\": \"In a faraway kingdom, Princess Amelia lived in a grand castle atop a hill. One day, a fearsome dragon began terrorizing the nearby villages. The king offered half his kingdom and Amelia's hand in marriage to whoever could slay the beast. Many knights tried and failed, but a humble farmer's son named Thomas succeeded. Instead of claiming the reward, he asked only for passage to the castle. There, he and Amelia discovered a shared love for adventure and soon embarked on a quest together, with the dragon as their guide, leaving behind the life of luxury in the castle.\"\n",+ " }\n",+ " ]\n",+ " },\n",+ " {\n",+ " \"id\": \"machine_task_4\",\n",+ " \"instruction\": \"Generate a list of potential names for a new restaurant, focusing on themes of nature and sustainability.\",\n",+ " \"is_classification\": false,\n",+ " \"instances\": [\n",+ " {\n",+ " \"input\": \"\",\n",+ " \"output\": \"- Green Haven\\n- Eco Eats\\n- Nature's Nook\\n- Sustainable Spoon\\n- Leafy Lounge\"\n",+ " },\n",+ " {\n",+ " \"input\": \"\",\n",+ " \"output\": \"- The Verdant Table\\n- Organic Oasis\\n- Farm to Fork Feast\\n- Earthy Eateria\\n- Clean Cuisine Corner\"\n",+ " }\n",+ " ]\n",+ " },\n",+ " {\n",+ " \"id\": \"machine_task_5\",\n",+ " \"instruction\": \"Design a logo for a local business that reflects its industry and values.\",\n",+ " \"is_classification\": false,\n",+ " \"instances\": [\n",+ " {\n",+ " \"input\": \"Business - \\\"Green Garden Cafe\\\", Industry - \\\"Caf\\u00e9\\\", Values - \\\"Sustainability, Community\\\"\",\n",+ " \"output\": \"A green leaf intertwined with a coffee cup, symbolizing the caf\\u00e9's commitment to sustainability. Underneath, the words \\\"Green Garden Cafe\\\" in a friendly, inviting font, with a small icon of people gathered around a table to represent community.\"\n",+ " },\n",+ " {\n",+ " \"input\": \"Business - \\\"Tech Innovators Inc.\\\", Industry - \\\"Technology\\\", Values - \\\"Innovation, Leadership, Cutting-edge\\\"\",\n",+ " \"output\": \"A modern, sleek design featuring a lightbulb made up of interconnected circuit boards, symbolizing innovation and cutting-edge technology. The words \\\"Tech Innovators Inc.\\\" in bold, contemporary font underneath, with a small icon of a leader's profile to represent leadership.\"\n",+ " }\n",+ " ]\n",+ " }\n",+ "]\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "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": {+ "id": "IXkjy1fq4cmM"+ }+ }+ ]+}\ No newline at end of filediff --git a/docs/cookbooks/model_training/sft_data_generation_and_unsloth_finetuning_Qwen2_5_7B.ipynb b/docs/cookbooks/data_generation/sft_data_generation_and_unsloth_finetuning_Qwen2_5_7B.ipynbsimilarity index 100%rename from docs/cookbooks/model_training/sft_data_generation_and_unsloth_finetuning_Qwen2_5_7B.ipynbrename to docs/cookbooks/data_generation/sft_data_generation_and_unsloth_finetuning_Qwen2_5_7B.ipynbdiff --git a/docs/cookbooks/model_training/sft_data_generation_and_unsloth_finetuning_mistral_7b_instruct.ipynb b/docs/cookbooks/data_generation/sft_data_generation_and_unsloth_finetuning_mistral_7b_instruct.ipynbsimilarity index 100%rename from docs/cookbooks/model_training/sft_data_generation_and_unsloth_finetuning_mistral_7b_instruct.ipynbrename to docs/cookbooks/data_generation/sft_data_generation_and_unsloth_finetuning_mistral_7b_instruct.ipynbdiff --git a/docs/cookbooks/model_training/sft_data_generation_and_unsloth_finetuning_tinyllama.ipynb b/docs/cookbooks/data_generation/sft_data_generation_and_unsloth_finetuning_tinyllama.ipynbsimilarity index 100%rename from docs/cookbooks/model_training/sft_data_generation_and_unsloth_finetuning_tinyllama.ipynbrename to docs/cookbooks/data_generation/sft_data_generation_and_unsloth_finetuning_tinyllama.ipynbdiff --git a/docs/cookbooks/model_training/cot_data_gen_upload_to_huggingface.ipynb b/docs/cookbooks/model_training/cot_data_gen_upload_to_huggingface.ipynbdeleted file mode 100644index 89405dfe1..000000000--- a/docs/cookbooks/model_training/cot_data_gen_upload_to_huggingface.ipynb+++ /dev/null@@ -1,1081 +0,0 @@-{- "cells": [- {- "cell_type": "markdown",- "id": "d80bea45",- "metadata": {- "id": "d80bea45"- },- "source": [- "# CoT Data Generation with CAMEL and Upload Data to Huggingface"- ]- },- {- "cell_type": "markdown",- "id": "MgAnJZTCCNDl",- "metadata": {- "id": "MgAnJZTCCNDl"- },- "source": [- "You can also check this cookbook in colab [here](https://drive.google.com/file/d/1DQuqntZsgWUaq9tHu4nfNEHTEwxKWXWw/view?usp=sharing) (Use the colab share link)\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)"- ]- },- {- "cell_type": "markdown",- "id": "RiZXE5RDB8tu",- "metadata": {- "id": "RiZXE5RDB8tu"- },- "source": [- "\n",- "\n",- "This notebook demonstrates how to set up and leverage CAMEL's **CoTDataGenerator** for generating high-quality question-answer pairs like o1 thinking data, uploading the data to Hugging Face.\n",- "\n",- "In this notebook, you'll explore:\n",- "\n",- "- **CAMEL**: A powerful multi-agent framework that enables SFT data generation and multi-agent role-playing scenarios, allowing for sophisticated AI-driven tasks.\n",- "- **CoTDataGenerator**: A tool for generating like o1 thinking data.\n",- "\n",- "- **Hugging Face Integration**: Uploading datasets to the Hugging Face platform for sharing\n"- ]- },- {- "cell_type": "markdown",- "id": "EnupE_558wFh",- "metadata": {- "id": "EnupE_558wFh"- },- "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",- "id": "0J0_iW-YVcq2",- "metadata": {- "id": "0J0_iW-YVcq2"- },- "source": [- "## ๐ฆ Installation"- ]- },- {- "cell_type": "code",- "execution_count": null,- "id": "87b853af",- "metadata": {- "id": "87b853af"- },- "outputs": [],- "source": [- "%%capture\n",- "!pip install camel-ai==0.2.16"- ]- },- {- "cell_type": "code",- "execution_count": null,- "id": "b77fd525",- "metadata": {- "id": "b77fd525",- "lines_to_next_cell": 2- },- "outputs": [],- "source": [- "import os\n",- "from datetime import datetime\n",- "import json\n",- "from camel.datagen.cotdatagen import CoTDataGenerator"- ]- },- {- "cell_type": "markdown",- "id": "lfNvFbhD6o8B",- "metadata": {- "id": "lfNvFbhD6o8B"- },- "source": [- "## ๐ Setting Up API Keys"- ]- },- {- "cell_type": "markdown",- "id": "a382a3a8",- "metadata": {- "id": "a382a3a8"- },- "source": [- "First we will set the OPENAI_API_KEY that will be used to generate the data.\n",- "\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "id": "5e59f61c",- "metadata": {- "id": "5e59f61c",- "lines_to_next_cell": 2- },- "outputs": [],- "source": [- "from getpass import getpass"- ]- },- {- "cell_type": "code",- "execution_count": null,- "id": "c90eae14",- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "c90eae14",- "lines_to_next_cell": 2,- "outputId": "c8d3ac17-502b-4ef2-d88b-6945fc385c82"- },- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "Enter your OpenAI API key: ยทยทยทยทยทยทยทยทยทยท\n"- ]- }- ],- "source": [- "openai_api_key = getpass('Enter your OpenAI API key: ')\n",- "os.environ[\"OPENAI_API_KEY\"] = openai_api_key"- ]- },- {- "cell_type": "markdown",- "id": "aecd3b42",- "metadata": {- "id": "aecd3b42"- },- "source": [- "## Set ChatAgent"- ]- },- {- "cell_type": "markdown",- "id": "bd726b2a",- "metadata": {- "id": "bd726b2a"- },- "source": [- "Create a system message to define agent's default role and behaviors."- ]- },- {- "cell_type": "code",- "execution_count": null,- "id": "a768c2af",- "metadata": {- "id": "a768c2af",- "lines_to_next_cell": 2- },- "outputs": [],- "source": [- "sys_msg = 'You are a genius at slow-thinking data and code'"- ]- },- {- "cell_type": "markdown",- "id": "f0f39ad6",- "metadata": {- "id": "f0f39ad6",- "lines_to_next_cell": 2- },- "source": [- "Use ModelFactory to set up the backend model for agent\n",- "\n",- "CAMEL supports many other models. See [here](https://docs.camel-ai.org/key_modules/models.html) for a list."- ]- },- {- "cell_type": "code",- "execution_count": null,- "id": "662e2f69",- "metadata": {- "id": "662e2f69"- },- "outputs": [],- "source": [- "from camel.models import ModelFactory\n",- "from camel.types import ModelPlatformType, ModelType\n",- "from camel.configs import ChatGPTConfig"- ]- },- {- "cell_type": "code",- "execution_count": null,- "id": "108da101",- "metadata": {- "id": "108da101"- },- "outputs": [],- "source": [- "# Define the model, here in this case we use gpt-4o-mini\n",- "model = ModelFactory.create(\n",- " model_platform=ModelPlatformType.OPENAI,\n",- " model_type=ModelType.GPT_4O_MINI,\n",- " model_config_dict=ChatGPTConfig().as_dict(), # [Optional] the config for model\n",- ")"- ]- },- {- "cell_type": "code",- "execution_count": null,- "id": "946b410d",- "metadata": {- "id": "946b410d",- "lines_to_next_cell": 2- },- "outputs": [],- "source": [- "from camel.agents import ChatAgent\n",- "chat_agent = ChatAgent(\n",- " system_message=sys_msg,\n",- " model=model,\n",- " message_window_size=10,\n",- ")"- ]- },- {- "cell_type": "markdown",- "id": "ed4208d6",- "metadata": {- "id": "ed4208d6",- "lines_to_next_cell": 2- },- "source": [- "## Load Q&A data from a JSON file"- ]- },- {- "cell_type": "markdown",- "id": "64e2b2cd",- "metadata": {- "id": "64e2b2cd"- },- "source": [- "### please prepare the qa data like below in json file:\n",- "\n",- "'''\n",- "{\n",- " \"question1\": \"answer1\",\n",- " \"question2\": \"answer2\",\n",- " ...\n",- "}\n",- "'''"- ]- },- {- "cell_type": "code",- "execution_count": null,- "id": "0XuYttZgwupa",- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "0XuYttZgwupa",- "outputId": "e20a3ff8-5df6-4e90-f0ab-91c23fc5c7f2"- },- "outputs": [- {- "output_type": "stream",- "name": "stdout",- "text": [- "/content\n"- ]- }- ],- "source": [- "!pwd"- ]- },- {- "cell_type": "markdown",- "id": "RERFki4MpiHH",- "metadata": {- "id": "RERFki4MpiHH"- },- "source": [- "The script fetches a example JSON file containing question-answer pairs from a GitHub repository and saves it locally. The JSON file is then loaded into the qa_data variable."- ]- },- {- "cell_type": "code",- "execution_count": null,- "id": "qACKggkeDAVQ",- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "qACKggkeDAVQ",- "outputId": "70d0eb2f-154f-44a4-ea95-c10653e54741"- },- "outputs": [- {- "output_type": "stream",- "name": "stdout",- "text": [- "JSON data successfully saved to qa_data.json\n"- ]- }- ],- "source": [- "#get example json data\n",- "\n",- "import requests\n",- "import json\n",- "\n",- "# URL of the JSON file\n",- "url = 'https://raw.githubusercontent.com/zjrwtx/alldata/refs/heads/main/qa_data.json'\n",- "\n",- "# Send a GET request to fetch the JSON file\n",- "response = requests.get(url)\n",- "\n",- "# Check if the request was successful\n",- "if response.status_code == 200:\n",- " # Parse the response content as JSON\n",- " json_data = response.json()\n",- "\n",- " # Specify the file path to save the JSON data\n",- " file_path = 'qa_data.json'\n",- "\n",- " # Write the JSON data to the file\n",- " with open(file_path, 'w', encoding='utf-8') as json_file:\n",- " json.dump(json_data, json_file, ensure_ascii=False, indent=4)\n",- "\n",- " print(f\"JSON data successfully saved to {file_path}\")\n",- "else:\n",- " print(f\"Failed to retrieve JSON file. Status code: {response.status_code}\")"- ]- },- {- "cell_type": "code",- "execution_count": null,- "id": "orMVK60weVn7",- "metadata": {- "id": "orMVK60weVn7"- },- "outputs": [],- "source": [- "with open(file_path, 'r', encoding='utf-8') as f:\n",- " qa_data = json.load(f)"- ]- },- {- "cell_type": "markdown",- "id": "12631bd0",- "metadata": {- "id": "12631bd0",- "lines_to_next_cell": 2- },- "source": [- "## Create an instance of CoTDataGenerator"- ]- },- {- "cell_type": "code",- "execution_count": null,- "id": "4fdb7792",- "metadata": {- "id": "4fdb7792"- },- "outputs": [],- "source": [- "# Create an instance of CoTDataGenerator\n",- "testo1 = CoTDataGenerator(chat_agent, golden_answers=qa_data)"- ]- },- {- "cell_type": "code",- "execution_count": null,- "id": "23e2d5a8",- "metadata": {- "id": "23e2d5a8",- "lines_to_next_cell": 2- },- "outputs": [],- "source": [- "# Record generated answers\n",- "generated_answers = {}"- ]- },- {- "cell_type": "markdown",- "id": "6d92f64e",- "metadata": {- "id": "6d92f64e"- },- "source": [- "## Test Q&A"- ]- },- {- "cell_type": "markdown",- "id": "v4Vi60CQrZTZ",- "metadata": {- "id": "v4Vi60CQrZTZ"- },- "source": [- "The script iterates through the questions, generates answers, and verifies their correctness. The generated answers are stored in a dictionary"- ]- },- {- "cell_type": "code",- "execution_count": null,- "id": "7fd7fe57",- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "7fd7fe57",- "lines_to_next_cell": 2,- "outputId": "169667d1-2eb0-4aac-f333-7726a83bb42b"- },- "outputs": [- {- "output_type": "stream",- "name": "stdout",- "text": [- "Question: What is the coefficient of $x^2y^6$ in the expansion of $\\left(\\frac{3}{5}x-\\frac{y}{2}\\right)^8$? Express your answer as a common fraction\n",- "AI's thought process and answer:\n",- "To find the coefficient of \\( x^2y^6 \\) in the expansion of \\( \\left(\\frac{3}{5}x - \\frac{y}{2}\\right)^8 \\), we will use the Binomial Theorem, which states that:\n",- "\n",- "\\[\n",- "(a + b)^n = \\sum_{k=0}^{n} \\binom{n}{k} a^{n-k} b^k\n",- "\\]\n",- "\n",- "In our case, we can identify \\( a = \\frac{3}{5}x \\) and \\( b = -\\frac{y}{2} \\), and \\( n = 8 \\).\n",- "\n",- "### Step 1: Analyze the problem requirements\n",- "We need to find the specific term in the expansion that contains \\( x^2y^6 \\). This means we need to determine the values of \\( k \\) and \\( n-k \\) such that:\n",- "\n",- "- The power of \\( x \\) is \\( 2 \\)\n",- "- The power of \\( y \\) is \\( 6 \\)\n",- "\n",- "### Step 2: List the steps to solve the problem\n",- "1. Identify the general term in the binomial expansion.\n",- "2. Set up equations based on the powers of \\( x \\) and \\( y \\).\n",- "3. Solve for \\( k \\) and \\( n-k \\).\n",- "4. Substitute \\( k \\) back into the general term to find the coefficient.\n",- "5. Simplify to get the final answer.\n",- "\n",- "### Step 3: Execute the solution process\n",- "1. The general term in the expansion is given by:\n",- "\n",- "\\[\n",- "T_k = \\binom{8}{k} \\left(\\frac{3}{5}x\\right)^{8-k} \\left(-\\frac{y}{2}\\right)^k\n",- "\\]\n",- "\n",- "2. We need \\( (8-k) \\) to equal \\( 2 \\) (for \\( x^2 \\)) and \\( k \\) to equal \\( 6 \\) (for \\( y^6 \\)). Thus, we set up the equations:\n",- "\n",- "\\[\n",- "8 - k = 2 \\quad \\Rightarrow \\quad k = 6\n",- "\\]\n",- "\n",- "3. Now, we substitute \\( k = 6 \\) into the general term:\n",- "\n",- "\\[\n",- "T_6 = \\binom{8}{6} \\left(\\frac{3}{5}x\\right)^{2} \\left(-\\frac{y}{2}\\right)^{6}\n",- "\\]\n",- "\n",- "4. Calculate \\( \\binom{8}{6} \\):\n",- "\n",- "\\[\n",- "\\binom{8}{6} = \\binom{8}{2} = \\frac{8 \\times 7}{2 \\times 1} = 28\n",- "\\]\n",- "\n",- "5. Now substitute \\( k = 6 \\) into the term:\n",- "\n",- "\\[\n",- "T_6 = 28 \\left(\\frac{3}{5}x\\right)^{2} \\left(-\\frac{y}{2}\\right)^{6}\n",- "\\]\n",- "\n",- "Calculating each part:\n",- "\n",- "\\[\n",- "\\left(\\frac{3}{5}x\\right)^{2} = \\frac{9}{25}x^2\n",- "\\]\n",- "\\[\n",- "\\left(-\\frac{y}{2}\\right)^{6} = \\left(-1\\right)^{6} \\left(\\frac{y}{2}\\right)^{6} = \\frac{y^6}{64}\n",- "\\]\n",- "\n",- "6. Combine these results:\n",- "\n",- "\\[\n",- "T_6 = 28 \\cdot \\frac{9}{25} x^2 \\cdot \\frac{y^6}{64}\n",- "\\]\n",- "\n",- "7. Now, calculate the coefficient:\n",- "\n",- "\\[\n",- "\\text{Coefficient} = 28 \\cdot \\frac{9}{25} \\cdot \\frac{1}{64} = \\frac{28 \\cdot 9}{25 \\cdot 64}\n",- "\\]\n",- "\n",- "Calculating \\( 28 \\cdot 9 = 252 \\):\n",- "\n",- "\\[\n",- "\\text{Coefficient} = \\frac{252}{1600}\n",- "\\]\n",- "\n",- "8. Simplify \\( \\frac{252}{1600} \\):\n",- "\n",- "The GCD of \\( 252 \\) and \\( 1600 \\) is \\( 4 \\):\n",- "\n",- "\\[\n",- "\\frac{252 \\div 4}{1600 \\div 4} = \\frac{63}{400}\n",- "\\]\n",- "\n",- "### Step 4: Provide the final answer\n",- "The coefficient of \\( x^2y^6 \\) in the expansion of \\( \\left(\\frac{3}{5}x - \\frac{y}{2}\\right)^8 \\) is:\n",- "\n",- "\\[\n",- "\\boxed{\\frac{63}{400}}\n",- "\\]\n",- "Answer verification result: Correct\n",- "--------------------------------------------------\n",- "\n",- "Question: how many a in banana?\n",- "AI's thought process and answer:\n",- "Sure! Let's break down the problem of counting the letter \"a\" in the word \"banana\" step by step.\n",- "\n",- "### Step 1: Analyze the Problem Requirements\n",- "The problem requires us to determine how many times the letter \"a\" appears in the word \"banana.\" This involves:\n",- "- Identifying the specific letter we are counting (in this case, \"a\").\n",- "- Understanding the context (the word \"banana\") and ensuring we only count occurrences of \"a\" in this specific word.\n",- "\n",- "### Step 2: List the Steps to Solve the Problem\n",- "To solve the problem, we can outline the following steps:\n",- "1. Write down the word \"banana.\"\n",- "2. Identify each letter in the word.\n",- "3. Count how many times the letter \"a\" appears in the word.\n",- "\n",- "### Step 3: Execute the Solution Process\n",- "Now, let's execute the steps outlined:\n",- "\n",- "1. **Write down the word**: The word is \"banana.\"\n",- "2. **Identify each letter**: The letters in \"banana\" are:\n",- " - b\n",- " - a\n",- " - n\n",- " - a\n",- " - n\n",- " - a\n",- "\n",- "3. **Count the occurrences of \"a\"**:\n",- " - The first letter is \"b\" (not \"a\").\n",- " - The second letter is \"a\" (count = 1).\n",- " - The third letter is \"n\" (not \"a\").\n",- " - The fourth letter is \"a\" (count = 2).\n",- " - The fifth letter is \"n\" (not \"a\").\n",- " - The sixth letter is \"a\" (count = 3).\n",- "\n",- "### Step 4: Provide the Final Answer\n",- "After counting, we find that the letter \"a\" appears **3 times** in the word \"banana.\"\n",- "\n",- "### Conclusion\n",- "The thought process involved breaking down the problem into manageable steps, carefully identifying each letter, and systematically counting the occurrences of the specified letter. The final answer is that there are **3 occurrences of the letter \"a\" in the word \"banana.\"**\n",- "Answer verification result: Correct\n",- "--------------------------------------------------\n",- "\n"- ]- }- ],- "source": [- "# Test Q&A\n",- "for question in qa_data.keys():\n",- " print(f\"Question: {question}\")\n",- "\n",- " # Get AI's thought process and answer\n",- " answer = testo1.get_answer(question)\n",- " generated_answers[question] = answer\n",- " print(f\"AI's thought process and answer:\\n{answer}\")\n",- "\n",- " # Verify the answer\n",- " is_correct = testo1.verify_answer(question, answer)\n",- " print(f\"Answer verification result: {'Correct' if is_correct else 'Incorrect'}\")\n",- " print(\"-\" * 50)\n",- " print() # Add a new line at the end of each iteration"- ]- },- {- "cell_type": "markdown",- "id": "8b35c0e9",- "metadata": {- "id": "8b35c0e9",- "lines_to_next_cell": 2- },- "source": [- "### Export the generated answers to a JSON file and transform these to Alpaca traing data format\n",- "\n",- "\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "id": "d47d8529",- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "d47d8529",- "lines_to_next_cell": 2,- "outputId": "60a4a6f6-5614-480d-8d5c-d4116ce5457c"- },- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "The generated answers have been exported to: generated_answers_20241227_111615.json\n"- ]- }- ],- "source": [- "simplified_output = {\n",- " 'timestamp': datetime.now().isoformat(),\n",- " 'qa_pairs': generated_answers\n",- "}\n",- "simplified_file = f'generated_answers_{datetime.now().strftime(\"%Y%m%d_%H%M%S\")}.json'\n",- "with open(simplified_file, 'w', encoding='utf-8') as f:\n",- " json.dump(simplified_output, f, ensure_ascii=False, indent=2)\n",- "print(f\"The generated answers have been exported to: {simplified_file}\")"- ]- },- {- "cell_type": "markdown",- "id": "riC_gYznYFN6",- "metadata": {- "id": "riC_gYznYFN6"- },- "source": [- "The script transforms the Q&A data into the Alpaca training data format, which is suitable for supervised fine-tuning (SFT). The transformed data is saved to a new JSON file."- ]- },- {- "cell_type": "code",- "execution_count": null,- "id": "2ef8dfbc",- "metadata": {- "id": "2ef8dfbc"- },- "outputs": [],- "source": [- "import json\n",- "from datetime import datetime\n",- "\n",- "def transform_qa_format(input_file):\n",- " # Read the input JSON file\n",- " with open(input_file, 'r', encoding='utf-8') as f:\n",- " data = json.load(f)\n",- "\n",- " # Transform the data\n",- " transformed_data = []\n",- " for question, answer in data['qa_pairs'].items():\n",- " transformed_pair = {\n",- " \"instruction\": question,\n",- " \"input\": \"\",\n",- " \"output\": answer\n",- " }\n",- " transformed_data.append(transformed_pair)\n",- "\n",- " # Generate output filename with timestamp\n",- " timestamp = datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n",- " output_file = f'transformed_qa_{timestamp}.json'\n",- "\n",- " # Write the transformed data\n",- " with open(output_file, 'w', encoding='utf-8') as f:\n",- " json.dump(transformed_data, f, ensure_ascii=False, indent=2)\n",- "\n",- " return output_file, transformed_data"- ]- },- {- "cell_type": "code",- "execution_count": null,- "id": "a83515f3",- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "a83515f3",- "outputId": "47e2fffd-6989-452c-a305-e4fcdf3998f6"- },- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "Transformation complete. Output saved to: transformed_qa_20241227_111622.json\n"- ]- }- ],- "source": [- "output_file, transformed_data = transform_qa_format(simplified_file)\n",- "print(f\"Transformation complete. Output saved to: {output_file}\")"- ]- },- {- "cell_type": "markdown",- "id": "lK8qEmdGYUeX",- "metadata": {- "id": "lK8qEmdGYUeX"- },- "source": [- "## Upload the Data to Huggingface"- ]- },- {- "cell_type": "markdown",- "id": "1696368d",- "metadata": {- "id": "1696368d"- },- "source": [- "This defines a function upload_to_huggingface that uploads a dataset to Hugging Face. The script is modular, with helper functions handling specific tasks such as dataset name generation, dataset creation, metadata card creation, and record addition"- ]- },- {- "cell_type": "code",- "execution_count": null,- "id": "5TYOIiF3yQZC",- "metadata": {- "id": "5TYOIiF3yQZC"- },- "outputs": [],- "source": [- "# Import necessary modules and classes\n",- "from camel.datahubs.huggingface import HuggingFaceDatasetManager # Manages interactions with Hugging Face datasets\n",- "from camel.datahubs.models import Record # Represents a single record in the dataset\n",- "from datetime import datetime # Handles date and time operations\n",- "\n",- "# Main function: Upload dataset to Hugging Face\n",- "def upload_to_huggingface(transformed_data, username, dataset_name=None):\n",- " r\"\"\"Uploads transformed data to the Hugging Face dataset platform.\n",- "\n",- " Args:\n",- " transformed_data (list): Transformed data, typically a list of dictionaries.\n",- " username (str): Hugging Face username.\n",- " dataset_name (str, optional): Custom dataset name.\n",- "\n",- " Returns:\n",- " str: URL of the uploaded dataset.\n",- " \"\"\"\n",- " # Initialize HuggingFaceDatasetManager to interact with Hugging Face datasets\n",- " manager = HuggingFaceDatasetManager()\n",- "\n",- " # Generate or validate the dataset name\n",- " dataset_name = generate_or_validate_dataset_name(username, dataset_name)\n",- "\n",- " # Create the dataset on Hugging Face and get the dataset URL\n",- " dataset_url = create_dataset(manager, dataset_name)\n",- "\n",- " # Create a dataset card to add metadata\n",- " create_dataset_card(manager, dataset_name, username)\n",- "\n",- " # Convert the transformed data into a list of Record objects\n",- " records = create_records(transformed_data)\n",- "\n",- " # Add the Record objects to the dataset\n",- " add_records_to_dataset(manager, dataset_name, records)\n",- "\n",- " # Return the dataset URL\n",- " return dataset_url\n",- "\n",- "# Generate or validate the dataset name\n",- "def generate_or_validate_dataset_name(username, dataset_name):\n",- " r\"\"\"Generates a default dataset name or validates and formats a user-provided name.\n",- "\n",- " Args:\n",- " username (str): Hugging Face username.\n",- " dataset_name (str, optional): User-provided custom dataset name.\n",- "\n",- " Returns:\n",- " str: Formatted dataset name.\n",- " \"\"\"\n",- " if dataset_name is None:\n",- " # If no dataset name is provided, generate a default name with the username and current date\n",- " dataset_name = f\"{username}/qa-dataset-{datetime.now().strftime('%Y%m%d')}\"\n",- " else:\n",- " # If a dataset name is provided, format it to include the username\n",- " dataset_name = f\"{username}/{dataset_name}\"\n",- " return dataset_name\n",- "\n",- "# Create a dataset on Hugging Face\n",- "def create_dataset(manager, dataset_name):\n",- " r\"\"\"Creates a new dataset on Hugging Face and returns the dataset URL.\n",- "\n",- " Args:\n",- " manager (HuggingFaceDatasetManager): Instance of HuggingFaceDatasetManager.\n",- " dataset_name (str): Name of the dataset.\n",- "\n",- " Returns:\n",- " str: URL of the created dataset.\n",- " \"\"\"\n",- " print(f\"Creating dataset: {dataset_name}\")\n",- " # Use HuggingFaceDatasetManager to create the dataset\n",- " dataset_url = manager.create_dataset(name=dataset_name)\n",- " print(f\"Dataset created: {dataset_url}\")\n",- " return dataset_url\n",- "\n",- "# Create a dataset card with metadata\n",- "def create_dataset_card(manager, dataset_name, username):\n",- " r\"\"\"Creates a dataset card to add metadata\n",- "\n",- " Args:\n",- " manager (HuggingFaceDatasetManager): Instance of HuggingFaceDatasetManager.\n",- " dataset_name (str): Name of the dataset.\n",- " username (str): Hugging Face username.\n",- " \"\"\"\n",- " print(\"Creating dataset card...\")\n",- " # Use HuggingFaceDatasetManager to create the dataset card\n",- " manager.create_dataset_card(\n",- " dataset_name=dataset_name,\n",- " description=\"Question-Answer dataset generated by CAMEL CoTDataGenerator\", # Dataset description\n",- " license=\"mit\", # Dataset license\n",- " language=[\"en\"], # Dataset language\n",- " size_category=\"<1MB\", # Dataset size category\n",- " version=\"0.1.0\", # Dataset version\n",- " tags=[\"camel\", \"question-answering\"], # Dataset tags\n",- " task_categories=[\"question-answering\"], # Dataset task categories\n",- " authors=[username] # Dataset authors\n",- " )\n",- " print(\"Dataset card created successfully.\")\n",- "\n",- "# Convert transformed data into Record objects\n",- "def create_records(transformed_data):\n",- " r\"\"\"Converts transformed data into a list of Record objects.\n",- "\n",- " Args:\n",- " transformed_data (list): Transformed data, typically a list of dictionaries.\n",- "\n",- " Returns:\n",- " list: List of Record objects.\n",- " \"\"\"\n",- " records = []\n",- " # Iterate through the transformed data and convert each dictionary into a Record object\n",- " for item in transformed_data:\n",- " record = Record(**item) # Use the dictionary key-value pairs to create a Record object\n",- " records.append(record)\n",- " return records\n",- "\n",- "# Add Record objects to the dataset\n",- "def add_records_to_dataset(manager, dataset_name, records):\n",- " r\"\"\"Adds a list of Record objects to the dataset.\n",- "\n",- " Args:\n",- " manager (HuggingFaceDatasetManager): Instance of HuggingFaceDatasetManager.\n",- " dataset_name (str): Name of the dataset.\n",- " records (list): List of Record objects.\n",- " \"\"\"\n",- " print(\"Adding records to the dataset...\")\n",- " # Use HuggingFaceDatasetManager to add the records to the dataset\n",- " manager.add_records(dataset_name=dataset_name, records=records)\n",- " print(\"Records added successfully.\")"- ]- },- {- "cell_type": "markdown",- "id": "TrxbW2_bY0im",- "metadata": {- "id": "TrxbW2_bY0im"- },- "source": [- "# Config Access Token of Huggingface"- ]- },- {- "cell_type": "markdown",- "metadata": {- "id": "YYlED5ONkemz"- },- "source": [- "You can go to [here](https://huggingface.co/settings/tokens/new?tokenType=write) to get API Key from Huggingface"- ],- "id": "YYlED5ONkemz"- },- {- "cell_type": "markdown",- "source": [- ""- ],- "metadata": {- "id": "T1r7USC2m3ea"- },- "id": "T1r7USC2m3ea"- },- {- "cell_type": "code",- "execution_count": null,- "id": "_QHHkipbY7kJ",- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "_QHHkipbY7kJ",- "outputId": "f88df1b1-268e-4a42-821c-486ac4dfa872"- },- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "Enter your HUGGING_FACE_TOKEN: ยทยทยทยทยทยทยทยทยทยท\n"- ]- }- ],- "source": [- "HUGGING_FACE_TOKEN = getpass('Enter your HUGGING_FACE_TOKEN: ')\n",- "os.environ[\"HUGGING_FACE_TOKEN\"] = HUGGING_FACE_TOKEN"- ]- },- {- "cell_type": "code",- "execution_count": null,- "id": "e84fb857",- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "e84fb857",- "outputId": "527a49bc-63e4-4e7d-b730-7c830f8a412e"- },- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "Enter your HuggingFace username: zjrwtxtechstudio\n",- "Enter dataset name (press Enter to use default): o1data88\n",- "Creating dataset: zjrwtxtechstudio/o1data88\n",- "Dataset created: https://huggingface.co/datasets/zjrwtxtechstudio/o1data88\n",- "Creating dataset card...\n",- "Dataset card created successfully.\n",- "Adding records to the dataset...\n",- "Records added successfully.\n",- "\n",- "Data successfully uploaded to HuggingFace!\n",- "Dataset URL: https://huggingface.co/datasets/zjrwtxtechstudio/o1data88\n"- ]- }- ],- "source": [- "# Set your personal huggingface config, then upload to HuggingFace\n",- "username = input(\"Enter your HuggingFace username: \")\n",- "dataset_name = input(\"Enter dataset name (press Enter to use default): \").strip()\n",- "if not dataset_name:\n",- " dataset_name = None\n",- "\n",- "try:\n",- " dataset_url = upload_to_huggingface(transformed_data, username, dataset_name)\n",- " print(f\"\\nData successfully uploaded to HuggingFace!\")\n",- " print(f\"Dataset URL: {dataset_url}\")\n",- "except Exception as e:\n",- " print(f\"Error uploading to HuggingFace: {str(e)}\")\n"- ]- },- {- "cell_type": "markdown",- "id": "2nLsMgSnzp6l",- "metadata": {- "id": "2nLsMgSnzp6l"- },- "source": [- "### final example preview"- ]- },- {- "cell_type": "markdown",- "id": "d1nFtlFFzldR",- "metadata": {- "id": "d1nFtlFFzldR"- },- "source": [- ""- ]- },- {- "cell_type": "markdown",- "id": "flYNal6-R4yR",- "metadata": {- "id": "flYNal6-R4yR"- },- "source": [- "## ๐ Highlights"- ]- },- {- "cell_type": "markdown",- "id": "-qsPHvwW6oW3",- "metadata": {- "id": "-qsPHvwW6oW3"- },- "source": [- "\n",- "\n",- "This cookbook demonstrates the process of using **CAMEL's CoTDataGenerator** to create high-quality question-answer pairs, similar to o1 thinking data. The notebook covers the following steps:\n",- "\n",- "1. **Setup**: Installation of the `camel-ai` library and configuration of the OpenAI API key.\n",- "2. **Data Generation**: Utilization of the `CoTDataGenerator` to generate answers for predefined questions using llm model.\n",- "3. **Data Transformation**: Conversion of the generated Q&A data into a format compliant with the Alpaca training data schema.\n",- "4. **Upload to Hugging Face**: Integration with Hugging Face to upload the transformed dataset, including the creation of a dataset card and metadata.\n",- "\n",- "The cookbook also includes detailed instructions for setting up the environment, handling API keys, and configuring the Hugging Face dataset upload process. The final output is a dataset uploaded to Hugging Face, ready for sharing and further use in AI training tasks."- ]- },- {- "cell_type": "markdown",- "id": "cGoeNB1X7Qv2",- "metadata": {- "id": "cGoeNB1X7Qv2"- },- "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": {- "accelerator": "GPU",- "colab": {- "gpuType": "T4",- "provenance": []- },- "jupytext": {- "cell_metadata_filter": "-all",- "main_language": "python",- "notebook_metadata_filter": "-all"- },- "kernelspec": {- "display_name": "camel-ai-1zf4chC7-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.5"- }- },- "nbformat": 4,- "nbformat_minor": 5-}\ No newline at end of filediff --git a/docs/index.rst b/docs/index.rstindex b3812cacb..112b63f90 100644--- a/docs/index.rst+++ b/docs/index.rst@@ -55,7 +55,7 @@ Main Documentationcookbooks/basic_concepts/indexcookbooks/advanced_features/indexcookbooks/multi_agent_society/index- cookbooks/model_training/index+ cookbooks/data_generation/indexcookbooks/applications/indexcookbooks/data_processing/index