TAI BUI
Back to curriculum
BuildPython

Few-Shot, Chain-of-Thought, Tree-of-Thought

Telling a model what to do is prompting. Showing it how to think is engineering. The gap between 78% and 91% accuracy on the same model, same task, same data comes from the reasoning strategy, not from a better model.

TIME: ~45 minutesPREREQUISITES: Lesson 11.01 (Prompt Engineering)

Learning Objectives

  • Implement few-shot prompting by selecting and formatting example demonstrations that maximize task accuracy
  • Apply chain-of-thought (CoT) reasoning to improve accuracy on multi-step problems like math word problems
  • Build a tree-of-thought prompt that explores multiple reasoning paths and selects the best one
  • Measure the accuracy improvement from zero-shot vs few-shot vs CoT on a standard benchmark
  • Combine self-consistency voting with an escalation rule that spends extra API calls only when the vote is split

The Problem

You build a math tutoring app. Your prompt says: "Solve this word problem." GPT-5 gets 94% of GSM8K, the standard grade-school math benchmark. That looks like a ceiling, but chain-of-thought still adds 3-4 points on the same model (97% zero-shot CoT, 98% few-shot CoT, in the table below).

The older numbers show the effect more sharply. On GPT-4o, adding five words ("Let's think step by step") moves GSM8K from 78% to 91%, and a few worked examples bring it to 95%. Same model, same temperature, a few extra tokens. The only difference is that you gave the model scratch paper.

This is not a hack. Humans do not solve multi-step problems in one mental leap, and neither do transformers. When you force a model to generate intermediate tokens, those tokens become context for the next token, so each reasoning step feeds the next. The model computes its way to the answer.

"Think step by step" is where this starts, not where it ends. What if you sampled five reasoning paths and took a majority vote? What if you let the model explore a tree of possibilities, evaluating and pruning branches? What if you interleaved reasoning with tool use? These are published techniques with measured improvements, and you will build all of them in this lesson.

Warm-up0/3
1. You sample the same prompt from a language model five times. Which setting makes the five outputs most likely to differ?Warm-up
A box labelled same prompt, unchanged each run, with an arrow to five dashed output slots labelled run 1 to run 5, each marked output question mark.
Setup only: the outputs are the unknown.
2. What limits how many example input-output pairs you can put into a single LLM request?Warm-up
A request box holding three example input to output rows, an ellipsis and a final row your input to question mark, with an arrow to a dashed response slot.
Setup only.
3. You rewrite a prompt and want to know whether it is really better. What is the sound way to check?Warm-up
Two boxes, old prompt and new prompt, with the word better and a question mark between them, and a dashed slot labelled evidence below each.
Setup only.

The Concept

Zero-Shot vs Few-Shot: When Examples Beat Instructions

Zero-shot prompting gives the model a task and nothing else. Few-shot prompting gives it examples first.

Wei et al. (2022) measured this across 8 benchmarks. For simple tasks like sentiment classification, zero-shot and few-shot performed within 2% of each other. For complex tasks like multi-step arithmetic and symbolic reasoning, few-shot improved accuracy by 10-25%.

The intuition: examples are compressed instructions. Instead of describing the output format, you show it. Instead of explaining the reasoning process, you demonstrate it. The model pattern-matches on the examples more reliably than it interprets abstract instructions.

Mermaid diagram

When few-shot wins: format-sensitive tasks, classification, structured extraction, domain-specific jargon, any task where the model needs to match a specific pattern.

When zero-shot wins: simple factual questions, creative tasks where examples constrain creativity, tasks where finding good examples is harder than writing good instructions.

Example Selection: Similar Beats Random

Not all examples are equal. Choosing examples similar to the target input outperforms random selection by 5-15% on classification tasks (Liu et al., 2022). Three principles:

  1. Semantic similarity: pick examples closest to the input in embedding space
  2. Label diversity: cover all output categories in your examples
  3. Difficulty matching: match the complexity level of the target problem

The best number of examples for most tasks is 3-5. With fewer than 3, the model may not get enough signal to extract the pattern. Past 5, returns diminish and you spend context window tokens for little gain. For classification with many labels, use one example per label.

Chain-of-Thought: Giving Models Scratch Paper

Chain-of-Thought (CoT) prompting was introduced by Wei et al. (2022) at Google Brain. The idea is simple: instead of asking the model for just the answer, ask it to show its reasoning steps first.

