LATS explained: Monte Carlo tree search for language agents, step by step with code
LATS gives a tool-using agent the ability to try several paths, judge them, back up and try again, using Monte Carlo tree search. This guide walks through the six operations from the ICML 2024 paper, runs a compact implementation, and works out what the search costs and when it is worth it.
- Reading time
- 13 min
- Sections
- 8
- Code examples
- 4
- Tables
- 2
- Sources
- 7
- Published
- 24 Nov 2026
- What changed
- The LATS paper appears on arXiv
- Why it matters
- Use LATS where a verifier exists and actions can be undone.
- What to do
- Check reversibility first
A ReAct agent commits to one path. If its second search query is poor, everything after it builds on that mistake, and the agent cannot go back. Language Agent Tree Search (LATS) changes this. It treats each agent state as a node in a tree, generates several possible next actions, scores them, explores the most promising branches, and learns from failed attempts through written reflections. The search algorithm under the hood is Monte Carlo tree search (MCTS), the same family of methods that powered game-playing systems such as AlphaGo.
The paper, from researchers at the University of Illinois Urbana-Champaign, reported a pass@1 of 92.7% on the HumanEval coding benchmark with GPT-4 and an average score of 75.9 on the WebShop navigation benchmark with GPT-3.5, comparable to methods that fine-tune the model. The price is many more model calls per task. This article explains each step of the algorithm, runs a compact implementation you can modify, and sets out when the extra cost is justified.
What happened
The LATS paper appears on arXiv (6 October 2023)
Andy Zhou, Kai Yan, Michal Shlapentokh-Rothman, Haohan Wang and Yu-Xiong Wang introduced LATS as a framework that "unifies reasoning, acting and planning". It combines three earlier ideas: ReAct-style interleaving of thoughts and actions, Reflexion-style self-reflection on failure, and Tree of Thoughts-style search over alternatives, all organised by MCTS.
LATS is published at ICML 2024 (July 2024)
The paper was accepted to the International Conference on Machine Learning 2024. The official repository has code for HotpotQA (reasoning and acting), HumanEval and MBPP (programming) and WebShop (decision making), with the programming code adapted from the Reflexion codebase.
Framework implementations follow
The authors point to a LangGraph implementation, now kept as an archived example in the LangGraph repository, and to a LlamaIndex LATS agent, published as the llama-index-agent-lats package (version 0.3.2 on PyPI).
How MCTS works, in one paragraph
Think of exploring a new city for the best dinner. You try a street, eat somewhere, and remember how good it was. Next evening you mostly go back to streets that gave good meals, but now and then you try one you have barely visited, in case it is better. Over time your map of good and bad streets gets sharper. MCTS does exactly this over a tree: it balances exploitation (visit nodes with high average value) and exploration (visit nodes with few visits) using the UCT rule, plays each choice out to an end to see what happens, and feeds the result back up the path so that every ancestor's estimate improves.
The UCT score of a child node s is:
UCT(s) = V(s) / N(s) + w * sqrt( ln N(parent) / N(s) )
V(s)/N(s) is the average value seen through s, N counts visits, and w sets how much to favour unexplored nodes.
How LATS works, step by step
LATS runs six operations in a loop until it finds a successful trajectory or exhausts its budget.
- Selection. Start at the root and repeatedly move to the child with the highest UCT score until you reach a leaf.
- Expansion. At the leaf, sample
ncandidate next actions (thought plus tool call) from the language model, execute them, and add the resulting states as children. Each child contains the observation from the environment. - Evaluation. Score each new child with a value function. LATS combines a language-model value, where the model is prompted to judge how promising the trajectory is, with a self-consistency score that rewards actions sampled several times.
- Simulation. From the selected child, keep acting until the episode ends, then read the environment's reward, such as "tests passed" or "product matched".
- Backpropagation. Add the result to the value and visit count of every node on the path back to the root, so future selection favours good branches.
- Reflection. If the trajectory failed, ask the model to write a short reflection on why, and include those reflections as context in later iterations, as in Reflexion.
The difference from Tree of Thoughts is feedback. ToT judges partial thoughts using only the model's opinion. LATS also uses real environment signals: search results, test outcomes and page contents. The difference from Reflexion is breadth: Reflexion retries one path at a time, while LATS keeps a whole tree of alternatives and their statistics.
A compact, runnable LATS
The code below implements the loop over a toy environment with three sequential decisions and one successful path out of 27. A noisy function stands in for the LLM value prompt, and random actions stand in for sampled LLM actions. The six operations are labelled.
import math, random
ACTIONS = ["a", "b", "c"]
GOAL = ("b", "c", "a") # the one path that succeeds
def reward(path): # environment feedback at a terminal state
return 1.0 if tuple(path) == GOAL else 0.0
def lm_value(path, rng):
"""Stand-in for the LLM value prompt: a noisy guess of how promising a partial path is."""
on_track = all(x == g for x, g in zip(path, GOAL))
return min(1.0, max(0.0, (0.7 if on_track else 0.3) + rng.gauss(0, 0.25)))
class Node:
def __init__(self, path, parent=None):
self.path, self.parent, self.children = path, parent, []
self.visits, self.value = 0, 0.0
def uct(self, w=1.0):
if self.visits == 0:
return float("inf")
return self.value / self.visits + w * math.sqrt(math.log(self.parent.visits) / self.visits)
def lats(n_children=3, max_iters=30, seed=0):
rng = random.Random(seed)
root, reflections = Node([]), []
for it in range(1, max_iters + 1):
node = root
while node.children: # 1. selection
node = max(node.children, key=lambda c: c.uct())
if len(node.path) < len(GOAL): # 2. expansion
node.children = [Node(node.path + [a], node) for a in ACTIONS[:n_children]]
node = rng.choice(node.children)
score = lm_value(node.path, rng) # 3. evaluation
path = list(node.path)
while len(path) < len(GOAL): # 4. simulation
path.append(rng.choice(ACTIONS))
r = reward(path)
if r == 1.0:
return it, path, reflections
reflections.append(f"iter {it}: {path} failed") # 5. reflection
v = 0.5 * score + 0.5 * r
while node: # 6. backpropagation
node.visits += 1; node.value += v; node = node.parent
return None, None, reflections
found = [lats(seed=s)[0] for s in range(200)]
solved = sorted(f for f in found if f)
print(f"LATS solved {len(solved)}/200 runs; median iterations {solved[len(solved) // 2]}")
Output:
LATS solved 200/200 runs; median iterations 13
For comparison, sampling 30 independent random trajectories solved 131 of the same 200 seeds (about 65%), which matches the theory: the chance of missing a 1-in-27 path 30 times in a row is (26/27)^30, about 32%. The value function, even with noise, steers the tree towards the right prefix, and backpropagation stops the search from wasting visits on branches that keep failing. In the real algorithm, each reflection is also fed back into the prompt that samples new actions, which this toy leaves out.
Two parameters dominate behaviour. n_children is the branching factor: more children per expansion means more coverage and more LLM calls. w controls exploration: too low and the search locks onto an early favourite, too high and it spreads visits thinly.
What the paper measured
| Benchmark | Model | Reported LATS result | What the agent does |
|---|---|---|---|
| HumanEval (programming) | GPT-4 | 92.7% pass@1 | Writes code, runs self-generated tests, searches over candidate programs |
| WebShop (web navigation) | GPT-3.5 | Average score 75.9 | Searches, clicks and buys on a simulated shopping site |
| HotpotQA (multi-hop QA) | GPT-3.5 | Higher exact match than ReAct, Reflexion and ToT-style baselines | Searches Wikipedia with ReAct actions inside the tree |
The authors describe the WebShop result as gradient-free performance comparable to gradient-based fine-tuning. That is the core claim: search plus feedback can recover much of what training would buy, at inference time.
A worked budget
Make the cost concrete with one HotpotQA-style task. Assume each model call reads about 2,000 tokens and writes about 150. One LATS iteration with n = 3 children uses three action samples, three value prompts, a two-step rollout and one reflection: nine calls, or about 18,000 input and 1,350 output tokens. Ten iterations cost about 180,000 input tokens. A ReAct run on the same task might use five calls with a growing history, around 12,000 input tokens. LATS is therefore roughly 15 times more expensive here, so it must solve noticeably more tasks to pay for itself. Prompt caching softens this, because every call in the tree shares the same instructions and examples; the prompt cache hits simulation shows how much of such a session can be served from cache.
The cost and the main assumption
LATS needs many more model calls than ReAct. Each iteration can include n action samples, value prompts for each new child, a rollout of several steps and a reflection. With n = 5, a three-step rollout and one reflection, one iteration can approach ten or more model calls; tens of iterations per task means hundreds. The paper acknowledges higher computational cost than simpler prompting methods.
The second limitation is less obvious. MCTS assumes you can return to an earlier state and try a different action. That is true for question answering with a read-only search tool, for code you can re-run, and for simulated websites. It is not true for actions with side effects: you cannot "un-send" an email or "un-place" an order to explore the alternative. LATS fits environments that are reversible, simulated or sandboxed.
Continue learning
How this article connects
3 pages link to or from it. Drag to turn, click a dot to open it.
Where LATS fits among agent patterns
| Pattern | Paths explored | Uses environment feedback during search? | Learns from failure? | Relative cost |
|---|---|---|---|---|
| ReAct | 1 | Yes, step by step | No | Low |
| Reflexion | 1 per trial, several trials | Yes | Yes, written reflections | Medium |
| Tree of Thoughts | Many | No, model judgement only | No | High |
| LATS | Many | Yes, values plus rewards | Yes, reflections in prompts | Highest |
Use the agentic patterns simulation to see ReAct, planning and reflection side by side, and the Tree of Thoughts reference for the search ideas LATS borrows.
What it means in practice
Use LATS where a verifier exists and actions can be undone. Code generation with tests, data queries in a read-only database and navigation in a sandboxed browser are good fits. The sandboxing page covers isolating such environments.
Treat it as a premium tier. Run a ReAct agent first and escalate to LATS only for tasks that fail or matter most. That keeps average cost close to ReAct while improving the hardest cases; see cost and latency budgets.
Cache everything. Many branches share prefixes. Cache tool results and value prompts keyed by state, as Tree of Thoughts' code does for value prompts.
Measure solved tasks per dollar. Accuracy alone flatters search. The SWE-bench cost per task simulation shows why benchmark scores need a cost axis.
What to do now
- Check reversibility first. List the tools your agent would use and confirm each is read-only, sandboxed or replayable before considering tree search.
- Build a reliable reward. Tests, exact checks or environment success signals should end each rollout; an LLM judge alone gives weak signals.
- Start small. Use
nof 2 to 3 children and a handful of iterations, then raise them only if logs show the right branch being missed. - Cap tokens and calls per task. Set a hard budget and return the best trajectory found when it runs out.
- Escalate selectively. Route only failed or high-value tasks from ReAct to LATS.
- Log the tree. Store every node's action, observation, value and visit count so you can see why a branch won.
- Reuse existing implementations to learn. The official repository, the archived LangGraph example and
llama-index-agent-latsshow complete prompts and state handling. - Compare at equal cost. Run self-consistency, Reflexion and LATS with the same token budget on your tasks before committing.
Risks and open questions
Irreversible actions break the method. Exploring alternatives requires resetting state. With real side effects, search can repeat harmful actions or leave the world inconsistent.
Noisy values mislead the search. If the model's value prompt is poorly calibrated, the tree spends its budget on attractive but wrong branches. Environment rewards help, but only at the end of rollouts.
Costs vary widely per task. Easy tasks finish in one iteration; hard ones use the whole budget. Plan capacity for the tail, not the average.
Results predate current models. The reported scores used GPT-4 and GPT-3.5. Stronger reasoning models narrow the gap that search fills, so re-measure on your own stack.
Watch next: tree search inside coding agents with sandboxed test runs, shared value models across tasks, and whether reasoning-model APIs expose branching controls that make external MCTS less necessary.
Frequently asked questions
What does LATS add to ReAct?
It lets the agent explore several action sequences instead of one, scores partial trajectories, uses environment feedback to update those scores, and feeds reflections on failures into later attempts. ReAct alone follows a single greedy path.
What is the UCT formula doing?
It picks which child to explore by adding the child's average value to an exploration bonus that is large for rarely visited nodes. This balances trying the best-looking branch with checking branches that have not been tested enough.
Why does LATS need reversible environments?
Tree search revisits earlier states to try different actions. If an action changes the real world, such as sending a message, you cannot return to the state before it to explore the alternative.
How expensive is LATS compared with ReAct?
Much more expensive: each iteration samples several actions, evaluates them and runs a rollout, and tasks may need many iterations. Budget it per task and use it selectively.
Is there a ready-made implementation?
Yes. The authors' repository has research code, the LangGraph repository keeps an archived LATS example, and LlamaIndex publishes llama-index-agent-lats. Treat them as starting points and add your own budgets and logging.
Summary
LATS applies Monte Carlo tree search to language agents: it selects promising states with UCT, expands them with sampled actions, scores them with a language-model value and self-consistency, rolls out to a reward, backpropagates the result and stores reflections on failures. The ICML 2024 paper reported 92.7% pass@1 on HumanEval with GPT-4 and a WebShop score of 75.9 with GPT-3.5. It is the most capable and most expensive of the classic agent patterns, and it assumes actions can be undone. Use it as an escalation tier for hard, verifiable tasks in reversible or sandboxed environments.
Sources
- Paper arXiv: Language Agent Tree Search Unifies Reasoning, Acting, and Planning in Language Models
- Code GitHub: lapisrocks/LanguageAgentTreeSearch official code
- Code GitHub: archived LangGraph LATS example
- Code PyPI: llama-index-agent-lats
- Paper arXiv: Reflexion: Language Agents with Verbal Reinforcement Learning
- Paper arXiv: Tree of Thoughts: Deliberate Problem Solving with Large Language Models
- Paper arXiv: ReAct: Synergizing Reasoning and Acting in Language Models
Cite this article
Kelahmet, Ö. C. (2026, November 24). LATS explained: Monte Carlo tree search for language agents, step by step with code. Özer Cem KELAHMET. https://www.ozercemkelahmet.com/articles/lats-language-agent-tree-search-mcts
BibTeX
@online{kelahmet2026lats,
author = {Kelahmet, {\"O}zer Cem},
title = {{LATS explained: Monte Carlo tree search for language agents, step by step with code}},
year = {2026},
month = {nov},
url = {https://www.ozercemkelahmet.com/articles/lats-language-agent-tree-search-mcts}
}Version historyfirst version
- Published
Factual corrections are listed here with what changed. Wording and formatting edits are not listed.