2.01 – Advanced Prompt Engineering | AI Course

🎯 2.01 – Advanced Prompt Engineering

📑 On this page

🔄 Quick Review: Prompt Components

📌 The Anatomy of an Effective Prompt
🎭 ROLE: "You are an expert [domain]..."
📝 CONTEXT: "I'm working on [project]..."
🎯 TASK: "Please [specific request]..."
⚠️ CONSTRAINTS: "Use [format]. Do not [restrictions]..."
📚 EXAMPLES: "Here are 2 examples: ..."

🧠 Chain-of-Thought (CoT)

📌 What is Chain-of-Thought?

Chain-of-Thought prompting encourages the model to reason step-by-step before giving a final answer. This dramatically improves performance on arithmetic, logic, and multi-step reasoning tasks.

Standard Prompt (without CoT):
Q: Roger has 5 tennis balls. He buys 2 more cans of tennis balls. Each can has 3 tennis balls. How many tennis balls does he have now?
A: 11
Chain-of-Thought Prompt:
Q: Roger has 5 tennis balls. He buys 2 more cans of tennis balls. Each can has 3 tennis balls. How many tennis balls does he have now?
A: Let's think step by step.
Roger starts with 5 balls.
2 cans of 3 balls each = 2 * 3 = 6 balls.
5 + 6 = 11.
Answer: 11
ScenarioStandard PromptCoT Improves?
Math word problems~30-40%✅ Yes (80-90%)
Logical reasoning~40-50%✅ Yes (70-80%)
Factual QA~70-80%➖ Minimal benefit
Creative writingGood➖ May over-rationalize
💡 Zero-shot CoT (Simple trick)

Just add "Let's think step by step" to the end of any prompt. This often improves reasoning without providing examples!

🌳 Tree of Thoughts (ToT)

📌 Tree of Thoughts

ToT generalizes CoT by exploring multiple reasoning paths simultaneously. Instead of one chain, the model explores branches, evaluates each, and selects the best path.

ToT Prompt Structure:
You are solving a complex problem. Follow this process:

1. Generate 3-5 possible next steps
2. Evaluate each step (score 1-10)
3. Select the best step
4. Repeat until solution is found

Problem: [Your complex problem here]

Think through multiple paths before deciding.
📌 When to use ToT vs CoT

🔄 Self-Consistency

📌 Self-Consistency

Run the same prompt multiple times (with temperature > 0) and take the majority answer. This leverages the wisdom of crowds and works especially well for factual questions.

Python Implementation:
import openai

def self_consistency(prompt, n=5, temperature=0.7):
    responses = []
    for _ in range(n):
        response = openai.ChatCompletion.create(
            model="gpt-4",
            messages=[{"role": "user", "content": prompt}],
            temperature=temperature
        )
        responses.append(response.choices[0].message.content)
    
    # Find most common answer (simplified - use majority voting)
    from collections import Counter
    return Counter(responses).most_common(1)[0][0]
💡 Accuracy Improvements with Self-Consistency:

🤖 ReAct (Reasoning + Acting)

📌 What is ReAct?

ReAct interleaves reasoning traces with actions. The model can think, then take actions (search, calculate, call APIs), then think again based on results.

ReAct Prompt Template:
You have access to these tools:
- search(query): Search the web for information
- calculate(expression): Evaluate math expressions
- finish(answer): Submit final answer

Use this format:
Thought: I need to find X
Action: search[X]
Observation: [results from search]
Thought: Based on this, I can...
Action: calculate[...]
Observation: [calculation result]
Thought: I have the answer
Action: finish[final answer]

Question: What is the current population of France divided by 2?
📌 ReAct vs CoT
AspectCoTReAct
Tool use❌ No✅ Yes
Information retrieval❌ Limited (knowledge cutoff)✅ Can search web
Action execution❌ No✅ Yes (APIs, code)
Hallucination reductionLowHigh (grounded in observations)

⚡ Prompt Optimization Techniques

📌 Temperature and Top_p Tuning
Task TypeRecommended TemperatureWhy?
Factual QA, classification0.0 - 0.2Deterministic, consistent answers
Code generation0.2 - 0.4Mostly accurate with slight variation
Creative writing, brainstorming0.7 - 1.0More diverse, creative outputs
Translation, summarization0.3 - 0.5Balance of accuracy and variety
📌 Prompt Compression

Long prompts cost more tokens. Compress while preserving meaning:

📌 Automated Prompt Engineering (APE)

Use AI to generate and evaluate prompts. Provide the LLM with examples of desired inputs and outputs, and ask it to write the most effective prompt.

System: You are a prompt engineer. Given example inputs and outputs, write a prompt that produces this behavior.

Example input: "I'm sad today"
Example output: {"sentiment": "negative", "confidence": 0.9}

Example input: "This is amazing!"
Example output: {"sentiment": "positive", "confidence": 0.95}

Write a prompt that would generate these outputs from any input.
📌 Prompt Optimization Checklist

✍️ Exercises

Exercise 2.01.1 – CoT vs Standard

Test both prompts on a logic puzzle and compare results:

"A bat and a ball cost $1.10 in total. The bat costs $1.00 more than the ball. How much does the ball cost?"

Why CoT helps:
Many people (and models) intuitively answer $0.10, which is wrong!
Let x = ball price. Bat = x + 1.00. Total = x + (x + 1.00) = 2x + 1.00 = 1.10.
2x = 0.10, x = 0.05. The ball costs $0.05, bat costs $1.05.
CoT forces step-by-step reasoning to avoid the intuitive trap.
Exercise 2.01.2 – Implement self-consistency

Write code that asks GPT-4 the same question 5 times with temperature 0.7 and takes the majority answer. What question would you test?

Sample implementation:
import openai
from collections import Counter

def majority_vote(question, n=5):
    answers = []
    for i in range(n):
        response = openai.ChatCompletion.create(
            model="gpt-4",
            messages=[{"role": "user", "content": question}],
            temperature=0.7
        )
        answers.append(response.choices[0].message.content)
    return Counter(answers).most_common(1)[0][0]
Exercise 2.01.3 – Design a ReAct prompt

Design a ReAct prompt for a customer support agent that can search a knowledge base and escalate to a human.

Sample ReAct Prompt for Support:
You are a customer support AI with these tools:
- search_kb(query): Search internal knowledge base
- escalate_ticket(issue, priority): Escalate to human agent

Thought: User asks about refund policy
Action: search_kb["refund policy"]
Observation: 30-day refund policy, restocking fee applies
Thought: I have the answer
Action: finish["Our refund policy allows returns within 30 days..."]

If confidence < 80% or issue is urgent:
Thought: This requires human review
Action: escalate_ticket["complex billing issue", priority="high"]
📌 Key Takeaways
📘 Next Module: 2.02 – RAG Deep Dive →