Mermaid diagram

Why does this work mechanically? Each token a transformer generates becomes context for the next token. Without CoT, the model must compress all reasoning into the hidden state of a single forward pass. With CoT, the model externalizes intermediate computations as tokens. Each reasoning token extends the effective computation depth.

GSM8K benchmarks (grade-school math, 8.5K problems):

ModelZero-ShotZero-Shot CoTFew-Shot CoT
GPT-4o78%91%95%
GPT-594%97%98%
o4-mini (reasoning)97%N/AN/A
Claude Opus 4.793%97%98%
Gemini 3 Pro92%96%98%
Llama 4 70B80%89%94%
DeepSeek-V3.189%94%96%

Note on reasoning models. Models like OpenAI's o-series (o3, o4-mini) and DeepSeek-R1 run chain-of-thought internally before emitting their answer. Adding "Let's think step by step" to a reasoning model is redundant and sometimes counterproductive, since they have already done it.

Two flavors of CoT:

Zero-shot CoT: append "Let's think step by step" to the prompt. No examples needed. Kojima et al. (2022) showed this single sentence improves accuracy across arithmetic, commonsense, and symbolic reasoning tasks.

Few-shot CoT: provide examples that include reasoning steps. More effective than zero-shot CoT because the model sees the exact reasoning format you expect.

When CoT hurts: simple factual recall ("What is the capital of France?"), single-step classification, tasks where speed matters more than accuracy. CoT adds 50-200 tokens of reasoning overhead per query. For high-throughput, low-complexity tasks, that is wasted cost.

Self-Consistency: Sample Many, Vote Once

Wang et al. (2023) introduced self-consistency. The insight: a single CoT path might contain reasoning errors. But if you sample N independent reasoning paths (using temperature > 0) and take the majority vote on the final answer, errors tend to cancel out.

Mermaid diagram

Self-consistency improved GSM8K accuracy from 56.5% (single CoT) to 74.4% with N=40 on the original PaLM 540B experiments. On GPT-5 the improvement is small (97% to 98%) because base accuracy is already saturated. The technique shines most on models with 60-85% base CoT accuracy, the sweet spot where single-path errors are frequent but not systematic. For reasoning models (o-series, R1) self-consistency is subsumed by the built-in internal sampling.

The tradeoff: N samples means Nx the API cost and latency. In practice, N=5 often captures most of the benefit. N=3 is the minimum for a meaningful vote. N > 10 has diminishing returns for most tasks.

Tree-of-Thought: Branching Exploration

Yao et al. (2023) introduced Tree-of-Thought (ToT). Where CoT follows one linear reasoning path, ToT explores multiple branches and evaluates which are most promising before continuing.

Mermaid diagram

ToT has three components:

  1. Thought generation: produce multiple candidate next-steps
  2. State evaluation: score each candidate (can use the LLM itself as evaluator)
  3. Search algorithm: BFS or DFS through the tree, pruning low-scoring branches

On the Game of 24 task (combine 4 numbers using arithmetic to make 24), GPT-4 with standard prompting solves 7.3% of problems. With CoT, 4.0% (CoT actually hurts here because the search space is wide). With ToT, 74%.

ToT is expensive. Each node in the tree requires an LLM call. A tree with branching factor 3 and depth 3 requires up to 39 LLM calls. Use it only for problems where the search space is large but evaluatable: planning, puzzle solving, creative problem-solving with constraints.

ReAct: Thinking + Doing

Yao et al. (2022) combined reasoning traces with actions. The model alternates between thinking (generating reasoning) and acting (calling tools, searching, computing).

Mermaid diagram

ReAct outperforms pure CoT on knowledge-intensive tasks because it can ground its reasoning in real data. On HotpotQA (multi-hop question answering), ReAct with GPT-4 achieves 35.1% exact match vs 29.4% for CoT alone. The real power is that reasoning errors get corrected by observations, so the model can update its plan mid-execution.

ReAct is the foundation of modern AI agents. Agent frameworks like LangChain, CrewAI, and AutoGen implement a variant of the Thought-Action-Observation loop. You will build full agents in Phase 14. This lesson covers the prompting pattern.

Structured Prompting: XML Tags, Delimiters, Headers

As prompts get complex, structure prevents the model from confusing sections. Three approaches:

