2.2 Few-Shot Prompting, Chain-of-Thought & Reasoning Models
Understand why Transformers cannot do multi-hop math in a single token: master Few-Shot calibration, the 'Reason-Before-Verdict' schema rule, and native Reasoning Models (o3, Gemini Thinking, Claude Extended Thinking).
1. Why Transformers Need "Scratchpad Tokens" to Think
Here is one of the deepest insights in all of AI Engineering: a Transformer spends a fixed, constant amount of serial compute per generated token (for example, 80 matrix layers from bottom to top).
Whether you ask "What is 2 + 2?" or "Does this 40-line concurrent Python lock deadlock under thread contention? Answer YES or NO only", forcing the model to answer on Token #1 gives it the exact same 80-layer forward pass to solve both!
When you allow the model to emit intermediate reasoning tokens (Chain-of-Thought) before stating its final answer, each generated token is fed back into the context window and attended over by all 80 layers on the next step — effectively turning generated tokens into external working RAM and serial test-time compute!
The Golden Schema Rule: reasoning MUST Come BEFORE verdict!
Look closely at these two JSON schemas for an automated PR security classifier. They contain the exact same fields, yet Schema B beats Schema A by 15%–30% accuracy on hard bugs:
# ❌ SCHEMA A: Verdict FIRST -> Forces a 1-token gut guess, then rationalizes the mistake!
class BadReview(BaseModel):
has_sql_injection: bool
step_by_step_analysis: str
# ✅ SCHEMA B: Reasoning FIRST -> Computes trace in working memory BEFORE committing to bool!
class GoodReview(BaseModel):
step_by_step_analysis: str
has_sql_injection: bool
Because autoregressive decoding generates tokens strictly left-to-right, putting has_sql_injection first forces the model to lock in true or false on token #5 before step_by_step_analysis is even computed!
2. Few-Shot Prompting: Showing Beats Telling
Whenever you need a subtle domain tone, bespoke classification boundary, or non-standard data mapping, 3 carefully chosen input -> output examples outperform 500 words of abstract rules.
4 Rules for High-Signal Few-Shot Examples
- Pick Boundary / Edge Cases, Not Easy Toy Cases: If your classifier confuses
"billing_refund"with"subscription_cancel", include 1 borderline example of each showing the exact distinction. - Include the Abstention / Negative Case: Always include 1 example where the right output is
[]or"INSUFFICIENT_DATA"— otherwise few-shot examples bias the model toward always finding something! - Vary Label Order & Surface Structure: Never make all 4 few-shot examples resolve to
"APPROVE"(recency/majority label bias will skew real predictions toward"APPROVE"!). Balance labels evenly. - Match Exact Production Formatting: If production inputs arrive wrapped in
<log_line>...</log_line>and output raw JSON, every few-shot example must use that exact wrapper and exact JSON format.
3. Standard Chat Models vs. Native Reasoning ("Thinking") Models
In 2025–2026, LLM architectures split into two distinct families that require different prompting styles:
| Dimension | Standard Instruction Models (GPT-4o, Gemini Flash, Claude Haiku/Sonnet) | Native Reasoning / Thinking Models (OpenAI o3/o4-mini, Gemini 2.5 Thinking, Claude Extended Thinking) |
|---|---|---|
| How Reasoning Happens | Only if you prompt for <thinking> or a reasoning JSON field | Trained via RL to emit hidden/explicit thinking tokens automatically before answering |
Typical Latency (TTFT) | 200 ms – 800 ms | 2 s – 30 s+ (proportional to thinking budget) |
| Prompting Style | Explicit step-by-step decomposition + 3–5 few-shot examples help hugely | Goal + Constraints + Context only! Over-prescribing "Think step 1, step 2..." can actually degrade native RL search |
| Best Production Fit | Low-latency chat, UI autocomplete, simple extraction, high-QPS routing | Complex debugging, SQL/code synthesis, legal/financial multi-doc audits, architecture planning |
4. Interactive Trace: Controlling Reasoning Effort & Token Budgets
Click Next to see how native Thinking budgets trade latency and tokens for dramatic accuracy gains on multi-hop logic:
{"breach_time": "05:30 EST"} // Missed Nov 1 02:00 AM Daylight Saving fallback hour!5. Production SDK Code: Tuning Thinking Budgets Across OpenAI, Gemini & Claude
Modern SDKs let you dial reasoning compute up or down per request (low / medium / high or exact thinking_budget tokens) so you only pay for deep thinking when the task needs it:
from openai import OpenAI
client = OpenAI()
# OpenAI o-series / GPT-5 reasoning: dial effort ("low" | "medium" | "high")
resp = client.responses.create(
model="o4-mini",
reasoning={"effort": "medium"},
max_output_tokens=4096, # Covers BOTH reasoning tokens + visible answer!
input=(
"Find the subtle concurrency race condition in this async cache helper:
"
"async def get_user(uid):
"
" if uid not in CACHE:
"
" CACHE[uid] = await db.fetch(uid)
"
" return CACHE[uid]"
),
)
print(resp.output_text)
print("Reasoning tokens used:", resp.usage.output_tokens_details.reasoning_tokens)6. What Breaks in Production (War Stories)
- Using a Reasoning Model for Simple Intent Routing (
3,500 msLatency Spike): Turning onhighreasoning effort just to classify"Hi, where is my invoice?"intoBILLINGwastes800thinking tokens and adds3 secondsof silence before your UI responds! Use a fast non-thinking Flash/Mini model (thinking_budget=0,temperature=0) for simple routing, and escalate only hard steps to reasoning models. - Showing Raw
<thinking>Monologues Directly to Non-Technical Customers: Internal reasoning traces contain half-formed hypotheses and internal policy names. Strip<thinking>...</thinking>tags on the server (or use native reasoning blocks) and render only the clean final answer (or a collapsed "Thought for 2s" indicator). - Biased Few-Shot Ordering: Putting 4 positive examples followed by 0 negative examples causes recency bias in small models, inflating false positives by
20%+. Keep few-shot sets compact (3–5 diverse examples) and include tricky negative cases.
Module 2.2 Mastery Check — Few-Shot, CoT & Reasoning Models
Keep Exploring: Related Lessons & Tools
All Courses →Validate, prettify, minify, sort keys, explore interactive collapsible JSON trees, and generate TypeScript interfaces instantly.
Compute MD5, SHA-1, SHA-256, SHA-384, and SHA-512 hashes or keyed HMAC signatures directly in your browser using Web Crypto.