Agentic Pattern Libraryby Vikas Goyal
Patterns / Math models / MCTS and beam search
No. M15 Planning Established Decision Verification

MCTS and beam search

Spending a call budget on search: greedy, beam, best-of-N and tree search

Takeaway

A -step plan where each proposed step is right % of the time works 4.7% of the time if you just run it. With model calls of search, beam search gets it right 78% of the time.

Change the blue numbers. Every figure on this page updates with them.

Why care

Long plans fail by compounding, and search is how agents fight back.

An agent that commits to its first idea at every step multiplies its per-step error rate across the whole plan (M01). Search changes that: propose several candidates for each step, score them, keep the promising ones, and back up when something fails. Tree-of-thought, beam search over reasoning steps, best-of-N sampling and Monte Carlo tree search (MCTS) are all ways of spending extra model calls to raise the odds of a working plan. They differ in what they need, a scorer for each step or a check at the end, and in how well they use a given budget. This page compares them on the same problem and the same budget.

The intuition

Picture a maze with a few exits and many dead ends. You can walk it in different ways:

  • Greedy: at each fork, take the path that looks best. Fast, but one bad look and you are lost.
  • Beam search: keep the \(k\) best-looking paths alive at every fork, then pick the best-looking one at the end. Robust to a few bad looks, but it can only judge by looks.
  • Best-of-N: send \(N\) people through at random and check who got out. Needs a way to check the exit, and no judgment at the forks.
  • MCTS: explore, check whether you got out, and remember which forks led closer. It uses both looks and checks, and spends more effort where it has been promising.

Which wins depends on what you have. A good step scorer favors beam search. A reliable final check (tests, a validator) favors strategies that can use it, and with enough budget, tree search that can back up and try again.

The math

Model a plan as \(d\) steps. At each step the model proposes \(b\) candidates; each is good with probability \(g\), and a plan works only if every step is good. A step scorer (a verifier or process reward model) rates candidates with quality AUC; a final check (tests) tells whether a whole plan works.

$$P_{\text{luck}} = g^{d}, \qquad P_{\text{best-of-}N} = 1-\big(1-g^{d}\big)^{N}, \qquad P_{\text{greedy}} = s^{\,d}$$

where \(s\) is the chance the top-scored of \(b\) candidates is good. MCTS chooses which branch to explore with the PUCT rule, balancing what has worked so far against the scorer's prior and how little a branch has been tried:

$$a^{*} = \arg\max_a \Big[\,Q(s,a) + c\,P(s,a)\,\frac{\sqrt{N(s)}}{1+N(s,a)}\Big]$$
\(d,\ b\)
steps in the plan, and candidates proposed per step
\(g\)
chance a proposed step is good, given the steps before it were good
\(k,\ N\)
beam width, and number of full plans sampled for best-of-N
\(Q,\ P,\ N(\cdot)\)
in MCTS: a branch's observed success rate, its prior from the step scorer, and visit counts
\(B\)
budget: model calls, one per proposed step
  • Greedy costs \(d\,b\) calls, beam search \(k\,d\,b\), best-of-N \(N\,d\). MCTS spends calls one expansion at a time until the budget runs out or the check passes.
  • Beam search has a ceiling: it never checks the final result, so it is only as good as its scorer, however wide the beam.
  • Search with a final check keeps improving with budget, because a failed check sends it back to try elsewhere.

Where each of these comes from is worked through in Derivations at the end of the page.

Interactive calculator

Each strategy is simulated 800 times per budget level on randomly generated plan trees. Greedy and beam search use only the step scorer; best-of-N uses only the final check; MCTS uses both.

–
Run the plan once, no search
–
Greedy, step scorer
–
Beam search, step scorer
–
Best-of-N, final check
–
MCTS, step scorer and final check
–
Best strategy at this budget
Greedy Beam search Best-of-N MCTS

Worked example: a six-step refactor

