Real environment (default)
All steps
Parts of this pattern
- Task Input / output
- A HumanEval-style coding task: write is_valid_bracket_seq(s) so that the hidden unit tests pass.
- Selector Router
- Plain code: walks the search tree from the root, picking the child with the best value plus exploration bonus.
- Expander LLM call
- Samples k different next actions from the selected node, here two candidate implementations, with saved reflections in its prompt.
- Test runner Tool
- Executes each candidate for real against the visible tests and returns which passed and which failed.
- Value Evaluator
- Scores each new child from 0 to 1, blending the test pass rate with a model score, then backs it up to every ancestor.
- Reflector LLM call
- For every failed attempt, writes a short lesson about what went wrong, without writing code.
- Reflections Memory
- Saved lessons from failed branches, added to every later expand prompt.
- Solution Input / output
- The code from the first child whose tests all pass.
- Task → Selector
- The task becomes the root of the search tree.
Write is_valid_bracket_seq(s): return True if every bracket in s is closed in the right order.
- Selector → Expanderselect
- The selected node, with the trajectory that reached it, goes to the expander.
Expand node B (visits 1, value 0.6): the stack-based draft that failed 1 of 4 tests.
- Expander → Test runnerk actions
- Each sampled action is run in the environment from the same starting state.
Child A: return s.count('(') == s.count(')'). Child B: stack-based check that returns False when s is empty.
- Test runner → Value
- The observations, here test results, go to the value function.
A: 2/4 passed (accepts ')('). B: 3/4 passed (fails on the empty string).
- Value → Selectorbackprop
- Each child's score is added to its ancestors' averages, so the next selection favours the promising branch.
A: 0.3, B: 0.6. Root: visits 2, value 0.45.
- Test runner → Reflectorfail
- A failed attempt, with its test output, goes to the reflector.
A failed test_order: ')(' returned True. B failed test_empty: '' returned False, expected True.
- Reflector → Reflections
- Each lesson is saved for every later expansion.
A: counting alone accepts ')('; track depth and fail if it goes negative. B: an empty string is balanced; return True for it.
- Reflections → Expanderlessons
- Saved lessons go into the expand prompt, so new branches avoid known mistakes.
<reflections>Empty string is valid. Counting alone accepts ')('.</reflections>
- Value → Solutionsolved
- When a child passes every test, its trajectory is returned and the search stops.
Child B1: stack-based check, returns True for an empty string. 4/4 tests passed.
World model (RAP)
No real environment: the model itself predicts the state each action leads to, and the tree search runs over those imagined states.
All steps
Parts of this pattern
- Goal Input / output
- A Blocksworld puzzle from the paper's benchmark: red is on blue; get blue onto red.
- Selector Router
- Plain code: walks the tree from the root, picking the child with the best value plus exploration bonus.
- Actions LLM call
- Proposes a few legal next actions for the selected state, such as 'unstack red from blue'.
- World model LLM call
- The same model, prompted to simulate: it predicts the state an action would lead to. Nothing is executed.
- Reward Evaluator
- Scores each predicted state for progress toward the goal, then backs the score up the tree.
- Plan Input / output
- The sequence of actions on the path whose predicted state meets the goal.
- Goal → Selector
- The starting state becomes the root of the search tree.
Start: red on blue, blue on table, hand empty. Goal: blue on red.
- Selector → Actionsselect
- The selected state goes to the action proposer.
State: red on blue, blue on table, hand empty.
- Actions → World modelaction
- Each proposed action is passed to the world model, which imagines its outcome.
Action: pick up blue
- World model → Rewardnext state
- The predicted state, or ILLEGAL, goes to the reward step.
ILLEGAL: blue is not clear, red is on top of it.
- Reward → Selectorbackprop
- Rewards are added to every ancestor's average, so the next rollout favours promising states.
pick up blue: 0.0. unstack red from blue: 0.7.
- Reward → Plangoal met
- When a predicted state meets the goal, the actions on its path are returned as the plan.
1. unstack red from blue 2. put down red 3. pick up blue 4. stack blue on red
← → neighboursesc atlas
Language Agent Tree Search
Also known as LATS · MCTS agent · Agent tree search
Monte Carlo tree search over agent actions. Expand, act for real, score, back up the score along the path, and learn from failed branches.
Real environment: Introduced by Zhou et al. (2023) · University of Illinois Urbana-Champaign & Lapis Labs
Published at ICML 2024. It combines Monte Carlo tree search with ReAct-style acting and Reflexion-style self-reflection; the paper evaluates it on HumanEval, HotpotQA and WebShop. For programming, its environment runs tests the model wrote itself as well as the visible examples.
World model (RAP): Introduced by Hao et al. (2023) · UC San Diego, University of Florida and others
RAP (Reasoning via Planning), EMNLP 2023. It came before LATS and uses the same Monte Carlo tree search, with the model acting as a world model instead of calling an environment.
Measured over one run
Real environment
- Nodes
- 8. Boxes in the diagram: models, tools, stores, people and plain code.
- LLM calls
- 6. Model invocations in the first scenario: each time a model or agent node starts thinking, plus each branch it decides.
- Tool calls
- 2. Messages sent to a tool node in the first scenario.
- Steps
- 7. Steps in the first scenario, with repeated steps counted every time they run.
- Scenarios
- 1. Distinct example runs you can switch between on the diagram.
- Loop
- yes. Whether the flow cycles back on itself until a condition is met.
- Parallel
- no. Whether two or more messages are in flight at the same time.
- Branch
- yes. Whether the flow takes one path out of several, chosen at run time.
- Human in the loop
- no. Whether a person appears as a node, to approve, correct or answer.
- Autonomy
- high. How much the model decides the control flow itself, from fixed code paths (low) to open-ended (high).
- Cost
- high. Relative token spend per request.
- Latency
- high. Relative wall-clock time per request.
World model (RAP)
- Nodes
- 6. Boxes in the diagram: models, tools, stores, people and plain code.
- LLM calls
- 10. Model invocations in the first scenario: each time a model or agent node starts thinking, plus each branch it decides.
- Tool calls
- 0. Messages sent to a tool node in the first scenario.
- Steps
- 6. Steps in the first scenario, with repeated steps counted every time they run.
- Scenarios
- 1. Distinct example runs you can switch between on the diagram.
- Loop
- yes. Whether the flow cycles back on itself until a condition is met.
- Parallel
- no. Whether two or more messages are in flight at the same time.
- Branch
- yes. Whether the flow takes one path out of several, chosen at run time.
- Human in the loop
- no. Whether a person appears as a node, to approve, correct or answer.
- Autonomy
- high. How much the model decides the control flow itself, from fixed code paths (low) to open-ended (high).
- Cost
- high. Relative token spend per request.
- Latency
- high. Relative wall-clock time per request.
Counted from the first scenario's timeline when the site is built.
Problem
An agent writing is_valid_bracket_seq(s) has many plausible first moves: count the brackets, use a stack, use a regular expression. A ReAct loop commits to one and keeps patching it. Reflexion learns from each failure, but it still retries in a straight line and never goes back to compare an earlier, more promising attempt. Tree of Thoughts compares alternatives, but only in the model’s head. Nothing runs, so a plausible-looking wrong answer scores as well as a right one.
How it works
Language Agent Tree Search, from Zhou et al., runs Monte Carlo tree search over the agent’s actions. Every node in the tree is a real state reached by real actions. The paper defines six operations: selection, expansion, evaluation, simulation, backpropagation and reflection.
The task becomes the root. The selector, plain code, walks down the tree, at each level picking the child with the best value plus a bonus for being rarely visited. That balance makes the search keep exploiting what works while still trying neglected branches.
The expander samples a few different next actions from the selected node: here, two candidate implementations. Each one runs for real in the environment, here a test runner with the visible tests. Candidate A, which only counts brackets, passes 2 of 4 because it accepts )(. Candidate B, a stack, passes 3 of 4 but returns False for the empty string.
The value step scores each child from 0 to 1. The paper blends a model’s judgement with a self-consistency score; for code, the test pass rate carries most of the signal. Then it backpropagates: every ancestor’s visit count goes up and its average absorbs the new score. Simulation, rolling a child forward until it reaches an end state, matters for multi-step tasks such as web navigation. Here each action is a whole program, so the paper skips simulation and backs up the child’s score straight away.
Both children are failed programs, so each goes to the reflector, which writes one lesson per failure into reflections: “counting alone accepts )(” and “an empty sequence is balanced”.
On the second rollout the selector follows the higher value down to B. The expander reads both saved lessons, writes a child that handles the empty string, and the tests all pass. The search stops and the code goes to the solution.
The World model (RAP) variant. RAP, from Hao et al., came first and drops the real environment. The same model plays two roles: one prompt proposes actions, another predicts the state each action leads to. The search runs entirely over imagined states. In a Blocksworld puzzle, the world model can say that “pick up blue” is illegal while red sits on top of it, without anyone touching a block. Use it when acting is impossible or costly, and accept that a wrong prediction leads the search astray with no environment to correct it.
When to use
- The environment gives honest feedback: tests, a web page, a game score, a checker.
- You can reset the environment or branch from a saved state, so siblings start from the same place.
- Accuracy matters more than cost, and a straight-line retry loop keeps getting stuck on its first idea.
When to avoid
- Actions cannot be undone, such as sending email, paying or deleting. You cannot branch from a state you cannot restore.
- The budget is tight. Each rollout costs several model calls plus environment runs.
- The first attempt usually works. ReAct or a few Reflexion trials are far cheaper.
Trade-offs
LATS spends calls to buy a search that can back out of bad decisions. It combines ideas you may already use, ReAct-style acting and Reflexion-style lessons, under a search policy that decides where to spend the next attempt. The price is heavy: rollouts multiply model calls, the environment must support resets, and the run is harder to follow than a loop because it jumps between branches. In exchange, a good early idea that failed on a detail gets revisited instead of abandoned.
Failure modes
- Overconfident value scores: the model rates a broken attempt highly and the search keeps returning to it. Ground the score in the environment’s feedback, such as tests passed, wherever you can.
- State leakage: siblings share an environment that was not reset, so one child’s side effects change another’s result. Snapshot or rebuild the state per node.
- Reward hacking on visible tests: code passes the tests the agent can see and fails the hidden ones. Keep a held-out check for the final answer.
- Runaway budget: without a rollout cap the search keeps exploring. Cap rollouts and children per expansion, and return the best node when the cap is hit.
Build it with your AI
Real environment
Paste this into Claude Code, Cursor, ChatGPT or any AI coding assistant.
Implement the Language Agent Tree Search pattern in this codebase, using the LLM client and language we already use.
## Goal
Find a sequence of actions that solves a task in an environment you can reset or branch, by running Monte Carlo tree search where a model proposes actions, the environment executes them, and a model scores the outcomes.
## How it works
1. Represent the search as a tree of nodes. Each node holds an environment state, the trajectory that reached it, a visit count and a running value; the root is the task.
2. Select: starting at the root, repeatedly pick the child with the highest UCT score (value plus an exploration bonus that shrinks with visits) until you reach a node that has not been expanded. Do this in code, not with a model.
3. Expand: call the model with the Expand prompt k times (default 2) to sample different next actions from that node, including every saved reflection in the prompt.
4. Act: run each sampled action in the environment from that node's state, such as executing the code against the visible tests, and record the observation as a new child node.
5. Simulate (multi-step tasks only): roll a new child forward to a terminal state by repeating expand and act with one sample per step. Skip this when one action is a complete answer, such as a whole program.
6. Evaluate: if the environment says a child solved the task, return its trajectory. Otherwise score it with the Value prompt; blend that score with a self-consistency score or, where tests exist, the test pass rate, and use the blend as the child's value.
7. Backpropagate: walk from each new child up to the root, adding one to each node's visit count and folding the child's value into each node's running average.
8. Reflect: for each child that ends in a terminal failure, call the model with the Reflection prompt, passing its trajectory and the environment's feedback, and save the reflection for every later expansion. Then start the next rollout at the select step.
## Prompts
### Expand prompt
```markdown
You are solving the task below step by step. Propose the next action.
<task>{{task}}</task>
<trajectory>{{trajectory_so_far}}</trajectory>
{{#if reflections}}
Earlier attempts failed. Lessons from them:
<reflections>{{reflections}}</reflections>
Do not repeat those mistakes.
{{/if}}
Think briefly about what is still missing, then give exactly one action
in this format: {{action_format}}
```
### Value prompt
```markdown
Judge how close this attempt is to solving the task.
<task>{{task}}</task>
<trajectory>{{trajectory}}</trajectory>
<latest_observation>{{observation}}</latest_observation>
Reason in two or three sentences about what is right and what is still wrong.
Then end with one line: SCORE: a number from 0 to 1, where 1 means solved.
```
### Reflection prompt
```markdown
This attempt failed. Work out why, so the next attempt avoids it.
<task>{{task}}</task>
<trajectory>{{trajectory}}</trajectory>
<feedback>{{environment_feedback}}</feedback>
In one or two sentences, name the specific mistake and what to do instead.
Do not write a solution.
```
## Stop rule
Stop as soon as the environment confirms a solution, or after a rollout budget (default 8). On the budget, return the trajectory of the highest-value node with a status saying no solution was confirmed.
## Requirements
- The environment must be resettable or snapshotable, because siblings start from the same state. Never run this over actions that cannot be undone.
- Cap rollouts (default 8) and children per expansion (default 2), and log the model calls and environment runs for each rollout.
- Parse the value prompt's score into a number between 0 and 1; if it does not parse, retry once, then score the child 0.
- Keep the tree, with visit counts and values, in a form you can dump to a log, so a run can be inspected after it ends.
- Add a test with a stub LLM and a fake test runner that fails both children of the first rollout and passes the child from the second; assert reflect was called twice, both lessons appear in every expand prompt of rollout 2, and the passing code is returned.
World model (RAP)
Paste this into Claude Code, Cursor, ChatGPT or any AI coding assistant.
Implement the Language Agent Tree Search pattern (World model (RAP) variant) in this codebase, using the LLM client and language we already use.
## Goal
Plan a sequence of actions toward a goal without touching a real environment, by running Monte Carlo tree search where a model proposes actions, a model predicts the resulting state, and a reward scores progress.
## How it works
1. Represent the search as a tree whose nodes are predicted states, each with a visit count and a running value; the root is the starting state from the task.
2. Select: from the root, repeatedly pick the child with the highest UCT score until you reach a node that has not been expanded. Do this in code.
3. Expand: call the model with the Action proposal prompt to propose up to k (default 3) actions that are legal in the node's state.
4. Simulate: for each action, call the model with the World model prompt to predict the next state, and add it as a child. No real action is taken.
5. Reward: score each child with the Reward prompt, combined with any check in code (for example, how many goal conditions the predicted state already meets).
6. Backpropagate each child's reward up to the root, then start the next rollout; when a predicted state meets the goal, return the actions on its path.
## Prompts
### Action proposal prompt
```markdown
<goal>{{goal}}</goal>
<state>{{state}}</state>
List up to {{k}} different actions that are legal in this state and could
move toward the goal, one per line. Use only these action forms: {{action_forms}}
```
### World model prompt
```markdown
You simulate the environment. Given a state and an action, predict the new state.
<state>{{state}}</state>
<action>{{action}}</action>
If the action is not legal in this state, reply ILLEGAL and why.
Otherwise list every fact in the new state, one per line, and nothing else.
```
### Reward prompt
```markdown
<goal>{{goal}}</goal>
<state>{{state}}</state>
<plan_so_far>{{actions}}</plan_so_far>
Is this a good step toward the goal? Answer Yes or No on the first line,
then one sentence of reasoning.
```
## Stop rule
Stop when a predicted state meets every goal condition, or after a rollout budget (default 10). On the budget, return the highest-value path with a status saying the goal was not reached.
## Requirements
- Keep states as structured text (a list of facts) so a code check can test goal conditions instead of trusting the model.
- Cap rollouts (default 10), depth (default 6) and actions per expansion (default 3).
- Validate each predicted state against simple rules in code where you have them (a block cannot be in two places) and drop children that break them.
- Treat the plan as a proposal: if it will run in the real world, execute it step by step and replan when an observed state differs from the predicted one.
- Add a test with a stub LLM whose world model reports the goal met after the fourth action on one path; assert the returned plan is exactly the four actions on that path, in order.
Prompt templates
Real environment
You are solving the task below step by step. Propose the next action.
<task>{{task}}</task><trajectory>{{trajectory_so_far}}</trajectory>
{{#if reflections}}Earlier attempts failed. Lessons from them:<reflections>{{reflections}}</reflections>Do not repeat those mistakes.{{/if}}
Think briefly about what is still missing, then give exactly one actionin this format: {{action_format}}Judge how close this attempt is to solving the task.
<task>{{task}}</task><trajectory>{{trajectory}}</trajectory><latest_observation>{{observation}}</latest_observation>
Reason in two or three sentences about what is right and what is still wrong.Then end with one line: SCORE: a number from 0 to 1, where 1 means solved.This attempt failed. Work out why, so the next attempt avoids it.
<task>{{task}}</task><trajectory>{{trajectory}}</trajectory><feedback>{{environment_feedback}}</feedback>
In one or two sentences, name the specific mistake and what to do instead.Do not write a solution.World model (RAP)
<goal>{{goal}}</goal><state>{{state}}</state>
List up to {{k}} different actions that are legal in this state and couldmove toward the goal, one per line. Use only these action forms: {{action_forms}}You simulate the environment. Given a state and an action, predict the new state.
<state>{{state}}</state><action>{{action}}</action>
If the action is not legal in this state, reply ILLEGAL and why.Otherwise list every fact in the new state, one per line, and nothing else.<goal>{{goal}}</goal><state>{{state}}</state><plan_so_far>{{actions}}</plan_so_far>
Is this a good step toward the goal? Answer Yes or No on the first line,then one sentence of reasoning.Related patterns
Composes well with:
Sources
From the Agentic Atlas by Joran Kikke · Edit on GitHub · Suggest a correction