XML tags (works best with Claude, solid everywhere):

<context>
You are reviewing a pull request.
The codebase uses TypeScript and React.
</context>

<task>
Review the following diff for bugs, security issues, and style violations.
</task>

<diff>
{diff_content}
</diff>

<output_format>
List each issue with: file, line, severity (critical/warning/info), description.
</output_format>

Markdown headers (universal):

Check: The Concept0/30
1. What is the key difference between zero-shot and few-shot prompting?Define
Two prompt cards for a sentiment task. The zero-shot card has an instruction, a review and an empty sentiment line. The few-shot card has the same instruction, two labelled reviews, then the same review and an empty sentiment line.
Typed illustration.
2. What does chain-of-thought prompting do?Define
A prompt card with the robe question from the lesson ending in A colon Let's think step by step, an arrow down to a dashed slot labelled model reply.
Question text from the lesson's code.
3. What does self-consistency (Wang et al.) do to improve chain-of-thought accuracy?Define
A row of five boxes, step 1 to step 4 and answer, with step 3 dashed and marked may contain an error. Below it a bar for a single path at 56.5 percent on GSM8K with PaLM 540B, and a dashed slot for the accuracy with self-consistency.
Figures are from the lesson.
4. What is Tree-of-Thought prompting?Define
A card describing the Game of 24 task, and four rows of Tree-of-Thought figures: GPT-4 solves 74 percent, 10 to 40 plus API calls, 10 to 40 times token cost, high complexity.
Figures from the lesson's comparison table.
5. What is ReAct?Define
Two horizontal bars for exact match on HotpotQA with GPT-4: chain-of-thought alone 29.4 percent and ReAct 35.1 percent.
Figures from the lesson.
6. What is prompt chaining?Define
A card with Natalia's clips problem and three unconnected chips naming jobs: extract the facts, solve step by step, verify the answer. A question asks how the jobs are arranged across prompts.
Problem and job names come from the lesson's code.
7. What is zero-shot CoT?Define
Three horizontal bars for GPT-4o on GSM8K: Zero-Shot 78 percent, Zero-Shot CoT 91 percent, Few-Shot CoT 95 percent.
Figures from the lesson.
8. Which structured-prompting approach is described as working best with Claude while staying solid across models generally?Define
Four stacked sections of a code-review prompt: context, task, diff and output format, each with a dashed question-mark slot where the section marker would go.
Section texts follow the lesson's example.
9. How does Tree-of-Thought differ from Chain-of-Thought?Explain
A two-row table: Few-Shot CoT with 1 API call and 300 to 600 tokens of overhead, and Tree-of-Thought with 10 to 40 plus calls and 10 to 40 times token cost.
Figures from the lesson.
10. Why does the lesson recommend 3-5 examples for most few-shot tasks instead of as many as fit?Explain
Two bars. The first, labelled 3-5 examples, is partly filled with four blue blocks. The second, labelled as many as fit, is filled edge to edge with eleven blue blocks.
Schematic: block counts are drawn for contrast, not measured.
11. Why does CoT prompting improve accuracy even though the model has the same knowledge with or without it?Explain
Two rows of token boxes. Top: question tokens then answer, 78 percent. Bottom: question tokens, step tokens, then answer, with 91 percent stated underneath, and a question asking why the same knowledge scores higher.
Figures from the lesson (zero-shot vs zero-shot CoT).
12. How does ReAct differ from pure chain-of-thought?Explain
A two-row table: Few-Shot CoT best for maximum single-call accuracy with 1 API call, and ReAct best for knowledge-grounded reasoning with 3 to 10 plus calls.
Rows from the lesson.
13. Why is adding "Let's think step by step" to a model like o4-mini or DeepSeek-R1 often unhelpful?Explain
A prompt card with a math word problem and the line A colon Let's think step by step, an arrow to a box labelled o4-mini, and an arrow to a dashed slot labelled effect.
Setup only.
14. Why can worked examples beat a written description of the output you want?Explain
Two cards. The first describes the format in words: reply with a JSON object with the keys name and age. The second shows one input line and its JSON output.
Typed illustration.
15. Which task is the best candidate for zero-shot rather than few-shot prompting?Explain
Two prompt layouts. Left: an instruction followed by the new input. Right: an instruction, two example input to output lines, then the new input.
Schematic.
16. A ticket classifier has 6 labels. Which example set follows the lesson's selection principles?Explain
Six label chips above a pool of labeled tickets with an arrow to a dashed slot labelled examples, then an arrow to a box for the incoming ticket.
Setup only.
17. Why does self-consistency add little on GPT-5 compared with its large gain on PaLM 540B?Explain
Two horizontal bars of accuracy gain from self-consistency: PaLM 540B with N=40 gains 17.9 points and GPT-5 gains 1 point.
Gains computed from the lesson's figures.
18. Why is few-shot CoT usually more effective than zero-shot CoT?Explain
Paired bars of GSM8K accuracy for zero-shot CoT and few-shot CoT: GPT-5 97 and 98, GPT-4o 91 and 95, Llama 4 70B 89 and 94 percent. The bars start at 80 percent.
Figures from the lesson's table.
19. Which is one reason a prompt chain can be cheaper than a single large prompt?Explain
Two panels. Left: one large prompt that does every step of the job in a single call, with a dashed cost slot. Right: a chain of prompt 1, prompt 2 and prompt 3 with a dashed cost slot.
Setup only.
20. A tree-of-thought search has branching factor 3 and depth 3, with one LLM call per node. What is the maximum number of calls?Apply
A tree: a problem node with three children, the first child expanded into three nodes and the first of those into three more, with ellipses for the unexpanded branches. A dashed slot asks for the number of calls.
Schematic: only the first branch is expanded, the rest is implied.
21. On the GSM8K table, how many points does few-shot CoT add over plain zero-shot for Llama 4 70B?Apply
One table row for Llama 4 70B on GSM8K: Zero-Shot 80 percent, Zero-Shot CoT 89 percent, Few-Shot CoT 94 percent.
Row from the lesson's table.
22. On Game of 24, GPT-4 solves 7.3% with standard prompting and only 4.0% with CoT, while ToT reaches 74%. What explains CoT doing worse?Analyze
Three bars of problems solved by GPT-4 on Game of 24: standard prompting 7.3 percent, chain-of-thought 4.0 percent, tree-of-thought 74 percent.
Figures from the question and the lesson.
23. A high-throughput service labels reviews as positive or negative. After adding "Let's think step by step", cost and latency rise and accuracy is unchanged. Why?Analyze
Two prompt cards for a review labeler, before and after adding the line Let's think step by step, and underneath: cost up, latency up, accuracy unchanged.
Typed illustration; the changes are those stated in the question.
24. A model scores 97% with one CoT call, and a team proposes self-consistency at N=5 for a bulk, low-stakes job. What is the right assessment?Analyze
Two cards. Today: one chain-of-thought call at 97 percent accuracy. Proposal: self-consistency with N=5, accuracy unknown, with a dashed slot for extra cost and latency.
Setup restated from the question.
25. A single large prompt extracts invoice fields, validates totals, and drafts a customer reply. Totals are sometimes wrong and you cannot tell which stage failed. What does splitting it into a prompt chain give you?Analyze
A single prompt card listing extract invoice fields, validate totals and draft customer reply, an arrow to one output card saying reply draft, total sometimes wrong, and a dashed question asking which stage produced the bad total.
Setup restated from the question.
26. You must tag 50,000 tickets a day across 12 categories in a strict output format, as cheaply as possible. Which design fits?Design
Four requirement rows: 50,000 tickets per day, 12 categories, strict output format, as cheap as possible, and a dashed slot labelled design.
Requirements restated from the question.
27. A tutoring app runs on a model with about 75% single-path CoT accuracy. It must be right on exam-grade problems and can pay for extra calls. Which approach fits?Design
A scale from 0 to 100 percent with a marker at 75 percent for the model's single-path chain-of-thought accuracy, a note that exam-grade problems must be right and extra calls are affordable, and a dashed slot labelled approach.
Setup restated from the question.
28. You must plan a week of deliveries under constraints, and partial plans can be checked for feasibility. Which technique fits?Design
Seven day boxes Monday to Sunday: the first three marked set, the other four dashed with question marks. A note says a partly built plan can be checked for feasibility, and a dashed slot is labelled technique.
Schematic: the question gives no deliveries or constraints.
29. An assistant must answer questions that need current facts from a search API, and it should revise its plan when results disagree. Which pattern fits?Design
Boxes for the user question, the assistant and a search API, two result strips where result 2 disagrees with result 1, and a dashed slot asking for the pattern that revises the plan.
Setup restated from the question.
30. You move a math job from GPT-4o to o4-mini. How should you adjust the prompting pipeline?Design
A box for GPT-4o with an arrow to a box for o4-mini, a reasoning model, and a dashed slot labelled changes to the prompting pipeline.
Setup restated from the question.

