Prompting Cookbook#

You can also check this cookbook in colab here

TLDR#

The CAMEL Prompt module offers a powerful way to guide AI models in producing accurate, contextually relevant, and personalized outputs. This cookbook demonstrates how to use various prompt templates, create custom prompts, and leverage different prompt dictionaries for tasks ranging from role-playing to code generation, evaluation, and more. By mastering the Prompt module, you can significantly enhance your AI agents’ capabilities and tailor them to specific tasks.

Installation#

Ensure you have CAMEL AI installed in your Python environment:

[ ]:
%pip install "camel-ai==0.2.1"

🔑 Setting Up API Keys#

You’ll need to set up your API keys for OpenAI.

[4]:
import os
from getpass import getpass

# Prompt for the API key securely
openai_api_key = getpass('Enter your API key: ')
os.environ["OPENAI_API_KEY"] = openai_api_key
Enter your API key: ··········

Getting Started with Prompt Templates#

CAMEL offers a wide range of pre-defined prompt templates that you can use to quickly create specialized AI agents. Let’s start with a basic example using the TaskSpecifyAgent with the AI_SOCIETY task type.

[5]:
from camel.agents import TaskSpecifyAgent
from camel.configs import ChatGPTConfig
from camel.models import ModelFactory
from camel.types import ModelPlatformType, ModelType, TaskType

# Set up the model
model = ModelFactory.create(
    model_platform=ModelPlatformType.OPENAI,
    model_type=ModelType.GPT_4O_MINI,
    model_config_dict=ChatGPTConfig().as_dict(),
)

# Create a task specify agent
task_specify_agent = TaskSpecifyAgent(
    model=model, task_type=TaskType.AI_SOCIETY
)

# Run the agent with a task prompt
specified_task_prompt = task_specify_agent.run(
    task_prompt="Improving stage presence and performance skills",
    meta_dict=dict(
        assistant_role="Musician", user_role="Student", word_limit=100
    ),
)

print(f"Specified task prompt:\n{specified_task_prompt}\n")
Specified task prompt:
Design a personalized workshop where the Musician guides the Student through a series of dynamic exercises, including improvisation, audience engagement techniques, and movement choreography. Incorporate video feedback sessions to analyze performance style, culminating in a mini-concert where the Student showcases their enhanced stage presence and performance skills.

Creating Custom Prompts#

CAMEL also allows you to create your own custom prompts. Here’s an example of how to create and use a custom prompt template:

[6]:
from camel.agents import TaskSpecifyAgent
from camel.configs import ChatGPTConfig
from camel.models import ModelFactory
from camel.prompts import TextPrompt
from camel.types import ModelPlatformType, ModelType

# Set up the model
model = ModelFactory.create(
    model_platform=ModelPlatformType.OPENAI,
    model_type=ModelType.GPT_4O_MINI,
    model_config_dict=ChatGPTConfig().as_dict(),
)

# Create a custom prompt template
my_prompt_template = TextPrompt(
    'Here is a task: I\'m a {occupation} and I want to {task}. Help me to make this task more specific.'
)

# Create a task specify agent with the custom prompt
task_specify_agent = TaskSpecifyAgent(
    model=model, task_specify_prompt=my_prompt_template
)

# Run the agent with a task prompt
response = task_specify_agent.run(
    task_prompt="get promotion",
    meta_dict=dict(occupation="Software Engineer"),
)

print(response)
To make your task of getting a promotion more specific, consider breaking it down into actionable steps and defining clear goals. Here’s a refined version of your task:

**Task: Prepare for Promotion to Senior Software Engineer**

1. **Understand Promotion Criteria:**
   - Review the company’s promotion guidelines and criteria for a Senior Software Engineer.
   - Identify specific skills, experiences, and contributions required for the promotion.

2. **Set Clear Goals:**
   - Define a timeline for when you want to achieve the promotion (e.g., within the next 6-12 months).
   - List specific projects or responsibilities you need to take on to demonstrate your readiness.

3. **Skill Development:**
   - Identify key technical skills or certifications needed for the Senior role (e.g., advanced algorithms, system design, leadership).
   - Create a learning plan to acquire these skills through online courses, workshops, or mentorship.

4. **Increase Visibility:**
   - Volunteer for high-impact projects or cross-functional teams to showcase your skills.
   - Present your work and contributions in team meetings or company-wide forums.

5. **Seek Feedback:**
   - Schedule regular check-ins with your manager to discuss your progress and areas for improvement.
   - Ask for constructive feedback from peers and mentors to identify blind spots.

6. **Build Relationships:**
   - Network with senior engineers and leaders in your organization to gain insights and advice.
   - Participate in team-building activities or company events to strengthen relationships.

