The classic algorithms inside modern AI agents, with runnable Python
A*, MCTS, beam search, bandits, policy gradients, constraint solving and topological sort: where each shows up in LLM agents, with papers and tiny Python code.
An LLM agent looks like a model in a loop calling tools. Look closer at the systems that score well on benchmarks and you find older computer science doing the hard parts. Tree of Thoughts runs breadth-first search over model outputs. LATS runs Monte Carlo tree search. LLMCompiler turns a plan into a dependency graph and runs it in topological order. GRPO, the RL method behind DeepSeek-R1, is a policy gradient with a different baseline.
This post covers seven of those algorithms. For each one you get the idea in a paragraph, where it appears in LLM agents (with the paper), and a pure-Python implementation of 30 to 50 lines with its real output. No API keys and no libraries: wherever a model would sit, a small stub function stands in, and the comments say where the real call goes. All seven scripts run on Python 3.9 or later.
If you want the control-flow side first (ReAct, plan-and-execute, reflection, routers), read AI agent architectures explained. This post is about the search, selection and learning algorithms those architectures call into.
where each algorithm sits in an agent
user goal
|
v
+-----------+ bandit (UCB / Thompson): which model or tool handles this?
| router |
+-----------+
|
v
+-----------+ A* / BFS over tool states, or LLM -> PDDL -> planner
| planner | constraint solver when the goal has hard rules
+-----------+
| task list with dependencies
v
+-----------+ topological sort: run independent tasks in parallel waves
| executor |
+-----------+
| candidate steps / answers
v
+-----------+ beam search, MCTS (ToT, LATS, RAP) with a verifier as reward
| search |
+-----------+
| rewards from tests, judges, users
v
+-----------+ policy gradient (PPO, GRPO): bake the good behaviour into weights
| training |
+-----------+
1. Breadth-first search and A* for planning#
The idea. Treat the agent's situation as a state (which facts it has, which files exist) and each tool call as an edge to a new state with a cost. Breadth-first search finds the plan with the fewest steps. A finds the cheapest plan by always expanding the state with the lowest g + h, where g is the cost paid so far and h is an estimate of the cost left. If h never overestimates, the first goal state A pops is optimal. With h = 0 A* becomes Dijkstra's algorithm.
Where it shows up. LLM+P has the model translate a natural-language task into PDDL, hands that file to a classical planner (a heuristic search engine), and translates the plan back. The authors report the combination finds optimal plans for most of their benchmark problems while the LLM alone fails to produce even feasible plans for most. Tree of Thoughts runs BFS and DFS over partial reasoning steps the model proposes and scores; on Game of 24 it lifted GPT-4 from 4% (chain of thought) to 74%.
Code. Five tools with preconditions, effects and latency. The goal is an email. BFS and A* disagree because the shortest plan is not the fastest one.
import heapq
from collections import deque
# Each tool: (name, needs, gives, cost in seconds)
TOOLS = [
("search_web", set(), {"urls"}, 2.0),
("fetch_pages", {"urls"}, {"pages"}, 6.0),
("search_kb", set(), {"pages"}, 9.0),
("summarise", {"pages"}, {"summary"}, 3.0),
("draft_email", {"summary"}, {"email"}, 1.0),
]
GOAL = {"email"}
def moves(state):
for name, needs, gives, cost in TOOLS:
if needs <= state and not gives <= state:
yield name, frozenset(state | gives), cost
def bfs(start):
q, seen = deque([(start, [])]), {start}
while q:
s, plan = q.popleft()
if GOAL <= s:
return plan
for name, nxt, _ in moves(s):
if nxt not in seen:
seen.add(nxt); q.append((nxt, plan + [name]))
def h(state):
# admissible: every missing goal fact needs at least one tool, cheapest tool is 1.0 s
return 1.0 * len(GOAL - state)
def astar(start):
frontier = [(h(start), 0.0, sorted(start), start, [])]
best, expanded = {start: 0.0}, 0
while frontier:
f, g, _, s, plan = heapq.heappop(frontier)
expanded += 1
if GOAL <= s:
return plan, g, expanded
for name, nxt, cost in moves(s):
g2 = g + cost
if g2 < best.get(nxt, float("inf")):
best[nxt] = g2
heapq.heappush(frontier, (g2 + h(nxt), g2, sorted(nxt), nxt, plan + [name]))
cost = {t[0]: t[3] for t in TOOLS}
p = bfs(frozenset())
print("BFS plan:", p, "steps:", len(p), "seconds:", sum(cost[x] for x in p))
p, g, n = astar(frozenset())
print("A* plan:", p, "steps:", len(p), "seconds:", g, "nodes expanded:", n)
Output:
BFS plan: ['search_kb', 'summarise', 'draft_email'] steps: 3 seconds: 13.0
A* plan: ['search_web', 'fetch_pages', 'summarise', 'draft_email'] steps: 4 seconds: 12.0 nodes expanded: 6
BFS picks the three-step route through the slow knowledge base (13 s). A* finds the four-step web route that finishes in 12 s, after expanding six states. The heuristic charges 1 s per missing goal fact, which is admissible because every tool costs at least 1 s and each missing fact needs at least one tool.
Failure mode. Search is only as good as the action model. If the LLM writes the preconditions or the PDDL, a wrong precondition gives you an optimal plan for the wrong world. Validate generated domain files against a few hand-checked cases before trusting the planner's output.
2. Monte Carlo tree search#
The idea. When you cannot score a partial path, only a finished one, MCTS builds the tree by sampling. Each iteration has four steps. Selection walks down the tree picking children by UCT: average reward plus c * sqrt(ln N_parent / N_child), which favours children that look good or have been tried rarely. Expansion adds one new child. Simulation plays random moves to the end and scores the result. Backpropagation adds that score to every node on the path. After enough iterations, the most visited child is the move to make.
Where it shows up. LATS runs MCTS where nodes are agent states, children are actions the LLM proposes, the value comes from an LLM evaluator plus environment feedback, and failed branches produce written self-reflections. It reports 92.7% pass@1 on HumanEval with GPT-4. RAP uses the LLM both as the world model that predicts the next state and as the reasoning agent, and searches with MCTS.
Code. The task is to reach 24 from 3 in exactly three operations. The reward function plays the role of a unit test or verifier: 1.0 for an exact hit, partial credit for getting close.
import math, random
random.seed(0)
# Toy task: reach exactly 24 from 3 by applying 3 operations.
# In LATS the "actions" are LLM-proposed thoughts or tool calls and the
# reward is a verifier or test result. Here both are plain functions.
OPS = {"+3": lambda x: x + 3, "*2": lambda x: x * 2, "-1": lambda x: x - 1, "*3": lambda x: x * 3}
DEPTH, TARGET = 3, 24
def reward(x): # stand-in for a verifier / unit test / LLM judge
return 1.0 if x == TARGET else max(0.0, 1 - abs(x - TARGET) / TARGET) * 0.5
class Node:
def __init__(self, value, depth, parent=None, op=None):
self.value, self.depth, self.parent, self.op = value, depth, parent, op
self.children, self.visits, self.total = {}, 0, 0.0
def untried(self):
return [o for o in OPS if o not in self.children] if self.depth < DEPTH else []
def uct(child, parent_visits, c=1.4):
return child.total / child.visits + c * math.sqrt(math.log(parent_visits) / child.visits)
def rollout(value, depth):
while depth < DEPTH:
value, depth = OPS[random.choice(list(OPS))](value), depth + 1
return reward(value)
def mcts(iterations):
root = Node(3, 0)
for _ in range(iterations):
node = root
while not node.untried() and node.children: # 1 selection
node = max(node.children.values(), key=lambda ch: uct(ch, node.visits))
if node.untried(): # 2 expansion
op = random.choice(node.untried())
node.children[op] = Node(OPS[op](node.value), node.depth + 1, node, op)
node = node.children[op]
r = rollout(node.value, node.depth) # 3 simulation
while node: # 4 backpropagation
node.visits += 1; node.total += r; node = node.parent
path, node = [], root
while node.children:
node = max(node.children.values(), key=lambda ch: ch.visits)
path.append(node.op)
return root, path, node.value
for n in (20, 200):
root, path, end = mcts(n)
visits = {op: ch.visits for op, ch in root.children.items()}
print(f"iterations={n:<4} root visits={visits} best path={path} -> {end}")
Output:
iterations=20 root visits={'*3': 6, '*2': 4, '-1': 5, '+3': 5} best path=['*3', '*3', '*2'] -> 54
iterations=200 root visits={'*2': 44, '+3': 40, '-1': 18, '*3': 98} best path=['*3', '-1', '*3'] -> 24
With 20 iterations the tree has barely been explored past depth one and the best path lands on 54. With 200 it finds 3 * 3 - 1 = 8, 8 * 3 = 24. In an LLM agent each iteration costs at least one model call to expand and one to evaluate, so 200 iterations is 400 calls for one decision. Use it where a test can score the result, such as code generation, not for a chat reply.
Failure mode. A noisy reward. If the LLM judge gives 0.7 to wrong answers half the time, MCTS will happily concentrate visits on a wrong branch. Prefer rewards from execution (tests pass, SQL returns the expected rows) over model opinions.
3. Beam search#
The idea. Greedy decoding keeps the single best next step. Beam search keeps the top k partial sequences by total log-probability, extends each by every option, and keeps the top k again. It trades k times the compute for a better chance of finding a sequence whose first step looked worse but whose total is higher. With k = 1 it is greedy.
Where it shows up. In agents it runs over reasoning steps rather than tokens. Self-evaluation guided beam search scores each step with the model's own judgement and reports gains of 6.34%, 9.56% and 5.46% on GSM8K, AQuA and StrategyQA over Codex baselines. Process reward models such as the one trained in Let's Verify Step by Step are the usual scorer when you can afford one. ToT's BFS with a breadth limit is beam search over thoughts.
Code. A stub "model" gives the probability of the next agent step. Greedy takes grep first because 0.55 beats 0.45, and then has no good follow-up.
import math
# Stub "model": probability of the next step given the steps so far.
# In a real agent this is the LLM's logprobs, or an LLM/PRM score per reasoning step.
TABLE = {
(): {"grep": 0.55, "read_file": 0.45},
("grep",): {"edit": 0.30, "read_file": 0.35, "run_tests": 0.35},
("read_file",): {"edit": 0.90, "grep": 0.10},
("grep", "edit"): {"<done>": 1.0},
("grep", "read_file"): {"<done>": 1.0},
("grep", "run_tests"): {"<done>": 1.0},
("read_file", "edit"): {"<done>": 1.0},
("read_file", "grep"): {"<done>": 1.0},
}
def next_steps(seq):
return TABLE.get(tuple(seq), {"<done>": 1.0})
def beam_search(width, max_len=3):
beams = [([], 0.0)] # (sequence, log-prob)
for _ in range(max_len):
cand = []
for seq, lp in beams:
if seq and seq[-1] == "<done>":
cand.append((seq, lp)); continue
for tok, p in next_steps(seq).items():
cand.append((seq + [tok], lp + math.log(p)))
beams = sorted(cand, key=lambda b: b[1], reverse=True)[:width]
return beams
for w in (1, 2):
seq, lp = beam_search(w)[0]
print(f"width={w}: {' -> '.join(seq)} p={math.exp(lp):.3f}")
Output:
width=1: grep -> read_file -> <done> p=0.192
width=2: read_file -> edit -> <done> p=0.405
Width 2 keeps read_file alive long enough to find the 0.405 sequence, more than twice the greedy one's 0.192.
Failure mode. Beams collapse into near-duplicates that differ in one word, so width 5 buys you one idea five times. Add a diversity penalty or deduplicate candidates by their normalised content before ranking.
4. Multi-armed bandits for routing and model selection#
The idea. You have k options with unknown payoffs and must pick one per request, learning as you go. UCB1 picks the arm with the highest mean plus sqrt(2 ln t / n), an optimism bonus that shrinks as an arm is tried. Thompson sampling keeps a Beta distribution per arm, draws a sample from each, and picks the highest draw, so arms are chosen in proportion to the chance they are best. A tutorial on Thompson sampling is the clearest primary reference.
Where it shows up. Model routing is the obvious fit: cheap model, mid model, expensive model, and a reward that mixes quality and cost. RouteLLM and Hybrid LLM train a classifier router offline from preference data, and RouteLLM reports cost cut by over 2x in some settings without losing quality. A bandit is the online version: no training set, it learns from live feedback.
Code. Three models with made-up success rates and costs. Reward is success minus 0.03 per unit of cost.
import math, random
random.seed(7)
# Three models behind a router. Success rates are made up for the simulation;
# in production "success" is a thumbs-up, a passing test, or a judge score.
MODELS = {"small": (0.62, 0.2), "medium": (0.80, 1.0), "large": (0.86, 5.0)} # (p_success, cost per call)
LAMBDA = 0.03 # how many units of success one unit of cost is worth
def pull(name):
p, cost = MODELS[name]
return (1.0 if random.random() < p else 0.0) - LAMBDA * cost
def ucb1(rounds):
n = {m: 0 for m in MODELS}; s = {m: 0.0 for m in MODELS}
for t in range(1, rounds + 1):
untried = [m for m in MODELS if n[m] == 0]
m = untried[0] if untried else max(MODELS, key=lambda m: s[m]/n[m] + math.sqrt(2*math.log(t)/n[m]))
s[m] += pull(m); n[m] += 1
return n, sum(s.values())
def thompson(rounds):
a = {m: 1 for m in MODELS}; b = {m: 1 for m in MODELS}; n = {m: 0 for m in MODELS}; total = 0.0
for _ in range(rounds):
m = max(MODELS, key=lambda m: random.betavariate(a[m], b[m]) - LAMBDA * MODELS[m][1])
p, cost = MODELS[m]
win = random.random() < p
a[m] += win; b[m] += not win; n[m] += 1
total += win - LAMBDA * cost
return n, total
true = {m: p - LAMBDA * c for m, (p, c) in MODELS.items()}
print("true value per call:", {m: round(v, 3) for m, v in true.items()})
for name, algo in (("UCB1", ucb1), ("Thompson", thompson)):
n, total = algo(2000)
print(f"{name:<9} calls={n} avg reward={total/2000:.3f}")
print(f"always-best avg reward={max(true.values()):.3f}")
Output:
true value per call: {'small': 0.614, 'medium': 0.77, 'large': 0.71}
UCB1 calls={'small': 198, 'medium': 1224, 'large': 578} avg reward=0.735
Thompson calls={'small': 40, 'medium': 1738, 'large': 222} avg reward=0.748
always-best avg reward=0.770
The best arm is medium (0.77 per call), not large, once cost counts. Over 2,000 requests Thompson sampling sends it 87% of traffic and reaches 0.748 per call, within 3% of an oracle that knew the answer from the start. UCB1 explores more and gets 0.735.
Failure mode. Plain bandits ignore the request. A hard legal question and "hi" get the same arm. The fix is a contextual bandit (features of the query feed the choice) or a trained router like RouteLLM's. Sparse feedback is the second problem: if 2% of users vote, the bandit learns from a skewed sample, so log the arm and reward per request.
5. Policy gradients, from REINFORCE to RLHF and GRPO#
The idea. A policy is a probability distribution over actions. REINFORCE nudges the log-probability of each sampled action up in proportion to its advantage, the reward minus a baseline. The baseline does not change the expected gradient but cuts its variance. PPO (Schulman et al.) adds a clipped ratio so one update cannot move the policy too far, and uses a learned value network as the baseline. For an LLM, the policy is the model, an action is a whole sampled response, and the reward comes from a reward model or a checker.
Where it shows up. InstructGPT trained a reward model on human rankings and then optimised the LLM against it with PPO: the RLHF recipe. GRPO, introduced with DeepSeekMath, drops the value network. It samples a group of responses to the same prompt and uses each response's reward, normalised by the group mean and standard deviation, as its advantage. That saves the memory of a second large network. DeepSeek-R1 used GRPO with rule-based rewards to train reasoning. To run it on a real model, Hugging Face TRL has a GRPOTrainer; the fine-tuning cheat sheet covers when to pick it over SFT or DPO.
Code. The policy is a softmax over four canned answers. A group of eight samples per step, a rule-based reward, group-normalised advantages, and the REINFORCE gradient of a softmax.
import math, random
random.seed(1)
# A "policy" over 4 canned answers to one prompt. A real LLM policy is a
# distribution over token sequences; the update rule below is the same idea.
ANSWERS = ["42", "forty-two", "I think 41", "no idea"]
def reward(ans): # rule-based verifier, as in GRPO maths training
return 1.0 if ans in ("42", "forty-two") else 0.0
logits = [0.0, 0.0, 0.0, 0.0]
def probs():
z = [math.exp(l) for l in logits]; s = sum(z); return [x / s for x in z]
LR, GROUP = 0.5, 8
print("step 0 ", [round(p, 2) for p in probs()])
for step in range(1, 31):
p = probs()
group = random.choices(range(4), weights=p, k=GROUP) # sample G answers to the same prompt
r = [reward(ANSWERS[i]) for i in group]
mean = sum(r) / GROUP
std = (sum((x - mean) ** 2 for x in r) / GROUP) ** 0.5 or 1.0
adv = [(x - mean) / std for x in r] # group-relative advantage, no critic
grad = [0.0] * 4
for i, a in zip(group, adv): # REINFORCE: grad log pi(i) = onehot(i) - p
for k in range(4):
grad[k] += a * ((1.0 if k == i else 0.0) - p[k]) / GROUP
logits = [l + LR * g for l, g in zip(logits, grad)]
if step in (5, 15, 30):
print(f"step {step:<2}", [round(x, 2) for x in probs()], "mean reward", round(mean, 2))
Output:
step 0 [0.25, 0.25, 0.25, 0.25]
step 5 [0.35, 0.36, 0.15, 0.14] mean reward 0.88
step 15 [0.36, 0.52, 0.06, 0.06] mean reward 1.0
step 30 [0.41, 0.55, 0.02, 0.02] mean reward 1.0
Probability on the two wrong answers falls from 0.25 each to 0.02. Note what happens after step 15: the mean reward is 1.0, every sample in the group is correct, all advantages are zero, and learning slows down sharply. GRPO only learns from groups that contain both successes and failures. On a real model this is the same trap from the other side: prompts that are always solved or never solved contribute no gradient, so curate prompts the model solves some of the time.
Failure mode. Reward hacking. The policy maximises the reward you wrote, not the one you meant. A checker that accepts any string containing "42" will teach the model to write "42" everywhere. Test your reward function against adversarial outputs before training.
Q-learning and DQN, the other RL classics, rarely appear inside LLM agents. The action space of a language model is too large for a Q-table, and policy-gradient methods map directly onto sampling text, so that is where the field went.
6. Constraint solving#
The idea. A constraint satisfaction problem has variables, a domain of values for each, and constraints that rule out combinations. Backtracking assigns one variable at a time, checks the constraints on the partial assignment, and undoes the last choice when it hits a dead end. Choosing the variable with the fewest remaining values first (the MRV heuristic) prunes failures early.
Where it shows up. LLMs are poor at holding six hard rules in their heads at once, and solvers are perfect at it. Logic-LM has the LLM translate a problem into a symbolic form, runs a solver, and feeds solver errors back to fix the translation; it reports average gains of 39.2% over standard prompting and 18.4% over chain of thought across five logic datasets. SatLM does the same with a SAT solver. In a product agent, this is the scheduling, rostering or configuration tool the model calls instead of guessing.
Code. A meeting request with three meetings, four slots, one attendee in every meeting, one attendee with limited days and an ordering rule.
# Backtracking constraint solver for a scheduling request an agent might get:
# "Book design review, standup and 1:1 this week, no overlaps, Priya only free Tue/Wed,
# 1:1 must be after design review."
SLOTS = ["Mon10", "Tue10", "Tue14", "Wed10"]
ORDER = {s: i for i, s in enumerate(SLOTS)}
VARS = {"design_review": SLOTS, "standup": ["Mon10", "Tue10", "Wed10"], "one_on_one": SLOTS}
PEOPLE = {"design_review": {"priya", "raj"}, "standup": {"raj", "dev"}, "one_on_one": {"priya", "raj"}}
PRIYA_FREE = {"Tue10", "Tue14", "Wed10"}
def ok(a):
vals = list(a.values())
if len(vals) != len(set(vals)):
return False # raj is in everything, so no shared slots
for m, s in a.items():
if "priya" in PEOPLE[m] and s not in PRIYA_FREE:
return False
if "design_review" in a and "one_on_one" in a:
return ORDER[a["design_review"]] < ORDER[a["one_on_one"]]
return True
calls = 0
def solve(a=None):
global calls; calls += 1
a = a or {}
if len(a) == len(VARS):
return a
var = min((v for v in VARS if v not in a), key=lambda v: len(VARS[v])) # fewest options first
for val in VARS[var]:
a2 = {**a, var: val}
if ok(a2):
res = solve(a2)
if res: return res
return None
print(solve(), "search calls:", calls)
Output:
{'standup': 'Mon10', 'design_review': 'Tue10', 'one_on_one': 'Tue14'} search calls: 4
Four calls find a schedule that meets every rule. In the agent, the model fills in VARS, PEOPLE and the rules from the user's message and a calendar API; the solver guarantees no overlap.
Failure mode. No solution. Over-constrained requests are common ("all three meetings Tuesday morning"). The solver returns None and the agent must say which constraint to relax, so make the solver report the conflicting constraints, not only failure.
7. Topological sort for task DAGs#
The idea. A plan with dependencies is a directed acyclic graph. Kahn's algorithm counts incoming edges for every task, starts with the tasks at zero, and each time a task finishes it decrements its dependents; any that reach zero are ready. Taking all ready tasks at once gives you waves that can run in parallel. If tasks remain when nothing is ready, the graph has a cycle. Python ships this as graphlib.TopologicalSorter since 3.9, with get_ready() and done() for exactly this pattern.
Where it shows up. LLMCompiler has a planner LLM emit a DAG of function calls, then a task-fetching unit dispatches each call once its inputs are ready, in parallel. Against ReAct it reports latency up to 3.7x lower, cost up to 6.7x lower and accuracy up to about 9% higher. Any plan-and-execute agent that lets the planner name dependencies needs this step; the task planning agent in Python post builds one end to end.
Code. A travel plan as the planner might emit it in JSON, plus a broken plan with a cycle.
from collections import deque
# Task DAG a planner LLM might emit as JSON: task -> tasks it depends on
PLAN = {
"search_flights": [], "search_hotels": [], "check_visa": [],
"pick_dates": ["search_flights", "check_visa"],
"book_hotel": ["pick_dates", "search_hotels"],
"book_flight": ["pick_dates"],
"email_itinerary": ["book_hotel", "book_flight"],
}
def waves(plan):
indeg = {t: len(d) for t, d in plan.items()}
users = {t: [] for t in plan}
for t, deps in plan.items():
for d in deps:
if d not in plan: raise ValueError(f"{t} depends on unknown task {d}")
users[d].append(t)
ready, out, done = deque(t for t, n in indeg.items() if n == 0), [], 0
while ready:
wave = list(ready); ready.clear(); out.append(wave); done += len(wave)
for t in wave:
for u in users[t]:
indeg[u] -= 1
if indeg[u] == 0: ready.append(u)
if done != len(plan):
raise ValueError(f"cycle among: {[t for t, n in indeg.items() if n > 0]}")
return out
for i, w in enumerate(waves(PLAN), 1):
print(f"wave {i}: {w}")
try:
waves({"a": ["b"], "b": ["a"], "c": []})
except ValueError as e:
print("rejected plan:", e)
Output:
wave 1: ['search_flights', 'search_hotels', 'check_visa']
wave 2: ['pick_dates']
wave 3: ['book_hotel', 'book_flight']
wave 4: ['email_itinerary']
rejected plan: cycle among: ['a', 'b']
Seven tasks run in four waves instead of seven sequential steps. If each tool call takes two seconds, that is 8 s instead of 14 s. The second plan is rejected before any tool runs.
Failure mode. The planner LLM will sometimes emit cycles, self-dependencies or references to tasks it never defined. Check the graph before executing it (the script raises on both) and send the error back to the planner for one retry.
How to test these inside an agent#
Each algorithm is deterministic code around a non-deterministic model, so the code part is easy to test.
- Fix the stub, test the algorithm. Every script above uses a stub where the model goes. Keep that seam in production code and unit-test the search with stubs that have a known best answer: A* must return the 12 s plan, beam width 2 must return the 0.405 sequence, the cycle check must raise.
- Count model calls per decision. MCTS and beam search multiply calls. Log calls and tokens per user task and set a hard budget, the way you would cap retries.
- Score the reward or verifier on its own. Before trusting MCTS, a bandit or GRPO, run the reward function on 50 labelled outputs and measure how often it agrees with a human. A 70% accurate judge sets the ceiling for everything built on top.
- Compare against the plain loop. Run the same eval set through a ReAct loop with no search. If search does not beat it by more than the extra cost, ship the loop. The agent evaluation guide has a harness for that comparison.
Which one to reach for#
| Problem in your agent | Algorithm | Cost |
|---|---|---|
| Find the cheapest sequence of tool calls with known effects | A* or a classical planner | Cheap once the model writes the domain |
| Many candidate paths, only finished ones can be scored | MCTS | Many model calls per decision |
| Step-by-step reasoning with a per-step scorer | Beam search | k times the calls of greedy |
| Pick a model, prompt or tool variant from live feedback | Thompson sampling or UCB1 | Near zero |
| Make good behaviour permanent in the weights | GRPO or PPO | GPU training run |
| Hard rules the answer must satisfy | Constraint solver | Cheap; translation is the risk |
| Plan with dependencies, run fast | Topological sort | Free |
Start with the bottom of the table. Topological sort, a constraint solver and a bandit router are cheap and deterministic and fix real latency, correctness and cost problems. Tree search and RL training pay off when you have a verifier you trust.
Sources#
- Liu et al., LLM+P: Empowering Large Language Models with Optimal Planning Proficiency, 2023.
- Yao et al., Tree of Thoughts: Deliberate Problem Solving with Large Language Models, 2023.
- Zhou et al., Language Agent Tree Search Unifies Reasoning Acting and Planning in Language Models, 2023.
- Hao et al., Reasoning with Language Model is Planning with World Model, 2023.
- Xie et al., Self-Evaluation Guided Beam Search for Reasoning, 2023.
- Lightman et al., Let's Verify Step by Step, 2023.
- Russo et al., A Tutorial on Thompson Sampling, 2017.
- Ong et al., RouteLLM: Learning to Route LLMs with Preference Data, 2024.
- Ding et al., Hybrid LLM: Cost-Efficient and Quality-Aware Query Routing, 2024.
- Schulman et al., Proximal Policy Optimization Algorithms, 2017.
- Ouyang et al., Training language models to follow instructions with human feedback, 2022.
- Shao et al., DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models, 2024.
- DeepSeek-AI, DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning, 2025.
- Hugging Face TRL, GRPO Trainer documentation.
- Pan et al., Logic-LM: Empowering Large Language Models with Symbolic Solvers for Faithful Logical Reasoning, 2023.
- Ye et al., SatLM: Satisfiability-Aided Language Models Using Declarative Prompting, 2023.
- Kim et al., An LLM Compiler for Parallel Function Calling, 2023.
- Python documentation, graphlib: functionality to operate with graph-like structures.