Planning and Search Algorithms

Classical ways of choosing a route to a goal, and how they combine with language models.

BeginnerIntermediateExpert · 12 min read · Last updated:

In short

Planning means choosing actions that lead from the current state to a goal. Search explores possible routes; a heuristic guides it. A* finds cheapest routes, Monte Carlo tree search balances trying new options with reusing good ones, hierarchical planning breaks tasks down by known methods, and GOAP chains actions by their preconditions and effects. Let models propose and interpret; let algorithms guarantee what can be guaranteed.

What you will learn: the vocabulary of planning, the main search algorithms, tree search with language models, hierarchical and goal-oriented planning, and how to choose.
Prerequisites: How Agents Reason and Decompose Tasks and basic Python. Math, Search and Algorithms for Agent Engineers gives more background.

Beginner States, actions and goals

The vocabulary

TermMeaningSupport example
StateWhat is true nowTicket open; cause unknown
ActionA step that changes the stateRead the logs
PreconditionWhat must be true before an actionA ticket exists
EffectWhat becomes true afterwardCause known
CostTime, money or risk of an actionThree minutes
GoalThe condition to reachFault fixed
HeuristicAn estimate of remaining costRoughly two steps to go

The possible states and actions form a tree or graph. Planning is finding a path through it. The difficulty is size: with 3 choices at each step and 5 steps, there are already 3 + 9 + 27 + 81 + 243 = 363 nodes. With 20 choices and 10 steps, examining everything is out of the question.

The main search methods

MethodChooses nextStrengthWeakness
Breadth-firstShallowest optionFinds the fewest stepsMemory grows quickly
Depth-firstDeepest optionLittle memoryCan wander far down a bad branch
Uniform-costCheapest path so farFinds the cheapest routeNo sense of direction
Greedy best-firstLooks closest to the goalFastEasily misled
A*Cost so far plus estimateCheapest route, guidedNeeds a sound estimate; memory
Beam searchKeeps the best few at each depthBounded costMay discard the winner
Monte Carlo tree searchBalances promise and uncertaintyWorks with only trial outcomesNeeds many trials

Greedy search against A*

Greedy search takes whatever looks closest to done. A* also counts what has already been spent. On this small graph the difference is large:

"""Greedy search and A* on the same task graph."""
import heapq

# state: [(next state, cost)]
GRAPH = {
    "start":  [("quick", 1), ("steady", 4)],
    "quick":  [("patch", 9)],
    "steady": [("tested", 3)],
    "patch":  [("done", 6)],
    "tested": [("done", 2)],
    "done":   [],
}
# Estimated remaining cost. It never overestimates, which A* relies on.
ESTIMATE = {"start": 4, "quick": 3, "steady": 5, "patch": 4,
            "tested": 2, "done": 0}

def search(use_cost_so_far):
    frontier = [(ESTIMATE["start"], 0, "start", ["start"])]
    seen = {}
    while frontier:
        _, cost, state, path = heapq.heappop(frontier)
        if state == "done":
            return path, cost, len(seen)
        if state in seen and seen[state] <= cost:
            continue
        seen[state] = cost
        for nxt, step in GRAPH[state]:
            total = cost + step
            priority = ESTIMATE[nxt] + (total if use_cost_so_far else 0)
            heapq.heappush(frontier, (priority, total, nxt, path + [nxt]))

if __name__ == "__main__":
    for name, flag in (("greedy", False), ("A*", True)):
        path, cost, expanded = search(flag)
        print(f"{name:<7} cost {cost:>2}  expanded {expanded}  "
              + " > ".join(path))

Output:

greedy  cost 16  expanded 3  start > quick > patch > done
A*      cost  9  expanded 4  start > steady > tested > done

The "quick" branch looks near the goal but hides an expensive patch. A* examines one more state and returns a much cheaper route. Its guarantee depends on the estimate being admissible, which means never higher than the true remaining cost. With an estimate that overstates costs, the search may miss the best path.

Intermediate Search with language models

In many agent tasks nobody has listed the actions or written a heuristic. A language model can fill both roles: propose a few candidate next steps and score the resulting states. Tree of Thoughts applies this to reasoning: it keeps several partial solutions, evaluates them, and continues or backtracks instead of following a single chain.

Current state
Proposeseveral next steps
Evaluatetests, rules or a model
Keep the bestdrop the rest
↺ Expand again until the goal or the budget is reached
The evaluator decides the quality of the whole search.