7. **Document Achievements:**
   - Keep a record of your contributions, projects, and any positive feedback received.
   - Prepare a portfolio or presentation to showcase your accomplishments when discussing your promotion.

8. **Prepare for the Promotion Discussion:**
   - Schedule a formal meeting with your manager to discuss your promotion.
   - Be ready to articulate your achievements, contributions, and readiness for the Senior role.

By following these specific steps, you can create a clear roadmap to achieve your goal of promotion.

Advanced Prompt Usage#

CAMEL provides various prompt dictionaries for different purposes. Let’s explore some advanced uses of these prompt templates:

1. Code Generation with CodePromptTemplateDict#

[7]:
from camel.prompts import CodePromptTemplateDict

# Generate programming languages
languages_prompt = CodePromptTemplateDict.GENERATE_LANGUAGES.format(num_languages=5)
print(f"Languages prompt:\n{languages_prompt}\n")

# Generate coding tasks
tasks_prompt = CodePromptTemplateDict.GENERATE_TASKS.format(num_tasks=3)
print(f"Tasks prompt:\n{tasks_prompt}\n")

# Create an AI coding assistant prompt
assistant_prompt = CodePromptTemplateDict.ASSISTANT_PROMPT.format(
    assistant_role="Python Expert",
    task_description="Implement a binary search algorithm",
)
print(f"Assistant prompt:\n{assistant_prompt}\n")
Languages prompt:
List the 5 most commonly used computer programming languages.
Be concise. No explanation required.

Tasks prompt:
List 3 diverse tasks that a programmer can assist a person working in {domain} using {language}.
Be concise. Be creative.

Assistant prompt:
Never forget you are a Computer Programmer and I am a person working in {domain}. Never flip roles! Never instruct me!
We share a common interest in collaborating to successfully complete a task.
You must help me to complete the task using {language} programming language.
Here is the task: {task}. Never forget our task!
I must instruct you based on your expertise and my needs to complete the task.

I must give you one instruction at a time.
You must write a specific solution that appropriately solves the requested instruction and explain your solutions.
You must decline my instruction honestly if you cannot perform the instruction due to physical, moral, legal reasons or your capability and explain the reasons.
Unless I say the task is completed, you should always start with:

Solution: <YOUR_SOLUTION>

<YOUR_SOLUTION> must contain {language} code and should be very specific, include detailed explanations and provide preferable implementations and examples for task-solving.
Always end <YOUR_SOLUTION> with: Next request.

2. Evaluation with EvaluationPromptTemplateDict#

[8]:
from camel.prompts import EvaluationPromptTemplateDict

# Generate evaluation questions
questions_prompt = EvaluationPromptTemplateDict.GENERATE_QUESTIONS.format(
    num_questions=5,
    field="Machine Learning",
    examples="1. What is the difference between supervised and unsupervised learning?\n2. Explain the concept of overfitting.",
)
print(f"Evaluation questions prompt:\n{questions_prompt}\n")
Evaluation questions prompt:
Generate 5 {category} diverse questions.
Here are some example questions:
1. What is the difference between supervised and unsupervised learning?
2. Explain the concept of overfitting.

Now generate 5 questions of your own. Be creative

3. Object Recognition with ObjectRecognitionPromptTemplateDict#

[9]:
from camel.prompts import ObjectRecognitionPromptTemplateDict

# Create an object recognition assistant prompt
recognition_prompt = ObjectRecognitionPromptTemplateDict.ASSISTANT_PROMPT
print(f"Object recognition prompt:\n{recognition_prompt}\n")
Object recognition prompt:
You have been assigned an object recognition task.
Your mission is to list all detected objects in following image.
Your output should always be a list of strings starting with `1.`, `2.` etc.
Do not explain yourself or output anything else.

4. Translation with TranslationPromptTemplateDict#

[10]:
from camel.prompts import TranslationPromptTemplateDict

# Create a translation assistant prompt
translation_prompt = TranslationPromptTemplateDict.ASSISTANT_PROMPT.format(target_language="Spanish")
print(f"Translation prompt:\n{translation_prompt}\n")
Translation prompt:
You are an expert English to {language} translator.
Your sole purpose is to accurately translate any text presented to you from English to {language}.
Please provide the {language} translation for the given text.
If you are presented with an empty string, simply return an empty string as the translation.
Only text in between ```TEXT``` should not be translated.
Do not provide any explanation. Just provide a translation.

Conclusion#

The CAMEL Prompt module provides a powerful and flexible way to guide AI models in producing desired outputs. By using pre-defined prompt templates, creating custom prompts, and leveraging different prompt dictionaries, you can create highly specialized AI agents tailored to your specific needs.