Prompt Engineering
Prerequisites
- Large Language Models — in-context learning, emergent abilities
- GPT Architecture — autoregressive generation
🎯 Learning Objectives
- Define prompt engineering and explain why it matters for LLMs
- Distinguish zero-shot, one-shot, and few-shot prompting
- Describe Chain-of-Thought (CoT) prompting and its benefits
- Apply structured prompt templates for various NLP tasks
- Understand advanced strategies: self-consistency, ReAct, Tree-of-Thought
1. What Is Prompt Engineering?
Modern LLMs like GPT-4, Claude, and Gemini are conditioned by the text they receive as input. The quality, structure, and specificity of the prompt dramatically affect the output. Prompt engineering is essentially programming with natural language.
Why it matters:
- No training or fine-tuning required — instant use
- Same model, vastly different outputs depending on the prompt
- Enables complex reasoning, structured outputs, and domain specialization
- Cost-effective: avoids expensive model retraining
2. Zero-Shot Prompting
Example: Sentiment Classification
Classify the sentiment of this review as Positive, Negative, or Neutral.
Review: "The battery life is amazing but the screen resolution is disappointing."
Sentiment:
Expected output: Neutral (or Mixed)
When zero-shot works well:
- Common, well-defined tasks (translation, summarization, classification)
- Large, capable models (GPT-4, Claude 3)
- Clear, unambiguous instructions
Limitations: May struggle with domain-specific formats, edge cases, or tasks requiring a specific output structure.
3. Few-Shot Prompting
Example: Named Entity Extraction (3-shot)
Extract the person names from each sentence.
Sentence: "Albert Einstein developed the theory of relativity."
Names: Albert Einstein
Sentence: "Marie Curie won two Nobel Prizes."
Names: Marie Curie
Sentence: "Ada Lovelace is considered the first computer programmer."
Names: Ada Lovelace
Sentence: "Alan Turing and John von Neumann laid the foundations of computer science."
Names:
Expected output: Alan Turing, John von Neumann
Best practices for few-shot:
- Diverse examples: Cover different cases, edge cases, and output formats
- Consistent format: Use a uniform template so the pattern is learnable
- Order matters: Place the most similar examples closest to the query
- Typical k: 3–8 examples strike a good balance between quality and token cost
4. Chain-of-Thought (CoT) Prompting
Example: Math Problem with CoT
Q: A store has 45 apples. They sell 12 in the morning and
receive a shipment of 30 in the afternoon. Then they sell
18 more. How many apples remain?
A: Let's think step by step.
- Start: 45 apples
- After morning sales: 45 − 12 = 33
- After shipment: 33 + 30 = 63
- After afternoon sales: 63 − 18 = 45
The answer is 45 apples.
Why CoT works:
- Breaks complex problems into manageable sub-problems
- The model can "check" intermediate results
- Significantly improves accuracy on math, logic, and multi-step reasoning
4.1 Zero-Shot CoT
Simply append “Let’s think step by step” to the prompt. Remarkably effective with no examples needed (Kojima et al., 2022).
4.2 Few-Shot CoT
Provide examples that include the reasoning chain (not just input → output, but input → reasoning → output).
5. Prompt Templates and Structure
A well-structured prompt typically has these components:
- Role / System instruction: Set the persona and behavior (“You are an expert NLP researcher”)
- Task description: Clear, specific instruction of what to do
- Context / Background: Relevant information or documents
- Examples: Few-shot demonstrations (if needed)
- Input: The actual query or data to process
- Output format: Specify desired structure (JSON, bullet points, table, etc.)
Example: Structured Prompt Template
Role: You are a medical information assistant.
Task: Summarize the following clinical note in 3 bullet points.
Constraints: Use simple language. No medical jargon.
Output format: Markdown bullet list.
Clinical note: [INSERT NOTE HERE]
Summary:
Key principles:
- Be specific: “List 5 reasons” > “Why?”
- Use delimiters: triple quotes, XML tags, or markdown to separate sections
- Specify constraints: length, format, what to include/exclude
- Use positive instructions: say what to do, not just what not to do
6. Advanced Prompting Strategies
6.1 Self-Consistency (Wang et al., 2022)
Sample multiple reasoning paths (using temperature > 0) and take a majority vote on the final answer. More robust than a single CoT path.
- Generate N answers with CoT prompting
- Select the most frequent final answer
- Improves accuracy by 5–15% on arithmetic and logic benchmarks
6.2 ReAct (Reason + Act)
Interleave reasoning traces with actions (e.g., web search, calculator, API calls). The model reasons about what action to take, executes it, observes the result, and continues.
ReAct Trace
Thought: I need to find the population of France.
Action: Search("population of France 2024")
Observation: Approximately 68.4 million.
Thought: Now I can answer the question.
Answer: The population of France is approximately 68.4 million.
6.3 Tree-of-Thought (ToT)
Extends CoT by exploring multiple reasoning branches (like a search tree) and evaluating/backtracking. Good for planning and creative tasks where a single chain may fail.
6.4 Retrieval-Augmented Generation (RAG)
Retrieve relevant documents from an external knowledge base, inject them into the prompt as context, then generate. Reduces hallucination and keeps answers grounded in facts.
7. Common Pitfalls and Solutions
| Pitfall | Solution |
|---|---|
| Vague or ambiguous instructions | Be specific: define format, length, style |
| Model hallucinating facts | Use RAG; ask “say I don’t know if unsure” |
| Wrong output format | Provide explicit format examples in the prompt |
| Too long / unfocused answers | Set length constraints (“in 2 sentences”) |
| Ignoring parts of the prompt | Use numbered instructions; use delimiters |
| Sensitivity to prompt wording | Try multiple phrasings; use self-consistency |
8. Summary
- Prompt engineering is designing natural-language inputs to steer LLM outputs without changing model weights.
- Zero-shot: No examples; relies on the model’s pretraining knowledge.
- Few-shot: k examples in the prompt for pattern demonstration (typically k = 3–8).
- Chain-of-Thought (CoT): “Let’s think step by step” — dramatically improves reasoning.
- Structured templates: Role + Task + Context + Examples + Input + Format.
- Self-Consistency: Majority vote over multiple CoT samples.
- ReAct: Interleave Thought → Action → Observation loops.
- RAG: Retrieve → Read → Generate for grounded answers.