A search is only as good as its evaluator. Compilers, tests and rule checkers give dependable signals. A model's opinion of its own proposal is much weaker.

Monte Carlo tree search

Monte Carlo tree search (MCTS) builds a tree gradually in four repeated phases: select a promising node, expand it with new actions, simulate or evaluate an outcome, and back up the result to the nodes above. Selection often uses a rule called UCB1, which adds a bonus for options tried rarely:

"""The selection rule inside many tree searches: UCB1."""
import math
import random

# True chance that each approach succeeds. The searcher cannot see this.
TRUE = {"rewrite query": 0.35, "read the file": 0.70, "ask the user": 0.50}

def choose(stats, total, c=1.4):
    for name, (wins, tries) in stats.items():
        if tries == 0:
            return name                       # try everything once
    return max(stats, key=lambda n: stats[n][0] / stats[n][1]
               + c * math.sqrt(math.log(total) / stats[n][1]))

if __name__ == "__main__":
    random.seed(3)
    stats = {name: [0, 0] for name in TRUE}
    for total in range(1, 301):
        name = choose(stats, total)
        stats[name][0] += random.random() < TRUE[name]
        stats[name][1] += 1
        if total in (10, 50, 300):
            summary = ", ".join(f"{n} {t}" for n, (_, t) in stats.items())
            print(f"after {total:>3} tries: {summary}")

Output:

after  10 tries: rewrite query 2, read the file 5, ask the user 3
after  50 tries: rewrite query 7, read the file 28, ask the user 15
after 300 tries: rewrite query 32, read the file 208, ask the user 60

The searcher does not know the success rates. It starts evenly and moves effort toward the approach that keeps working, while still testing the others occasionally. This script shows only the selection rule on one level, not a full tree.

Language Agent Tree Search (LATS) brings MCTS to agents: the model proposes actions and estimates value, the environment gives external feedback, and reflections on failed paths guide later ones. It reported strong results on programming and question-answering tasks, at the price of many model calls.

Search needs a place where actions can be undone

Exploring alternatives means trying actions you may abandon. Do this only in a sandbox, a simulator or with read-only tools. You cannot backtrack a sent email or a payment. See Code Execution and Sandboxing.

Hierarchical planning

Hierarchical task network (HTN) planning starts from a high-level task and replaces it with smaller tasks using known methods, until only directly executable actions remain. Each method can have conditions.

Onboard employee
Create accountsdirectory, email, access groups
Provide equipmentchoose by role, order, ship
Arrange inductionschedule, materials, mentor
Known procedures become methods; a model may choose among them.

HTN planning suits organizations with established procedures, because the result stays inside methods someone approved. A language model can be used to understand the request and pick a method, while the structure prevents invented steps.

Goal-oriented action planning

GOAP, popularized in video games by Jeff Orkin, describes each action by its preconditions, effects and cost. The planner searches for the cheapest chain that makes the goal true. Add or remove actions and the plan adapts with no new branching logic.

"""Goal-oriented action planning: actions have needs, effects and a cost."""
import heapq
from itertools import count

ACTIONS = [
    # name, needs, adds, removes, cost
    ("open ticket",    set(),                    {"ticket"},  set(), 1),
    ("read logs",      {"ticket"},               {"cause"},   set(), 3),
    ("guess a fix",    {"ticket"},               {"patch"},   set(), 6),
    ("write fix",      {"cause"},                {"patch"},   set(), 2),
    ("run tests",      {"patch"},                {"tested"},  set(), 1),
    ("get approval",   {"tested"},               {"approved"}, set(), 2),
    ("deploy",         {"tested", "approved"},   {"fixed"},   set(), 1),
]

def plan(state, goal, actions):
    """Cheapest sequence of actions that makes every goal fact true."""
    order = count()
    queue = [(0, next(order), frozenset(state), [])]
    best = {}
    while queue:
        cost, _, facts, steps = heapq.heappop(queue)
        if goal <= facts:
            return steps, cost
        if best.get(facts, 10**9) <= cost:
            continue
        best[facts] = cost
        for name, needs, adds, removes, price in actions:
            if needs <= facts and not adds <= facts:
                new = (facts - removes) | adds
                heapq.heappush(queue, (cost + price, next(order), new,
                                       steps + [name]))
    return None, None