Role

Senior security engineer at a fintech company.

Task

Analyze this API endpoint for vulnerabilities.

Input

{api_code}

Rules

  • Focus on OWASP Top 10
  • Rate each finding: critical, high, medium, low
  • Include remediation steps

**Delimiters** (minimal but effective):

---INPUT--- {user_text} ---END INPUT---

---INSTRUCTIONS--- Summarize the above in 3 bullet points. ---END INSTRUCTIONS---


### Prompt Chaining: Sequential Decomposition

Some tasks are too complex for a single prompt. Prompt chaining breaks them into steps, where the output of one prompt becomes the input of the next.

![Mermaid diagram](/curriculum-assets/11-llm-engineering/02-few-shot-cot/mermaid-diagram-216.svg)

Chaining beats single-prompt for three reasons:

1. **Each step is simpler**: the model handles one focused task instead of juggling everything
2. **Intermediate outputs are inspectable**: you can validate and correct between steps
3. **Different steps can use different models**: use a cheap model for extraction, an expensive one for reasoning

### Performance Comparison

| Technique | Best For | GSM8K Accuracy (GPT-5) | API Calls | Token Overhead | Complexity |
|-----------|----------|------------------------|-----------|----------------|------------|
| Zero-Shot | Simple tasks | 94% | 1 | None | Trivial |
| Few-Shot | Format matching | 96% | 1 | 200-500 tokens | Low |
| Zero-Shot CoT | Quick reasoning boost | 97% | 1 | 50-200 tokens | Trivial |
| Few-Shot CoT | Maximum single-call accuracy | 98% | 1 | 300-600 tokens | Low |
| Self-Consistency (N=5) | High-stakes reasoning | 98.5% | 5 | 5x token cost | Medium |
| Reasoning model (o4-mini) | Drop-in CoT replacement | 97% | 1 | hidden (2-10x internal) | Trivial |
| Tree-of-Thought | Search/planning problems | N/A (74% on Game of 24) | 10-40+ | 10-40x token cost | High |
| ReAct | Knowledge-grounded reasoning | N/A (35.1% on HotpotQA) | 3-10+ | Variable | High |
| Prompt Chaining | Complex multi-step tasks | 96% (pipeline) | 2-5 | 2-5x token cost | Medium |

