Tree of Thoughts explained: propose, evaluate and search with a runnable Game of 24
Tree of Thoughts turns one chain of reasoning into a search over many partial solutions. This guide follows the paper and its official code: how thoughts are proposed, how states are valued, how breadth-first search prunes them, what it costs and when it is worth it.
- Reading time
- 14 min
- Sections
- 7
- Code examples
- 5
- Tables
- 2
- Sources
- 7
- Published
- 24 Nov 2026
- What changed
- The Tree of Thoughts paper appears on arXiv
- Why it matters
- Use ToT when steps can be checked.
- What to do
- Define what one thought is
A chain-of-thought prompt asks a model to reason in one line, left to right. If the first step is wrong, every later step builds on the mistake. Tree of Thoughts (ToT), a 2023 paper from Princeton and Google DeepMind, treats reasoning as a search instead: the model proposes several possible next steps, judges how promising each one is, keeps the best few and continues from those. Bad branches are dropped before they waste the whole answer.
The headline result was striking. On the Game of 24 puzzle, GPT-4 with chain-of-thought prompting solved 4% of the hard test games; with Tree of Thoughts it solved 74%. Since then the idea has spread into agent design: tree search over tool-using trajectories (LATS), test-time compute in reasoning models and search-based planners all borrow from it. This article explains the algorithm from the paper and its official code, then runs a complete Game of 24 search in Python.
What happened
The Tree of Thoughts paper appears on arXiv (17 May 2023)
Shunyu Yao, Dian Yu, Jeffrey Zhao, Izhak Shafran, Thomas Griffiths, Yuan Cao and Karthik Narasimhan introduced ToT as a generalisation of chain-of-thought prompting. They tested it on three tasks that need planning or search: Game of 24, creative writing and 5x5 mini crosswords.
ToT is presented as an oral paper at NeurIPS 2023 (December 2023)
The paper was accepted to NeurIPS 2023 as an oral presentation. The official repository, princeton-nlp/tree-of-thought-llm, publishes the prompts, the search code and all model outputs, and ships as the tree-of-thoughts-llm package on PyPI.
The repository documents a reproduction gap
The README notes that a later re-run of the main Game of 24 experiment scored 69% instead of the paper's 74%, "due to randomness in GPT decoding". That is a useful reminder for anyone citing search results with sampled models: a single run can move by several points.
How Tree of Thoughts works, step by step
Think of a chess player. They do not play the first move that comes to mind. They list a few candidate moves, look a step or two ahead, judge which positions look good, and drop the bad lines. ToT asks a language model to play both roles: the one who suggests moves and the one who judges positions.
The paper frames every ToT system as four design choices.
- Thought decomposition. Decide what one "thought" is. In Game of 24 it is one arithmetic step, such as
4 * 5 = 20 (left: 6 10 20). In creative writing it is a whole paragraph plan. - Thought generation. Produce candidate next thoughts from a state. Either sample several independent thoughts (good when thoughts are long, as in writing), or propose several in one call (good when they are short and should not repeat, as in arithmetic).
- State evaluation. Judge how promising a state is. Either value each state on its own (the model answers "sure", "likely" or "impossible") or vote across states (the model picks the best of several).
- Search algorithm. Breadth-first search (BFS) that keeps the best
bstates at each depth, or depth-first search (DFS) that goes deep and backtracks when a state is judged impossible.
Game of 24 in the official code
In Game of 24 you get four numbers and must reach 24 with +, -, * and /, using each number once. The official code uses BFS with three steps, because each step combines two numbers and four numbers become one after three steps.
The propose prompt is a one-shot example that lists possible next steps:
Input: 2 8 8 14
Possible next steps:
2 + 8 = 10 (left: 8 10 14)
8 / 2 = 4 (left: 4 8 14)
14 + 2 = 16 (left: 8 8 16)
...
Input: {input}
Possible next steps:
The value prompt shows worked judgements and ends each with one word:
Evaluate if given numbers can reach 24 (sure/likely/impossible)
10 14
10 + 14 = 24
sure
...
5 7 8
5 + 7 + 8 = 12 + 8 = 20
(8 - 5) * 7 = 3 * 7 = 21
I cannot obtain 24 now, but numbers are within a reasonable range
likely
The code samples the value prompt three times per state (n_evaluate_sample=3), maps each answer to a number with {'impossible': 0.001, 'likely': 1, 'sure': 20} (the source marks the weights "ad hoc") and sums them. It then keeps the five highest-scoring states (n_select_sample=5, the paper's breadth b = 5) with greedy selection. A state that scores "sure" three times gets 60; one that is "likely" three times gets 3. One "sure" vote outweighs many "likely" votes, so the search strongly prefers states the model can already see a path from.
A runnable ToT search
The code below keeps the paper's structure exactly, BFS, depth 3, b = 5 and the same value map, but replaces the two model calls with deterministic functions so you can run it instantly. propose() enumerates every legal step, as a perfect proposer would. evaluate() mimics the value prompt: "sure" when the remaining numbers can reach 24 in one step, "likely" when they are in a plausible range, otherwise "impossible".
from fractions import Fraction as F
from itertools import combinations
VALUE = {"sure": 20, "likely": 1, "impossible": 0.001} # the official repo's value map
def propose(nums):
"""Thought generator. A real ToT asks the LLM to propose these steps."""
out = []
for i, j in combinations(range(len(nums)), 2):
a, b = nums[i], nums[j]
rest = [n for k, n in enumerate(nums) if k not in (i, j)]
cands = {(f"{a} + {b}", a + b), (f"{a} * {b}", a * b),
(f"{max(a, b)} - {min(a, b)}", abs(a - b))}
if b: cands.add((f"{a} / {b}", a / b))
if a: cands.add((f"{b} / {a}", b / a))
for expr, c in cands:
out.append((f"{expr} = {c}", sorted(rest + [c])))
return out
def evaluate(nums):
"""State evaluator standing in for the LLM's sure/likely/impossible answer."""
if len(nums) == 1:
return "sure" if nums[0] == 24 else "impossible"
if len(nums) == 2:
a, b = nums
hits = {a + b, a * b, abs(a - b)} | ({a / b} if b else set()) | ({b / a} if a else set())
return "sure" if 24 in hits else "impossible"
return "likely" if max(nums) * len(nums) >= 24 and sum(nums) <= 72 else "impossible"
def tot_bfs(start, b=5):
frontier, evals = [([], sorted(map(F, start)))], 0
for depth in range(3):
children = []
for steps, nums in frontier:
for thought, left in propose(nums):
evals += 1
children.append((VALUE[evaluate(left)], steps + [thought], left))
children.sort(key=lambda c: c[0], reverse=True)
frontier = [(s, l) for _, s, l in children[:b]] # keep the b best states
print(f"depth {depth + 1}: {len(children)} candidates")
for steps, nums in frontier:
if nums[0] == 24:
return steps, evals
return None, evals
print(tot_bfs([4, 5, 6, 10]))
The run prints:
depth 1: 30 candidates
depth 2: 75 candidates
depth 3: 25 candidates
(['4 * 5 = 20', '10 - 6 = 4', '4 + 20 = 24'], 130)
Read the numbers as a cost trace. At depth 1, six pairs of numbers and up to six operations give 30 distinct candidate states. Five are kept. At depth 2 those five states expand to 75 candidates, and three of them are already "sure" (for example 4 20 and 10 14). At depth 3 the "sure" states finish on 24. In total the evaluator judged 130 states. With the paper's three value samples per state, a real run would make up to 390 value calls plus one propose call per expanded state, before caching. The official code caches value prompts and gives duplicate candidates a value of zero, which cuts this noticeably.
What the paper measured
| Task | Thought | Generation | Evaluation | Search | Reported result |
|---|---|---|---|---|---|
| Game of 24 (100 hard games) | One equation step | Propose | Value, 3 samples | BFS, b = 5 | 74% success with GPT-4, against 4% for chain of thought |
| Creative writing (4 random sentences must end 4 paragraphs) | A writing plan | Sample 5 | Vote | BFS, depth 2 | More coherent passages than IO and CoT, by GPT-4 scores and human preference |
| Mini crosswords (5x5) | One word filled in | Propose | Value per remaining clue | DFS with pruning | Higher word- and game-level success than IO and CoT |
Two lessons carry over. First, the evaluator does most of the work. In Game of 24 the proposer finds legal steps easily; the hard part is knowing which partial states can still reach 24. Second, the search structure must fit the task. Crosswords needed DFS with backtracking because an early wrong word makes later clues impossible; BFS with a fixed beam would waste effort.
The cost side
ToT spends many model calls per problem. The paper acknowledges that ToT needs more resources than sampling methods and suggests using it only where a task needs deliberate search and simpler prompting fails. A rough budget for one Game of 24 problem with the paper's settings: up to 3 depths x 5 kept states = about 15 propose calls (fewer at depth 1, which starts from one state), plus three value samples for every new candidate. That is one to two orders of magnitude more calls than a single chain-of-thought answer. Compare that with self-consistency, which samples many complete chains but never evaluates partial ones.
Continue learning
How this article connects
5 pages link to or from it. Drag to turn, click a dot to open it.
When to use Tree of Thoughts in agents
ToT is a reasoning strategy, not a framework feature, but it shows up in agent design in three ways.
Search over plans. Before an agent acts, generate several candidate plans, score each with a value prompt or a cheap simulator, and execute the best. This is ToT with one level of depth and fits planning agents well.
Search over actions. LATS-style tree search extends ToT to tool-using agents: each node is a ReAct state, children are possible next actions, and a value function plus environment feedback guide a Monte Carlo tree search.
Test-time compute. Reasoning models now spend extra tokens exploring and backtracking internally. External ToT still helps when you have a reliable evaluator the model does not have, such as a solver, a unit test or a constraint checker. The test-time compute page covers this trade-off.
| Method | Explores alternatives? | Judges partial work? | Typical calls per task |
|---|---|---|---|
| Chain of thought | No | No | 1 |
| Self-consistency | Yes, full chains | No, majority vote at the end | k (often 5 to 40) |
| Tree of Thoughts | Yes, step by step | Yes, value or vote prompts | Tens to hundreds |
| LATS | Yes, over actions | Yes, value plus environment reward | Tens to hundreds, plus tool calls |
What it means in practice
Use ToT when steps can be checked. The method pays off when partial states can be judged: arithmetic, constraint puzzles, code that compiles or fails, plans that can be simulated. On open-ended chat, the evaluator has little to grip.
Replace the LLM evaluator where you can. In the run above, an exact checker made the search cheap and reliable. In real systems, a SQL engine, type checker or test suite is often a better state evaluator than a value prompt.
Watch the beam width. b = 5 at depth 3 already means 130 states in a small puzzle. Widening the beam improves the chance of keeping a correct branch but multiplies cost. The Tree of Thoughts reference page collects variants, and the beam search simulation shows the same width-versus-cost trade-off for decoding.
Prefer the simplest method that works. Try chain of thought, then self-consistency style sampling, then ToT. Each step up adds cost, and the reasoning models you call may already search internally; keep it only if your evaluation shows a real gain.
What to do now
- Define what one thought is. Pick a unit small enough to judge and large enough to make progress, like one equation, one plan step or one tool call.
- Write the evaluator first. If you cannot judge partial states better than chance, ToT will not help; use LLM as a judge only after measuring its agreement on your data.
- Start with BFS and a small beam. Begin with depth 2 or 3 and
bof 2 to 5, then widen only if the logs show correct branches being pruned. - Cache and deduplicate states. The official code caches value prompts and zeros out duplicate candidates; both are cheap wins.
- Count calls per task. Log proposals, evaluations and tokens per solved problem, and compare with chain of thought and self-consistency at the same budget.
- Run several seeds. The repo's own 74% versus 69% reproduction shows how much one run can vary; report a range, not a single number.
- Use the official code to learn. The
tree-of-thoughts-llmpackage and its logs show exactly how prompts, values and selection were wired. - Consider LATS for tool use. If your "thoughts" are actions with real observations, move to a tree search that uses environment feedback.
Risks and open questions
Evaluator errors prune the right answer. If the value prompt wrongly calls a good state "impossible", BFS drops it forever. A larger beam or DFS with backtracking reduces the risk but costs more.
Costs are hard to bound. The number of calls depends on branching and pruning, which vary per problem. Put hard limits on expanded nodes and tokens, and set them from a cost and latency budget per task.
Benchmarks are narrow. The paper's three tasks are puzzles chosen because chain of thought fails on them. Gains on real business tasks need your own measurement.
Reasoning models narrow the gap. Models trained to think longer already explore internally. External tree search keeps an edge mainly when it brings an evaluator the model does not have.
Watch next: search methods that share one evaluator across many problems, tree search inside agent frameworks, and whether reasoning-model APIs expose controls that make external ToT unnecessary for most tasks.
Frequently asked questions
How is Tree of Thoughts different from chain of thought?
Chain of thought follows one line of reasoning and cannot undo a bad step. Tree of Thoughts generates several candidate steps, evaluates partial states and keeps or backtracks, so a wrong early step can be abandoned.
What does b = 5 mean?
It is the breadth of the breadth-first search: after each step, only the five highest-valued states are kept and expanded. A larger b keeps more alternatives alive at a higher cost.
Why does the value map give "sure" a weight of 20?
The official code uses 20 for "sure", 1 for "likely" and 0.001 for "impossible", and marks these weights as ad hoc. The large gap makes states the model is confident about dominate the selection.
Is Tree of Thoughts useful for agents with tools?
Yes, in extended forms. LATS applies tree search to ReAct-style trajectories with tools and environment feedback, and planning agents can use one-level ToT to choose among candidate plans before acting.
Is the 74% result reproducible?
The repository notes that a later reproduction of the Game of 24 run scored 69%, attributing the gap to decoding randomness. Treat single-run search results as estimates and run several seeds.
Summary
Tree of Thoughts makes a language model search: it proposes candidate thoughts, judges partial states as sure, likely or impossible, and keeps the best few at each step with BFS or backtracks with DFS. With GPT-4 it raised Game of 24 success from 4% with chain of thought to 74%, at the cost of many more model calls. The method works best when partial progress can be judged reliably, ideally by a real checker, and when the task punishes early mistakes. For tool-using agents, its ideas live on in LATS and in plan-scoring steps before execution.
Sources
- Paper arXiv: Tree of Thoughts: Deliberate Problem Solving with Large Language Models
- Code GitHub: princeton-nlp/tree-of-thought-llm official code, prompts and logs
- Code GitHub: Game of 24 prompts in the official repository
- Code GitHub: BFS search code in the official repository
- Paper NeurIPS 2023: Tree of Thoughts oral presentation
- Code PyPI: tree-of-thoughts-llm
- Paper arXiv: Language Agent Tree Search
Cite this article
Kelahmet, Ö. C. (2026, November 24). Tree of Thoughts explained: propose, evaluate and search with a runnable Game of 24. Özer Cem KELAHMET. https://www.ozercemkelahmet.com/articles/tree-of-thoughts-search-explained-code
BibTeX
@online{kelahmet2026tree,
author = {Kelahmet, {\"O}zer Cem},
title = {{Tree of Thoughts explained: propose, evaluate and search with a runnable Game of 24}},
year = {2026},
month = {nov},
url = {https://www.ozercemkelahmet.com/articles/tree-of-thoughts-search-explained-code}
}Version historyfirst version
- Published
Factual corrections are listed here with what changed. Wording and formatting edits are not listed.