A coding agent plans a six-step refactor: update a config, change a schema, migrate data access, update callers, adjust tests, update docs. At each step it can propose four alternatives; each proposed step is right about 60% of the time. A reviewer model scores proposed steps with an AUC of 0.80, and the test suite checks the finished change. Run once, the plan works \(0.6^6 = 4.7\%\) of the time.

StrategyUses96 calls192 calls
Run once–4.7%4.7%
Greedy (always 24 calls)Reviewer36%36%
Beam search (\(k = 4\), then 8)Reviewer78%85%
Best-of-N (\(N = 16\), then 32)Tests53%78%
MCTSReviewer and tests73%91%

Greedy is computed exactly; the others are averages over 6,000 to 10,000 simulated runs. The calculator uses 800 runs per point, so its figures can differ by a point or two.

At 96 calls, beam search won: it spent every call on the most promising candidates. Doubling the budget barely helped it, because without running the tests it could only be as right as the reviewer. MCTS was slower to start, since it spent calls exploring and checking, but with 192 calls it overtook beam search by using the test results to abandon failing branches. The team ran beam search for routine changes and switched to tree search, with a larger budget, for refactors that touched many files.

Assumptions and where it breaks

  • Candidates are assumed independent. Samples from one model at one step tend to share mistakes, so four candidates can be worth fewer than four (M10). Vary prompts or temperature to keep them diverse.
  • Steps are all-or-nothing. Real plans can recover from a weak step later, and some steps matter more than others. Treat \(g\) as an average and test on real tasks.
  • Scorer calls are not counted. If the step scorer is itself an expensive model, add its calls to the budget; that penalizes beam search and MCTS relative to best-of-N.
  • Calls are not latency. Beam search and best-of-N parallelize well; MCTS is sequential. Under a tight time limit, a parallel strategy can win even with lower success per call.
  • A final check may not exist. For open-ended outputs with no tests, only scorer-based strategies apply, and the scorer's quality is the ceiling.

How to apply it

  1. Identify your signals. Do you have a step scorer, a final check, or both? That narrows the choice before any tuning.
  2. Measure them. Estimate the per-step success rate from traces and the step scorer's AUC on labeled steps.
  3. Start with beam search when you have a decent scorer and a modest budget; add the final check on the beam's survivors when you have one.
  4. Move to tree search for long tasks with a reliable final check and room for a bigger budget.
  5. Set the budget where the curve flattens, and give the agent an explicit call budget so search stops (M03).

How to explain it to a stakeholder

"A plan with six steps, each a little uncertain, rarely works first time. So the agent tries a few options at each step and keeps the promising ones. If we can test the result, it can also back up and try again, which is how we turn a 5% shot into something that works most of the time."

For coding agents

A machine-readable summary and a reference implementation. The same spec is embedded in this page as <script type="application/json" id="model-spec">, and the whole series is listed in models.json.

Model spec (YAML)
id: mcts-beam-search
number: M15
name: Search over agent plans (greedy, beam, best-of-N, MCTS)
family: planning
answers: "How should an agent spend a call budget searching over multi-step plans?"
formula:
  no_search: "g**d"
  best_of_n: "1 - (1 - g**d)**N, calls N*d"
  greedy: "s**d, calls d*b, s = P(top-scored of b candidates is good)"
  beam: "calls k*d*b, simulated"
  puct: "argmax_a Q(s,a) + c * P(s,a) * sqrt(N(s)) / (1 + N(s,a))"
inputs:
  d: {type: int, meaning: steps in the plan}
  b: {type: int, meaning: candidates per step}
  g: {type: float, meaning: chance a proposed step is good}
  auc: {type: float, meaning: step scorer quality}
  budget: {type: int, meaning: model calls available}
assumptions:
  - candidates independent; a plan works only if every step is good
  - final check is reliable when present
  - scorer calls not counted in the budget
use_when:
  - choosing a search strategy for multi-step agent tasks
  - sizing the call budget for planning
related_patterns: [plan-and-execute, draft-verify, test-first-loop, parallel-worktrees]
Reference implementation (Python, NumPy)
import math
import numpy as np
from scipy.stats import norm