The right technique depends on three factors: accuracy requirement, latency budget, and cost tolerance. For most production systems, few-shot CoT with a 3-sample self-consistency fallback covers 90% of use cases.

Build It

We will build a math problem solver that combines few-shot prompting, chain-of-thought reasoning, and self-consistency voting into a single pipeline. Then we will add tree-of-thought for hard problems.

The full implementation is in code/advanced_prompting.py. Here are the key components.

Step 1: Few-Shot Example Store

The first component manages few-shot examples and selects the most relevant ones for a given problem.

python
GSM8K_EXAMPLES = [
    {
        "question": "Janet's ducks lay 16 eggs per day. She eats three for breakfast every morning and bakes muffins for her friends every day with four. She sells every remaining egg at the farmers' market for $2. How much does she make every day at the farmers' market?",
        "reasoning": "Janet's ducks lay 16 eggs per day. She eats 3 and bakes with 4, using 3 + 4 = 7 eggs. So she has 16 - 7 = 9 eggs left. She sells each for $2, so she makes 9 * 2 = $18 per day.",
        "answer": "18"
    },
    ...
]

Each example has three parts: the question, the reasoning chain, and the final answer. The reasoning chain is what transforms a regular few-shot example into a CoT few-shot example.

Step 2: Chain-of-Thought Prompt Builder

The prompt builder assembles a system message, few-shot examples with reasoning chains, and the target question into a single prompt.

