Prompt Engineering: Chat Templates, Few-Shot & Chain-of-Thought (CoT)
How ChatML / LLaMA-3 role special tokens serialize conversations, why Few-Shot demonstrations steer attention without weight updates, and the exact computational reason Chain-of-Thought (CoT) unlocks multi-step reasoning.
Prompt Engineering structures instructions using ChatML role templates, Few-Shot input/output demonstrations, and Chain-of-Thought (CoT) intermediate reasoning steps.
Small formatting bugs or missing role tags quietly tank accuracy, whereas 2–3 crisp few-shot examples and step-by-step reasoning unlock huge gains with zero retraining.
Prompt engineering isn't magic spells — it is conditioning the next-token probability distribution via role delimiters, few-shot attention anchors, and serial scratchpad compute!
Always render chat prompts via tokenizer.apply_chat_template(...) and keep static instructions at the TOP of the prompt so Prefix Caching saves 80% on TTFT and API costs!
Knowing when to use Few-Shot demonstrations (formatting & edge cases) vs. Chain-of-Thought (multi-step math/logic) vs. Self-Consistency (majority vote over N CoT rollouts) systematically boosts accuracy.
Great conceptual interview question: 'Why does adding "Let's think step by step" actually improve math accuracy in a Transformer with fixed weights?'
Why does placing dynamic user timestamps or per-request IDs at the VERY BEGINNING of your System Prompt hurt production latency and cost?
- Serialize multi-turn conversations into exact ChatML / LLaMA-3 special-token templates with generation prompts and stop tokens
- Explain why a mismatched chat template silently destroys benchmark accuracy on open-weights LLMs
- Understand In-Context Learning (Zero-Shot vs. Few-Shot) via Transformer Induction Heads
- Explain why Chain-of-Thought (CoT) gives a fixed-depth Transformer extra serial compute steps via intermediate KV-Cache tokens
A fixed-layer Transformer only gets 1 single pass of depth to produce its very next token — like trying to multiply 23 × 17 in your head in one blink. Chain-of-Thought (CoT) hands the Transformer a piece of scratch paper (its own output stream & KV-Cache): writing 23 × 10 = 230 and 23 × 7 = 161 lets each step become a fresh, easy lookup for the next forward pass!
1. Chat Templates & Special Role Delimiters
Toggle between ChatML and LLaMA-3 in the mini-lab below to see how exact special tokens wrap every turn — and note the trailing assistant generation prompt!
Why Exact Chat Templates Are Non-Negotiable
Base LLMs only complete raw text. Instruction-tuned LLMs were fine-tuned on a specific special-token template (e.g., <|im_start|>role\n...<|im_end|> in ChatML, or <|start_header_id|>role<|end_header_id|> in LLaMA 3):
- Never hand-concatenate
"User: ... Assistant: ..."for modern chat models — using the wrong delimiter tokens can drop benchmark accuracy by 10–30%! - Prompt Injection Defense: Because role tokens are special token IDs (not plain text), properly escaped templates prevent user text from forging a fake
<|im_start|>systemturn.
Chat Template Token Inspector
<|im_start|>system You are a helpful AI.<|im_end|> <|im_start|>user Explain RoPE briefly.<|im_end|> <|im_start|>assistant
2. Why Chain-of-Thought (CoT) Works: Tokens = Compute Depth
Compare a single direct forward pass against a 3-step Chain-of-Thought scratchpad below.
The Computational Theory of Chain-of-Thought
Every single output token executes all Transformer layers ( FLOPs) and writes its result into the KV-Cache.
- Without CoT: Answering a multi-hop problem directly gives the model constant serial depth — theoretically incapable of simulating arbitrary multi-step circuits!
- With CoT: Generating scratchpad tokens gives the Transformer sequential passes where step reads all previous steps via attention — provably elevating a constant-depth Transformer to Turing-complete serial computation!
3. Few-Shot In-Context Learning & Prompt Caching Layout
Few-shot demonstrations steer the model's induction heads with zero gradient updates — and when placed right after the System Prompt, they are 100% prefix-cached!
Production Prompt Layout Checklist (Prefix-Cache Friendly!)
- Static System Role & Rules (cached across all requests)
- Static Output Schema & 2–4 Diverse Few-Shot Examples (include 1 hard edge case!)
- Dynamic Context / RAG Snippets (changes per query)
- Current User Question (always last!)
Worked Example: Rendering a Safe Multi-Variable Prompt Template
Template: "Summarize {{topic}} in {{n}} bullets for {{audience}}." with {topic: 'RoPE', n: 3, audience: 'ML interns'}.
Extract all {{key}} tokens (topic, n, audience) and verify none are missing before sending to the LLM.
'{{topic}}' to production LLMs!Why does Chain-of-Thought (CoT) improve multi-step arithmetic and logic accuracy on a frozen LLM?
If you replace template variables sequentially (for k, v in vars: text = text.replace('{{'+k+'}}', v)), what security/correctness bug can happen?
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
No! Reasoning models were trained with Reinforcement Learning (Module 5.5) to automatically generate hidden or explicit <think>...</think> chains. Over-prompting them with rigid CoT instructions can actually hurt their performance!
Chain-of-Thought (CoT) Serial Compute Depth Stepper
See how generating intermediate reasoning tokens gives the Transformer fresh forward passes and KV-Cache scratchpad state.
Self-Consistency Decoding
Samples 5–16 independent CoT traces at T=0.7 and selects the most frequent final answer — dramatically improving reliability on hard math and logic.
Prefix-Cached Prompt Engineering
Structuring static system prompts + few-shot examples first cuts input token costs by 50%–90% on Anthropic, OpenAI, Gemini, and vLLM.
# ChatML Prompt Template Renderer with Few-Shot Chain-of-Thought (CoT) Examples
def render_chatml(system_msg: str, few_shots: list[tuple[str, str]], user_query: str) -> str:
blocks = [f"<|im_start|>system\n{system_msg}<|im_end|>"]
for q, a in few_shots:
blocks.append(f"<|im_start|>user\n{q}<|im_end|>")
blocks.append(f"<|im_start|>assistant\n{a}<|im_end|>")
blocks.append(f"<|im_start|>user\n{user_query}<|im_end|>")
blocks.append("<|im_start|>assistant\n")
return "\n".join(blocks)
prompt = render_chatml(
system_msg="Solve step by step, then end with 'Answer: <number>'.",
few_shots=[("3 packs of 4 pens minus 2?", "3 * 4 = 12 pens. 12 - 2 = 10.\nAnswer: 10")],
user_query="5 boxes of 6 apples minus 4?",
)
print(prompt)
.replace() loops?