We use cookies to enhance your experience on the site
CodeWorlds

Prompt Engineering - The Art of Prompts

Prompt Engineering is the skill of writing effective instructions for AI!

Basic Principles

1. Be Specific

1# ❌ Bad
2"Write something about animals"
3
4# ✅ Good
5"Write 3 paragraphs about the hunting behaviors of African lions,
6focusing on pack cooperation."

2. Provide Context

1# ❌ Bad
2"How do I fix this?"
3
4# ✅ Good
5"I'm a junior Python developer. My FastAPI code returns a 422
6error on a POST request. Here's the code: [code]. How do I fix it?"

3. Specify the Format

1prompt = """
2Analyze the text and return the result in JSON format:
3{
4    "species": "species name",
5    "habitat": "where it lives",
6    "diet": "what it eats",
7    "threats": ["list of threats"]
8}
9
10Text: The African lion lives on the savannas...
11"""

Prompting Techniques

Few-shot Prompting

1# Provide examples so the model understands the pattern
2prompt = """
3Classify the animals:
4
5Example 1:
6Animal: Lion
7Classification: Predator
8
9Example 2:
10Animal: Zebra
11Classification: Herbivore
12
13Animal: Elephant
14Classification:
15"""

Chain of Thought (CoT)

1# Ask the model to "think step by step"
2prompt = """
3Solve the problem step by step:
4
5Problem: There are 15 lions and 23 elephants on a Safari.
6Each day 2 lions arrive and 1 elephant leaves.
7How many animals will there be after 5 days?
8
9Solution:
10Step 1: Count the initial number of animals...
11"""

Role Prompting

1# Assign a role to the model
2system_prompt = """
3You are an experienced Safari guide with 20 years of experience.
4You respond enthusiastically, sharing anecdotes from the field.
5You always prioritize tourist safety.
6"""

Prompt Templates

1from string import Template
2
3# Template with placeholders
4template = Template("""
5As an expert in $field, analyze the following $data_type:
6
7$data
8
9Return the analysis in this format:
101. Key observations
112. Potential issues
123. Recommendations
13""")
14
15prompt = template.substitute(
16    field="Safari ecology",
17    data_type="population report",
18    data="Lions: 45, Elephants: 120, Giraffes: 78"
19)

Best Practices

1# 1. Iterate and test prompts
2# 2. Use separators for clarity
3prompt = """
4### Instructions ###
5Analyze the code below.
6
7### Code ###
8\`\`\`python
9def calculate(): pass
10\`\`\`
11
12### Requirements ###
13- Find bugs
14- Suggest fixes
15"""
16
17# 3. Specify what NOT to do
18"Respond briefly, without preambles like 'Of course, here is...'"
19
20# 4. Test different temperatures
21# - temperature=0 for code and facts
22# - temperature=0.7 for creativity
Go to CodeWorlds