python
def build_cot_prompt(question, examples, num_examples=3):
    system = (
        "You are a precise math problem solver. "
        "For each problem, show your step-by-step reasoning clearly. "
        "After your reasoning, state your final answer on the last line "
        "in exactly this format: 'The answer is [number]'."
    )
 
    example_text = ""
    for ex in examples[:num_examples]:
        example_text += f"Q: {ex['question']}\n"
        example_text += f"A: {ex['reasoning']} The answer is {ex['answer']}.\n\n"
 
    user = f"{example_text}Q: {question}\nA:"
    return system, user

The format constraint ("The answer is [number]") matters. Without it, pulling out answers to compare across samples gets unreliable.

Step 3: Self-Consistency Voting

Sample N reasoning paths and take the majority answer.

python
def self_consistency_solve(question, examples, client, model, n_samples=5):
    system, user = build_cot_prompt(question, examples)
 
    answers = []
    reasonings = []
    for _ in range(n_samples):
        text = call_llm(client, model, system, user, temperature=0.7)
        reasonings.append(text)
        answer = extract_answer(text)
        if answer is not None:
            answers.append(answer)
 
    if not answers:
        return None, 0.0, reasonings, Counter()
 
    vote_counts = Counter(answers)
    best_answer = vote_counts.most_common(1)[0][0]
    confidence = vote_counts[best_answer] / len(answers)
 
    return best_answer, confidence, reasonings, vote_counts

Temperature 0.7 is important. At temperature 0.0, all N samples would come out near-identical, defeating the purpose. You need enough randomness for diverse reasoning paths but not so much that the model produces gibberish.

Step 4: Tree-of-Thought Solver

For problems where linear reasoning fails, ToT explores multiple approaches and evaluates which direction is most promising.

python
def tree_of_thought_solve(question, client, model, breadth=3, depth=3):
    thoughts = generate_initial_thoughts(question, client, model, breadth)
    scored = [(t, evaluate_thought(t, question, client, model)) for t in thoughts]
    scored.sort(key=lambda x: x[1], reverse=True)
 
    for current_depth in range(1, depth):
        next_thoughts = []
        top_k = min(2, len(scored))
        for thought, score in scored[:top_k]:
            extensions = extend_thought(thought, question, client, model, breadth)
            for ext in extensions:
                ext_score = evaluate_thought(ext, question, client, model)
                next_thoughts.append((ext, ext_score))
        if next_thoughts:
            scored = sorted(next_thoughts, key=lambda x: x[1], reverse=True)
 
    best_thought = scored[0][0] if scored else ""
    return extract_answer(best_thought), best_thought

The evaluator is itself an LLM call. You ask the model: "On a scale of 0.0 to 1.0, how promising is this reasoning path for solving the problem?" This is the key insight of ToT: the model evaluates its own partial solutions.

Step 5: Full Pipeline

The pipeline combines all techniques with an escalation strategy.

python
def solve_with_escalation(question, examples, client, model):
    system, user = build_cot_prompt(question, examples)
    single_response = call_llm(client, model, system, user, temperature=0.0)
    single_answer = extract_answer(single_response)
 
    sc_answer, confidence, _, _ = self_consistency_solve(
        question, examples, client, model, n_samples=5
    )
 
    if confidence >= 0.8:
        return sc_answer, "self_consistency", confidence
 
    tot_answer, _ = tree_of_thought_solve(question, client, model)
    return tot_answer, "tree_of_thought", None

The escalation logic: run the 5-sample vote, and if self-consistency confidence is below 0.8 (fewer than 4 of 5 samples agree), escalate to ToT. Easy problems stop at the vote, and hard ones get more compute.

