Course
AI · Module 02: Production Prompt EngineeringTutorial 5 of 21
AI Course·~1.5 hrs

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).

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

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!

DIRECT ZERO-SHOT (1 FORWARD PASS = FIXED COMPUTE!)Prompt: "Is 9,973 prime? Answer YES/NO first."Forced to guess in 1 token → High error!Putting the verdict FIRST locks the model into RationalizationREASONING SCRATCHPAD (TEST-TIME SERIAL COMPUTE)<thinking> √9973 ≈ 99.8; check primes ≤ 97...none divide evenly → prime! </thinking>{"verdict": "YES"}Intermediate tokens act as external working RAM!
Figure: Always generate `reasoning` fields BEFORE `verdict` fields in JSON schemas (or use native Thinking models) so compute happens before commitment.

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:

PYTHON
# ❌ 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

  1. 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.
  2. 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!
  3. 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.
  4. 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:

DimensionStandard 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 HappensOnly if you prompt for <thinking> or a reasoning JSON fieldTrained via RL to emit hidden/explicit thinking tokens automatically before answering
Typical Latency (TTFT)200 ms – 800 ms2 s – 30 s+ (proportional to thinking budget)
Prompting StyleExplicit step-by-step decomposition + 3–5 few-shot examples help hugelyGoal + Constraints + Context only! Over-prescribing "Think step 1, step 2..." can actually degrade native RL search
Best Production FitLow-latency chat, UI autocomplete, simple extraction, high-QPS routingComplex 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:

Tracing Standard Model vs. Tunable Thinking Budget
Interactive LLM Pipeline Tracer · Step 1 of 3 (1. Verdict-First Standard Call Misses DST Transition)
Wire Telemetry:in=85 tokout=18 toklatency=340mscost=$0.00004
1→# Complex constraint problem (timezone + DST + SLA window)
2→task = "Incident opened Nov 1 01:30 EDT; 4h business SLA..."
3→# Attempt 1: Fast non-thinking call (verdict-first)
4→fast = call_standard_model(task)
5# Attempt 2: Reasoning model with reasoning_effort="medium"
6deep = call_reasoning_model(task, effort="medium")
Fast Direct OutputSUBTLE BUG!
{"breach_time": "05:30 EST"}  // Missed Nov 1 02:00 AM Daylight Saving fallback hour!
What's Happening: Jumping straight to the timestamp in 18 tokens skipped checking whether Nov 1 crossed a DST clock rollback and weekend business-hours pause.

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:

SDK:
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)

  1. Using a Reasoning Model for Simple Intent Routing (3,500 ms Latency Spike): Turning on high reasoning effort just to classify "Hi, where is my invoice?" into BILLING wastes 800 thinking tokens and adds 3 seconds of 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.
  2. 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).
  3. 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

Q1.Why does placing `reasoning: str` BEFORE `is_fraud: bool` inside a structured JSON schema dramatically improve classification accuracy?
Q2.How are internal 'thinking / reasoning tokens' billed by providers like OpenAI, Google Gemini, and Anthropic?
Q3.When prompting a native Reasoning Model (`o3`, `o4-mini`, Claude Extended Thinking), which prompt anti-pattern should you AVOID?
Q4.What is the biggest flaw in providing 5 few-shot examples where all 5 resolve to `'APPROVED'`?

Keep Exploring: Related Lessons & Tools

All Courses →