if __name__ == "__main__":
    steps, cost = plan(set(), {"fixed"}, ACTIONS)
    print(f"cost {cost}: " + " > ".join(steps))
    no_logs = [a for a in ACTIONS if a[0] != "read logs"]
    steps, cost = plan(set(), {"fixed"}, no_logs)
    print(f"logs unavailable, cost {cost}: " + " > ".join(steps))
    no_approver = [a for a in ACTIONS if a[0] != "get approval"]
    print("no approver:", plan(set(), {"fixed"}, no_approver)[0])

Output:

cost 10: open ticket > read logs > write fix > run tests > get approval > deploy
logs unavailable, cost 11: open ticket > guess a fix > run tests > get approval > deploy
no approver: None

When logs are unavailable the planner quietly switches to guessing a fix, which is valid according to the rules it was given. If guessing is unacceptable, say so in the model of the world, for example by requiring a known cause before deployment. When no approver is available, no plan exists, and that is the correct answer.

Expert Choosing and combining

Combining models and planners

Language models are good at turning messy requests into structured descriptions. Classical planners are good at producing valid plans from them. One line of research, such as LLM+P, has the model translate a problem into a formal planning language, runs a standard planner, and translates the result back. The plan is then only as correct as the translation, so validate it.

This division matters because models can be unreliable planners on their own. PlanBench, built from classical planning domains, was designed to test this, and its authors found plan generation fell well short in the models they studied. Their later evaluation of newer reasoning models reported progress alongside remaining limits. Test the model you use rather than assuming either way.

Which method when

SituationReasonable choice
Steps always the sameA fixed workflow; no planner
Known actions with clear effects and costsGOAP or A*
Approved procedures with variationsHierarchical planning
Unknown next steps, cheap reliable checksPropose and verify, beam search or tree search
Long exploratory work in a sandboxInterleaved action with replanning, occasional branching
Irreversible actionsPlan first, validate, obtain approval, then execute

Budget the search

With model-based search, every node may cost one or more calls. Estimate before building: three proposals per step over five steps is up to 363 nodes, and scoring each doubles the calls. Limit depth, width and total calls; cache repeated states; stop at the first solution that passes verification unless a cheaper plan is worth the extra search. See Agent Decisions: Confidence, Stopping, Loops and Budgets.

Keep the world model honest

A planner reasons over a description of the world. Reality differs: an action fails, another person changes a record, an estimate is wrong. Check preconditions again immediately before each action, compare actual effects with expected ones, and replan on mismatch. A plan is a hypothesis until the results confirm it.

Illustrative example: data repair

An invented operations agent must repair a broken nightly report. Its actions are described with preconditions, so it cannot rerun the load before validating the source. It searches several diagnoses against a copy of the data, picks the one whose tests pass, and then presents the single change for approval on the live system.

Verification beats cleverness

Spending effort on a sharper checker usually improves results more than a more elaborate search. With a weak evaluator, a bigger search simply finds more convincing mistakes.

How to compare planners on your task

Run each candidate method on the same set of problems, including some with no solution. Record five things: the share of problems solved with a valid plan, the cost of that plan compared with the best known one, model calls and time used, how often a plan failed during execution, and whether impossible problems were reported correctly. A method that solves two more problems but uses ten times the calls may not be the better choice.

Start with the simplest baseline: one attempt, checked, with one retry. Add search only if the baseline fails often enough to justify it, and keep the baseline in the comparison afterward, because a newer model may close the gap and let you remove the machinery.

Common mistakes

  • Using tree search where one well-checked attempt is enough.
  • Letting exploration touch real systems.
  • Leaving a rule out of the action model and being surprised when the planner ignores it.
  • Comparing methods on success alone and not on calls and time.
  • Treating a heuristic score from a model as if it were measured.
  • Failing to report that no valid plan exists.

Planning checklist

  • States, actions, preconditions, effects and goal are written down.
  • Hard rules are part of the action model or enforced in code.
  • The evaluator is as objective as the task allows.
  • Exploration happens only where actions can be undone.
  • Depth, width and call budgets are set.
  • Preconditions are rechecked at execution time.
  • "No plan found" is a handled result.

Frequently asked questions

Do I need these algorithms if I use a large model?

Often not for simple tasks. They help when plans must be valid, costs must be controlled or many routes need comparing.

What is the difference between HTN and GOAP?

HTN expands tasks using predefined methods. GOAP chains individual actions by what they need and produce. HTN gives more control; GOAP adapts more freely.

Is tree search expensive with language models?

Yes, because each node can need several calls. Use it where success is valuable and checkable, and set strict limits.

References and further reading

Next steps