def beam_search(d=6, b=4, g=0.6, auc=0.8, k=4, trials=2000, seed=1):
    """Share of runs where beam search ends on a plan whose every step is good."""
    rng = np.random.default_rng(seed)
    mu = math.sqrt(2) * norm.ppf(auc)                 # scorer separation
    wins = 0
    for _ in range(trials):
        beam = [True]                                  # each entry: is this partial plan still good?
        for _ in range(d):
            cands = []
            for good_so_far in beam:
                for _ in range(b):
                    good = good_so_far and rng.random() < g
                    cands.append((rng.normal(mu if good else 0.0, 1.0), good))
            cands.sort(key=lambda c: -c[0])
            beam = [good for _, good in cands[:k]]
        wins += beam[0]
    return wins / trials

def best_of_n(d=6, g=0.6, n=16):
    return 1 - (1 - g ** d) ** n

if __name__ == "__main__":
    print(round(0.6 ** 6, 3))                    # 0.047, no search
    print(beam_search(k=4))                      # about 0.78 with 96 calls
    print(round(best_of_n(n=16), 3))             # 0.534 with 96 calls

Derivations

For the math-curious: where each result in The math comes from. Nothing above depends on reading this.

No search and best-of-N

A plan sampled step by step is good only if all \(d\) steps are good: \(g^d\). Best-of-N samples \(N\) independent plans and runs the final check on each; it fails only if all \(N\) fail, so it succeeds with \(1-(1-g^d)^N\). That is the retry formula from M02, applied to whole plans, and it needs \(N \approx \ln(1-T)/\ln(1-g^d)\) plans to reach target \(T\): many, when \(g^d\) is small.

Greedy with a step scorer

At each step, with \(m\) of the \(b\) candidates good (binomially distributed), greedy picks a good one if the highest of the \(m\) good scores beats the highest of the \(b-m\) bad scores. With good scores \(\sim N(\mu,1)\) and bad \(\sim N(0,1)\), \(\mu = \sqrt2\,\Phi^{-1}(\text{AUC})\), the per-step success is

$$s = \sum_{m=1}^{b}\binom{b}{m}g^m(1-g)^{b-m}\,\Pr\Big(\max_{m}X^{+} > \max_{b-m}X^{-}\Big),$$

and the plan succeeds with \(s^d\). Greedy turns the per-step rate from \(g\) into \(s\), which can be much higher, but errors still compound over \(d\) steps.

Why beam search has a ceiling

Beam search keeps the \(k\) highest-scoring partial plans at each step. A wider beam keeps more good plans alive, but at the end it returns the plan with the best final score. Since the scorer can mistake a bad plan for a good one, the chance that the top-scored survivor is actually good stays below 1 even as \(k\) grows: the ceiling is set by the scorer's AUC. Adding the final check on all \(k\) survivors removes the ceiling, and turns beam search into a hybrid.

MCTS is a bandit at every node

At each node, choosing which child to explore is a multi-armed bandit problem: exploit children whose subtrees have led to working plans, but keep exploring children that are untried. UCT applies the UCB1 bandit rule at every node (Kocsis and Szepesvári, 2006); PUCT, used in AlphaZero, adds a prior \(P(s,a)\) from a learned scorer, so promising children are tried first. Each iteration selects down the tree, expands a node, rolls out to a full plan, runs the final check, and passes the result back up. Because failed checks lower \(Q\) along the path, the search moves its budget away from branches that don't work.

References

  1. Kocsis, L. and Szepesvári, C. (2006). Bandit based Monte-Carlo planning. European Conference on Machine Learning, 282–293. The UCT algorithm.
  2. Yao, S. et al. (2023). Tree of Thoughts: Deliberate Problem Solving with Large Language Models. Breadth- and depth-first search over reasoning steps.
  3. Zhou, A. et al. (2023). Language Agent Tree Search Unifies Reasoning, Acting, and Planning in Language Models. MCTS for LLM agents, guided by model-scored values.
  4. Lightman, H. et al. (2023). Let's Verify Step by Step. Process reward models that score individual reasoning steps.