Self-instruct Data Generation Using Qwen#
You can also check this cookbook in colab here
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.
In this notebook, you’ll explore:
CAMEL-AI: A versatile multi-agent framework that facilitates the creation and execution of complex data tasks.
Qwen: A large language model by Alibaba Cloud, used for instruction generation.
Self-Instruct Pipeline: A technique for automating instruction dataset creation.
Instruction Filters: A set of filters that is used to filter a dataset.
Installation and Setup#
First, install the CAMEL package with all its dependencies
[ ]:
!pip install "camel-ai[all]==0.2.18"
If you don’t have a Qwen API key, you can obtain one by following these steps:
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.
In the upper-right corner of the console, click on your account name and select API-KEY.
On the API Key management page, click on the Create API Key button to generate a new key.
[12]:
import os
from getpass import getpass
qwen_api_key = getpass('Enter your Qwen API key: ')
os.environ["QWEN_API_KEY"] = qwen_api_key
Enter your Qwen API key: ··········
[33]:
from camel.configs import QwenConfig
from camel.models import ModelFactory
from camel.types import ModelPlatformType, ModelType
from camel.agents import ChatAgent
from camel.messages import BaseMessage
qwen_model = ModelFactory.create(
model_platform=ModelPlatformType.QWEN,
model_type=ModelType.QWEN_TURBO,
model_config_dict=QwenConfig(temperature=0.2).as_dict(),
)
Basic Agent Setup#
[34]:
from camel.agents import ChatAgent
from camel.datagen.self_instruct import SelfInstructPipeline
agent = ChatAgent(
model=qwen_model,
)
Basic Pipeline Setup#
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.
The seed instructions are typically stored in a JSON Lines (JSONL) file. Each line in the file represents a single instruction in JSON format.
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.
Please replace seed_path
with the path to your seed file, and replace data_output_path
with your desired output location.
[ ]:
import os
import requests
# Create directory for local data
os.makedirs('local_data', exist_ok=True)
# Update the URL to the raw file content
url = "https://raw.githubusercontent.com/camel-ai/camel/master/examples/datagen/self_instruct/seed_tasks.jsonl"
# Fetch the raw file
response = requests.get(url)
with open('local_data/seed_tasks.jsonl', 'wb') as file:
file.write(response.content)
[36]:
seed_path = 'local_data/seed_tasks.jsonl'
data_output_path = 'data_output.json'
The cell below shows some example instructions in the seed file. All seed files should follow this format.
[37]:
with open('local_data/seed_tasks.jsonl', 'r') as file:
for i, line in enumerate(file):
print(line.strip())
if i >= 9:
break
{"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}
{"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}
{"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}
{"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}
{"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}
{"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}
{"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}
{"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}
{"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}
{"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}
The self-instruct pipeline works iteratively. In each round:
It selects a certain number of human-written instructions (
num_human_sample
) from theseed_path
.It selects a certain number of machine-generated instructions (
num_machine_sample
) from previous rounds.It uses these selected instructions to guide the language model in generating new instructions.
These new instructions are added to the pool of machine-generated instructions, and the process repeats until the desired number of instructions is generated.
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.
Feel free to alter num_human_sample
and num_machine_sample
, which both will be passed into human_to_machine_ratio
later
[38]:
num_human_sample = 6
num_machine_sample = 2
Please replace target_num_instructions
with the number of machine instructions you want to generate
[39]:
target_num_instructions = 3
Pass everything to our pipeline.
[40]:
pipeline = SelfInstructPipeline(
agent=agent,
seed=seed_path,
num_machine_instructions=target_num_instructions,
data_output_path=data_output_path,
human_to_machine_ratio=(num_human_sample, num_machine_sample),
)
Try generating it! You will see the generated data file being created at your desired location!
[41]:
pipeline.generate()
Pretty print the generated data content
[42]:
import json
with open(data_output_path, 'r') as file:
data = json.load(file)
print(json.dumps(data, indent=4))
[
{
"id": "machine_task_1",
"instruction": "Compose a detailed plan for a community initiative aimed at reducing waste in your local area and describe how it could positively impact the environment and community relations.",
"is_classification": false,
"instances": [
{
"input": "",
"output": "Plan: Implement a community-wide recycling program that includes regular curbside pickup, educational workshops on waste reduction, and incentives for businesses and residents who participate. Additionally, organize periodic community clean-up events to remove litter and promote community engagement.\n\nImpact: This initiative would significantly reduce the amount of waste sent to landfills, conserve natural resources, and decrease pollution. It would also foster a sense of community pride and cooperation, as residents and businesses work together towards a common goal."
},
{
"input": "",
"output": "Plan: Launch a composting initiative in public parks and schools, providing bins and educational materials. Partner with local farmers markets to accept food scraps for composting. Encourage restaurants to donate unused food to shelters and compostable waste to the program.\n\nImpact: This plan would divert organic waste from landfills, enrich soil health, and reduce greenhouse gas emissions. It would also strengthen community ties by engaging various sectors in sustainable practices, promoting environmental stewardship and civic responsibility."
}
]
},
{
"id": "machine_task_2",
"instruction": "Create a step-by-step guide on how to repurpose old furniture into unique home decor items.",
"is_classification": false,
"instances": [
{
"input": "",
"output": "Step 1: Gather materials such as paint, brushes, sandpaper, and any decorative elements like stencils or fabric.\nStep 2: Choose a piece of furniture to repurpose, such as an old dresser or table.\nStep 3: Sand the surface of the furniture to prepare it for painting or staining.\nStep 4: Paint or stain the furniture according to your desired design.\nStep 5: Once dry, apply any decorative elements like stencils or fabric to add unique details.\nStep 6: Allow the decorations to dry completely before using the newly repurposed furniture as a home decor item."
},
{
"input": "",
"output": "Step 1: Collect tools and supplies including a saw, screws, nails, and decorative hardware.\nStep 2: Select an old chair or table that needs refreshing.\nStep 3: Disassemble the furniture if necessary to access the parts needing repair.\nStep 4: Repair any broken or worn parts using the collected tools and supplies.\nStep 5: Reassemble the furniture and attach decorative hardware like knobs or legs.\nStep 6: Place the refurbished furniture in your home as a unique decor item."
}
]
},
{
"id": "machine_task_3",
"instruction": "Identify the main theme of the provided poem and provide a brief explanation.",
"is_classification": false,
"instances": [
{
"input": "Poem: \"The Road Not Taken\" by Robert Frost\nTwo roads diverged in a yellow wood,\nAnd sorry I could not travel both\nAnd be one traveler, long I stood\nAnd looked down one as far as I could\nTo where it bent in the undergrowth;\n\nThen took the other, as just as fair,\nAnd having perhaps the better claim,\nBecause it was grassy and wanted wear;\nThough as for that the passing there\nHad worn them really about the same,\n\nAnd both that morning equally lay\nIn leaves no step had trodden black.\nOh, I kept the first for another day!\nYet knowing how way leads on to way,\nI doubted if I should ever come back.\n\nI shall be telling this with a sigh\nSomewhere ages and ages hence:\nTwo roads diverged in a wood, and I\u2014\nI took the one less traveled by,\nAnd that has made all the difference.",
"output": "Main Theme: The poem explores the theme of choices and their consequences. It reflects on the speaker's decision to take the road less traveled and how it has shaped their life journey."
},
{
"input": "Poem: \"Still I Rise\" by Maya Angelou\nYou may write me down in history\nWith your bitter, twisted lies,\nYou may trod me in the very dirt\nBut still, like dust, I'll rise.\n\nDoes my sassiness upset you?\nWhy are you beset with gloom?\n'Cause I walk like I've got oil wells\nPumping in my living room.\n\nJust like moons and like suns,\nWith the certainty of tides,\nJust like hopes springing high,\nStill I'll rise.\n\nDid you want to see me broken?\nBowed head and lowered eyes?\nShoulders falling down like teardrops.\nWeakened by my soulful cries.\n\nDoes my haughtiness offend you?\nDon't you take it awful hard\n'Cause I laugh like I've got gold mines\nDiggin' in my own back yard.\n\nYou may shoot me with your words,\nYou may cut me with your eyes,\nYou may kill me with your hatefulness,\nBut still, like air, I'll rise.",
"output": "Main Theme: The poem celebrates resilience and self-esteem in the face of adversity. It emphasizes rising above oppression and discrimination with dignity and strength."
}
]
}
]
Filter functions#
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.
Length Filter#
LengthFilter
filters out all the instructions which has a length less than min_len
or greater than max_len
.
[43]:
from camel.datagen.self_instruct import LengthFilter
length_filter = LengthFilter(min_len=5, max_len=50)
instructions = [
"Sort the numbers in ascending order.",
"Calculate the sum.",
"Create a report that details the monthly expenses and savings in a spreadsheet."
]
filtered_instructions = [instr for instr in instructions if length_filter.apply(instr)]
print(filtered_instructions)
['Sort the numbers in ascending order.', 'Create a report that details the monthly expenses and savings in a spreadsheet.']
Keyword Filter#
KeywordFilter
filters instructions that contain specific undesirable keyword.
[44]:
from camel.datagen.self_instruct import KeywordFilter
keyword_filter = KeywordFilter(keywords=["ban", "prohibit", "forbid"])
instructions = [
"Ban the use of plastic bags.",
"Encourage recycling programs.",
"Prohibit smoking in public areas."
]
filtered_instructions = [instr for instr in instructions if keyword_filter.apply(instr)]
print(filtered_instructions)
['Encourage recycling programs.']
Punctuation Filter#
PunctuationFilter
filters instructions that begin with a non-alphanumeric character.
[45]:
from camel.datagen.self_instruct import PunctuationFilter
punctuation_filter = PunctuationFilter()
instructions = [
"Sort the data by category.",
"#Analyze the trends over time.",
"*Create a summary of results."
]
filtered_instructions = [instr for instr in instructions if punctuation_filter.apply(instr)]
print(filtered_instructions)
['Sort the data by category.']
Non-English Filter#
NonEnglishFilter
filters instructions that do not begin with English letters.
[46]:
from camel.datagen.self_instruct import NonEnglishFilter
non_english_filter = NonEnglishFilter()
instructions = [
"Analyze the performance metrics.",
"计算结果的统计数据.",
"Test the new algorithm."
]
filtered_instructions = [instr for instr in instructions if non_english_filter.apply(instr)]
print(filtered_instructions)
['Analyze the performance metrics.', 'Test the new algorithm.']
ROUGE Similarity Filter#
RougeSimilarityFilter
filters instructions that are too similar to existing instructions based on ROUGE scores.
[47]:
from camel.datagen.self_instruct import RougeSimilarityFilter
existing_instructions = [
"Summarize the article.",
"Write a brief overview of the text."
]
similarity_filter = RougeSimilarityFilter(existing_instructions, threshold=0.5)
instructions = [
"Summarize the content.",
"Create a summary for the text.",
"Provide an analysis of the text."
]
filtered_instructions = [instr for instr in instructions if similarity_filter.apply(instr)]
print(filtered_instructions)
['Create a summary for the text.', 'Provide an analysis of the text.']
Custom Filter Function#
Additionaly, you could implement your own filter function.
[48]:
from camel.datagen.self_instruct import FilterFunction
class CustomFilter(FilterFunction):
def apply(self, instruction: str) -> bool:
# apply your logic here
logic = ...
return logic
Instruction Filter#
InstructionFilter
manages all filter functions. And we can use a custom InstructionFilter to initialize the pipeline
Start by adding filter functions you want and configure them.
[49]:
filter_config = {
"length": {"min_len": 5, "max_len": 100},
"keyword": {"keywords": ["image", "video"]},
"non_english": {},
"rouge_similarity": {
"existing_instructions": ["Some existing instructions"],
"threshold": 0.6
}
}
Then, initialize an InstructionFilter
[50]:
from camel.datagen.self_instruct import InstructionFilter
filters = InstructionFilter(filter_config)
Pipeline Setup with Custom InstructionFilter
#
CAMEL has some default filter functions inside the pipeline, but you can also choose your own!
[51]:
pipeline = SelfInstructPipeline(
agent=agent,
seed=seed_path,
num_machine_instructions=target_num_instructions,
data_output_path=data_output_path,
human_to_machine_ratio=(num_human_sample, num_machine_sample),
instruction_filter=filters, # pass in your InstructionFilter
)
Or if you want to use the default function filters, but different configuration, you can also just pass in the filter configuration
Finally, generate!
[52]:
pipeline.generate()
Pretty print the generated data content
[53]:
import json
with open(data_output_path, 'r') as file:
data = json.load(file)
print(json.dumps(data, indent=4))
[
{
"id": "machine_task_1",
"instruction": "Write a Python function to determine if a given number is prime.",
"is_classification": false,
"instances": [
{
"input": "Number: 23",
"output": "```\ndef is_prime(num):\nif num <= 1:\nreturn False\nfor i in range(2, int(num**0.5) + 1):\nif num % i == 0:\nreturn False\nreturn True\n\nis_prime(23)\n```\nOutput: True"
},
{
"input": "Number: 4",
"output": "```\ndef is_prime(num):\nif num <= 1:\nreturn False\nfor i in range(2, int(num**0.5) + 1):\nif num % i == 0:\nreturn False\nreturn True\n\nis_prime(4)\n```\nOutput: False"
}
]
},
{
"id": "machine_task_2",
"instruction": "Generate a correct SQL query to retrieve all records from a specific table where a certain condition is met.",
"is_classification": false,
"instances": [
{
"input": "Table: Employees\nCondition: Department = 'Sales'",
"output": "```sql\nSELECT * FROM Employees WHERE Department = 'Sales';\n```"
},
{
"input": "Table: Orders\nCondition: OrderDate BETWEEN '2023-01-01' AND '2023-03-31'",
"output": "```sql\nSELECT * FROM Orders WHERE OrderDate BETWEEN '2023-01-01' AND '2023-03-31';\n```"
}
]
},
{
"id": "machine_task_3",
"instruction": "Identify the main theme of the provided poem and provide a brief explanation.",
"is_classification": false,
"instances": [
{
"input": "Poem: \"The Road Not Taken\" by Robert Frost\nTwo roads diverged in a yellow wood,\nAnd sorry I could not travel both\nAnd be one traveler, long I stood\nAnd looked down one as far as I could\nTo where it bent in the undergrowth;\n\nThen took the other, as just as fair,\nAnd having perhaps the better claim,\nBecause it was grassy and wanted wear;\nThough as for that the passing there\nHad worn them really about the same,\n\nAnd both that morning equally lay\nIn leaves no step had trodden black.\nOh, I kept the first for another day!\nYet knowing how way leads on to way,\nI doubted if I should ever come back.\n\nI shall be telling this with a sigh\nSomewhere ages and ages hence:\nTwo roads diverged in a wood, and I\u2014\nI took the one less traveled by,\nAnd that has made all the difference.",
"output": "Main Theme: The poem explores the theme of choices and their consequences. It reflects on the speaker's decision to take the road less traveled and how it has shaped their life journey."
},
{
"input": "Poem: \"Still I Rise\" by Maya Angelou\nYou may write me down in history\nWith your bitter, twisted lies,\nYou may trod me in the very dirt\nBut still, like dust, I'll rise.\n\nDoes my sassiness upset you?\nWhy are you beset with gloom?\n'Cause I walk like I've got oil wells\nPumping in my living room.\n\nJust like moons and like suns,\nWith the certainty of tides,\nJust like hopes springing high,\nStill I'll rise.\n\nDid you want to see me broken?\nBowed head and lowered eyes?\nShoulders falling down like teardrops.\nWeakened by my soulful cries.\n\nDoes my haughtiness offend you?\nDon't you take it awful hard\n'Cause I laugh like I've got gold mines\nDiggin' in my own back yard.\n\nYou may shoot me with your words,\nYou may cut me with your eyes,\nYou may kill me with your hatefulness,\nBut still, like air, I'll rise.",
"output": "Main Theme: The poem celebrates resilience and self-esteem in the face of adversity. It emphasizes rising above oppression and discrimination with dignity and strength."
}
]
}
]
That’s everything: Got questions about 🐫 CAMEL-AI? Join us on Discord! 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! 🤝
Check out some of our other work:
🐫 Creating Your First CAMEL Agent free Colab
Graph RAG Cookbook free Colab
🧑⚖️ Create A Hackathon Judge Committee with Workforce free Colab
🔥 3 ways to ingest data from websites with Firecrawl & CAMEL free Colab
🦥 Agentic SFT Data Generation with CAMEL and Mistral Models, Fine-Tuned with Unsloth free Colab
Thanks from everyone at 🐫 CAMEL-AI