Check: Build It0/11
1. Why does the prompt builder require a final line of the form 'The answer is [number]'?Explain
Six lines of the system message from build_cot_prompt. The last three lines, the final-answer format requirement, are highlighted.
Text copied from the lesson's code.
2. Why does self-consistency sample at temperature 0.7 rather than 0.0?Explain
Two panels, temperature 0.0 and temperature 0.7, each holding five dashed slots labelled path 1 to path 5.
Setup only: what the paths look like is the unknown.
3. In the Tree-of-Thought solver, why is the evaluator itself an LLM call?Explain
A problem box with three branches to thought 1, thought 2 and thought 3, each with a dashed score slot beneath it.
Setup only.
4. Five samples extract the answers 18, 18, 17, 18, 18. What does solve_with_escalation return?Apply
Five sample chips with extracted answers 18, 18, 17, 18, 18, above the last lines of solve_with_escalation: if confidence is at least 0.8 return the vote, otherwise run the tree-of-thought solver.
Answers are from the question; code is from the lesson.
5. The five samples vote 18, 18, 17, 17, 16. What does solve_with_escalation do?Apply
Five sample chips with extracted answers 18, 18, 17, 17, 16, above the last lines of solve_with_escalation: if confidence is at least 0.8 return the vote, otherwise run the tree-of-thought solver.
Answers are from the question; code is from the lesson.
6. Five samples are drawn and one has no extractable answer (extract_answer returns None). The other four give 18, 18, 18, 17. What happens?Apply
Five sample chips with extracted answers 18, 18, 18, 17, None, above the last lines of solve_with_escalation: if confidence is at least 0.8 return the vote, otherwise run the tree-of-thought solver.
Answers are from the question; code is from the lesson. None means extract_answer found no answer.
7. build_cot_prompt receives a list of 5 examples and num_examples=3. What does the user prompt contain before the target question?Apply
Five example chips ex 1 to ex 5 in order, an arrow down to a dashed slot labelled user prompt before the target question. The call is build_cot_prompt with num_examples equal to 3.
Example list from the lesson's code.
8. A question has all 5 samples agreeing. How many LLM calls does the lesson's solve_with_escalation snippet make?Apply
Five sample chips all showing 18, above a shortened copy of solve_with_escalation from the lesson's file, ending with the tree-of-thought line. A question asks how many LLM calls one question makes.
Code shortened from advanced_prompting.py; the lesson's Step 5 snippet has the same structure.
9. Some samples ramble and never state 'The answer is'. A vote sometimes returns a wrong number. Which part of the code is responsible?Analyze
Four boxes in a row joined by arrows: 5 sampled texts, one number per text, vote, returned number. Below, a rambling sample text with no answer line, and a dashed question asking which part of the code let it vote for a wrong number.
The sample text is typed.
10. You run self-consistency with N=5 and all five reasoning paths are word-for-word identical. Which setting should you check first?Analyze
Five rows labelled path 1 to path 5, each containing the same placeholder text meaning identical reasoning, and a dashed slot asking which setting to check first.
Schematic: placeholder text stands in for identical outputs.
11. A team says their escalation pipeline 'tries cheap first', yet every question costs at least 6 calls. What explains it?Analyze
Three boxes in a row: cheap path, check confidence, escalate if needed. Below, a panel noting the observed cost of at least 6 calls per question and a dashed slot asking what explains it.
Setup restated from the question.

Use It

With LangChain

LangChain provides built-in support for prompt templates and output parsing that simplify few-shot and CoT patterns:

python
from langchain_core.prompts import FewShotPromptTemplate, PromptTemplate
from langchain_openai import ChatOpenAI
 
example_prompt = PromptTemplate(
    input_variables=["question", "reasoning", "answer"],
    template="Q: {question}\nA: {reasoning} The answer is {answer}."
)
 
few_shot_prompt = FewShotPromptTemplate(
    examples=examples,
    example_prompt=example_prompt,
    suffix="Q: {input}\nA: Let's think step by step.",
    input_variables=["input"]
)
 
llm = ChatOpenAI(model="gpt-4o", temperature=0.7)
chain = few_shot_prompt | llm
result = chain.invoke({"input": "If a train travels 120 km in 2 hours..."})

LangChain also has ExampleSelector classes for semantic similarity selection:

python
from langchain_core.example_selectors import SemanticSimilarityExampleSelector
from langchain_openai import OpenAIEmbeddings
 
selector = SemanticSimilarityExampleSelector.from_examples(
    examples,
    OpenAIEmbeddings(),
    k=3
)

With DSPy

DSPy treats prompting strategies as optimizable modules. Instead of handcrafting CoT prompts, you define a signature and let DSPy optimize the prompt:

python
import dspy
 
dspy.configure(lm=dspy.LM("openai/gpt-4o", temperature=0.7))
 
class MathSolver(dspy.Module):
    def __init__(self):
        self.solve = dspy.ChainOfThought("question -> answer")
 
    def forward(self, question):
        return self.solve(question=question)
 
solver = MathSolver()
result = solver(question="Janet's ducks lay 16 eggs per day...")

DSPy's ChainOfThought automatically adds reasoning traces. dspy.majority implements self-consistency:

python
result = dspy.majority(
    [solver(question=q) for _ in range(5)],
    field="answer"
)

Comparison: From-Scratch vs Frameworks

FeatureFrom-Scratch (this lesson)LangChainDSPy
Control over prompt formatFullTemplate-basedAutomatic
Self-consistencyManual votingManualBuilt-in (dspy.majority)
Example selectionCustom logicExampleSelectordspy.BootstrapFewShot
Tree-of-ThoughtCustom tree searchCommunity chainsNot built-in
Prompt optimizationManual iterationManualAutomatic compilation
Best forLearning, custom pipelinesStandard workflowsResearch, optimization
Check: Use It0/1
1. In DSPy, what does dspy.majority give you?Define
A code block with the call dspy.majority over a list of five solver calls with field equal to answer, and a question asking what result holds.
Code copied from the lesson.

Ship It

This lesson produces two artifacts.

1. Reasoning Chain Prompt (outputs/prompt-reasoning-chain.md): a production-ready prompt template for few-shot CoT with self-consistency. Plug in your examples and problem domain.

2. CoT Pattern Selection Skill (outputs/skill-cot-patterns.md): a decision framework for choosing the right reasoning technique based on task type, accuracy requirements, and cost constraints.

Author's Note

I'd run advanced_prompting.py against a cheap model before anything else. It needs the openai package and OPENAI_API_KEY set, and the model is hardcoded to gpt-4o in the __main__ block, so change that line if you want to test one of the other models from the table. Self-consistency alone makes 5 calls per question, and the escalation path can add tree-of-thought calls on top.

The function I'd read twice is extract_answer. The vote only means something if final answers can be compared, so it tries "The answer is", then ####, then a trailing = number, and falls back to the last number in the text. That last fallback lets a rambling sample cast a vote, sometimes for the wrong number. The "The answer is [number]" constraint in the prompt exists to keep it from reaching that branch.

I'd also read solve_with_escalation in the file next to the Step 5 snippet. Both always run the single-call answer and the 5-sample vote before checking confidence, so "try cheap first" is looser than it sounds: the single-call answer is computed and the escalation decision never uses it, which means every question pays for 6 calls before any tree-of-thought. The file also calls tree-of-thought with depth=2, while the snippet leaves it at the default 3, and the file returns a dict where the snippet returns a tuple.

Exercises

  1. Measure the gap: Take 10 GSM8K problems. Solve each with zero-shot, few-shot, zero-shot CoT, and few-shot CoT. Record accuracy for each. Which technique gives the biggest lift on your model?

  2. Example selection experiment: For the same 10 problems, compare random example selection vs hand-picked similar examples. Measure accuracy difference. At what point does example quality matter more than example quantity?

  3. Self-consistency cost curve: Run self-consistency with N=1, 3, 5, 7, 10 on 20 GSM8K problems. Plot accuracy vs cost (total tokens). Where is the knee of the curve for your model?

  4. Build a ReAct loop: Extend the pipeline with a calculator tool. When the model generates a math expression, execute it with Python's eval() (in a sandbox) and feed the result back. Measure if tool-grounded reasoning outperforms pure CoT.

  5. ToT for creative tasks: Adapt the Tree-of-Thought solver for a creative writing task: "Write a 6-word story that is both funny and sad." Use the LLM as evaluator. Does branching exploration produce better creative outputs than single-shot generation?

Key Terms

TermWhat people sayWhat it actually means
Few-shot prompting"Give it some examples"Including input-output demonstrations in the prompt to anchor the model's output format and behavior
Chain-of-Thought"Make it think step by step"Eliciting intermediate reasoning tokens that extend the model's effective computation before producing a final answer
Self-Consistency"Run it multiple times"Sampling N diverse reasoning paths at temperature > 0 and selecting the most common final answer by majority vote
Tree-of-Thought"Let it explore options"Structured search over reasoning branches where each partial solution is evaluated and only promising paths are expanded
ReAct"Thinking + tool use"Interleaving reasoning traces with external actions (search, compute, API calls) in a Thought-Action-Observation loop
Prompt chaining"Break it into steps"Decomposing a complex task into sequential prompts where each output feeds the next input
Zero-shot CoT"Just add 'think step by step'"Appending a reasoning trigger phrase to a prompt without any examples, relying on the model's latent reasoning capability

Further Reading