02 / 27 · Agents and Environments
Search and planning
How a goal-based agent finds a sequence of actions before acting: problem formulation, breadth-first and uniform-cost search, A* with admissible and consistent heuristics and its optimality proof, STRIPS and PDDL planning, and why language-model planners reuse these ideas.
On this page 7
The previous note classified agents by how much they compute before acting. A goal-based agent is told which states it wants and works out how to reach them. When the world is fully observable, deterministic and known, this can be done entirely in advance: the agent imagines sequences of actions with its model of the world, finds one that ends in a goal, and then executes it without needing to look. Finding that sequence is search. This note formulates the search problem, solves it with three algorithms of increasing cleverness, proves that the last of them, A*, returns an optimal solution, and then describes the planning languages that let one formulation cover a whole family of problems. Both ideas come back later in the course, inside agents built on language models.
Notation. A state is , an action ; is the set of actions applicable in , the state they lead to, and the cost of the step. A node of a search is a state together with the path that reached it; is the cost of that path, the cost of the cheapest path to the state of , a heuristic estimate of the cheapest cost from to a goal, and that cheapest cost itself. is the cost of an optimal solution. is the branching factor (the number of successors of a node), the depth of the shallowest goal and the smallest step cost.
Formulating a problem#
A search problem has five parts (Russell and Norvig, 2021, section 3.1):
- a set of states, and an initial state ;
- a goal test, which says whether a state is a goal (a set of goal states, or a predicate);
- the actions available in each state;
- a transition model ;
- an action cost .
A solution is a sequence of actions that leads from to a goal state; an optimal solution has the smallest total cost . The states and actions form a directed graph, the state space, and every solution is a path in it. On a road map the states are towns, the actions are roads and the costs are lengths. In the 8-puzzle, eight numbered tiles on a 3 × 3 board with one blank, a state is an arrangement of the tiles, an action slides a tile into the blank, and every action costs 1; half of the arrangements can be reached from any given one, so the state space has states.
Formulating a problem is a choice of abstraction. A route planner leaves out the weather, the radio and the exact position of the wheel; an abstraction is good if every abstract solution can be turned into a real one and the abstract problem is much smaller than the real one.
A search algorithm explores the state space from without building it in full. It keeps a frontier of nodes that have been reached but not yet expanded, and repeatedly expands one: it removes it from the frontier and adds the nodes for all its successors. Since the same state can be reached by several paths, a graph search also remembers which states it has reached, and keeps only the cheapest known path to each. The algorithms below differ in one thing only: which frontier node they expand next.
Baseline: breadth-first search#
Breadth-first search expands the shallowest node first, with a first-in, first-out queue as the frontier. It reaches every state at depth 1 before any at depth 2, and so on, so the first goal it reaches lies at the smallest depth ; it can check the goal test as soon as a node is generated. When every action costs the same, the shallowest goal is also the cheapest one, and breadth-first search is optimal.
The price is memory. With successors per node, it generates
nodes and keeps all of them, because each reached state must be remembered. For and that is nodes, far more than a computer holds. And as soon as costs differ it is not optimal: a path of two expensive roads can be shallower than a path of three cheap ones.
Uniform-cost search#
Uniform-cost search expands the node with the smallest path cost , using a priority queue as the frontier. It is Dijkstra’s algorithm for shortest paths (Dijkstra, 1959), started from one source and stopped at the goal. Two details matter.
- The goal test is applied when a node is expanded, not when it is generated. On the graph of the figure below, uniform-cost search first reaches G through C with ; only later does it reach G through D with . Stopping at the first G it generates would return the worse path.
- Step costs must be positive, at least some . Then the costs of expanded nodes never decrease, the first goal expanded is optimal, and the search terminates. With zero-cost loops it could run forever; with negative costs Dijkstra’s argument fails.
Uniform-cost search is optimal for any positive costs, but it is blind: it spreads out from in every direction, in order of cost, whether or not the direction leads to the goal. Its work grows like .
A*: guessing the remaining cost#
A* search (Hart, Nilsson and Raphael, 1968) expands the frontier node with the smallest
an estimate of the cost of the cheapest solution that passes through . With it is uniform-cost search. Two properties of decide what A* guarantees:
- is admissible if it never overestimates: for every , and so at goals.
- is consistent if it satisfies a triangle inequality along every step:
Consistency implies admissibility. Take a cheapest path from to a goal and apply the inequality times: . The converse fails, but most admissible heuristics met in practice are consistent too.
Worked example. The graph has seven nodes; the heuristic, shown next to each node, is consistent on every edge:
A* on the graph of the worked example
- Expand S (, ). A enters the frontier with , B with . The tie goes to the deeper node, B.
- Expand B (, ). C enters with , , and E with , .
- Expand A (, ). D enters with , . A also offers a path to C, of cost 5, worse than the 4 already known, so it is discarded.
- Expand D (, ). G enters with , .
- Expand G: it is the goal, with cost 7, along S–A–D–G.
C and E are never expanded: their values, 8 and 10, are larger than . Uniform-cost search on the same graph expands all seven nodes.
Why A* returns an optimal solution#
The argument for graph search with a consistent heuristic has three steps.
Step 1: never decreases along a path. If is a successor of , then
Step 2: when A* expands a node, it has found the cheapest path to it. Suppose A* is about to expand a node with . Look at a cheapest path from to the state of . Its first node is expanded (it is ) and its last is not, so some node on it is on the frontier with all its predecessors on the path expanded; and since was reached along the cheapest path, . Then
so A* would have expanded before , a contradiction. Hence at expansion.
Step 3: the first goal expanded is optimal. Apply Step 2 to the first goal node A* expands: its is the cheapest cost to that goal. Any other goal reached later has, by Step 1, an at least as large, and at a goal because there. Hence
Two consequences follow. A* expands every node with , and none with : the set of expanded nodes is a contour of around the start, as in the figure where C and E lie outside the contour at . And no other optimal algorithm that is given the same heuristic and extends paths from the start can be sure of optimality while skipping a node with , because the remaining cost might be as low as promises; A* is optimally efficient in this sense, up to ties at (Russell and Norvig, 2021, section 3.5).
For tree search, which does not remember reached states, admissibility alone is enough. If a suboptimal goal with is on the frontier, some node of an optimal path is also on the frontier, and , so is expanded first; repeating the argument, the optimal goal is expanded before .
Where heuristics come from#
A good heuristic is the exact cost of a relaxed problem, one with some constraints removed. On a grid with walls, removing the walls gives the Manhattan distance . In the 8-puzzle, letting a tile move to any adjacent square, occupied or not, gives the sum of the tiles’ Manhattan distances to their places. A relaxed problem has more solutions, so its optimal cost cannot exceed the real one: the heuristic is admissible. It is also consistent, because it is the exact cost in a problem with the same moves and more freedom, and exact costs satisfy the triangle inequality.
If for every and both are admissible, dominates , and A* with never expands a node that A* with leaves alone (up to ties): every node with also has . The ideal heuristic is itself, which leads A* straight to the goal; it costs as much to compute as the problem it solves, and the art is to find a cheap function close to it.
Worked example: a grid. A 16 × 10 grid with walls, four moves of cost 1, from S to G. The same best-first search with , the Manhattan distance, is run with three weights:
How many cells the search expands under different heuristics
Uniform-cost search () expands 136 cells; A* () expands 80 and finds the same path of length 21. Breadth-first search, optimal here because all costs are 1, reaches 139 states before it stops. A weight gives weighted A* (Pohl, 1970): the heuristic counts more than the cost paid, the search becomes greedier, and is no longer a lower bound. With an admissible the cost it finds is at most . On the grid:
The weight on the heuristic: less work, longer paths
Weighted A* is the first instance of a trade-off that returns throughout the course, in the number of simulations of tree search and in the test-time compute of reasoning models: computation spent on search buys quality, and a strong but imperfect guide saves computation at the price of guarantees.
Classical planning: STRIPS and PDDL#
Each problem above came with its own code for and . Planning languages describe a whole family of problems with one factored representation, so that one general algorithm can solve all of them, and the description itself can be inspected to derive heuristics automatically.
In the STRIPS representation (Fikes and Nilsson, 1971), a state is a set of ground facts, such as on(C, A) and clear(B); every fact not in the set is false. An action schema has parameters and three lists of facts:
- preconditions, which must all hold for the action to apply;
- an add list of facts that become true;
- a delete list of facts that become false.
For an applicable action the transition model is set arithmetic:
PDDL, the Planning Domain Definition Language (McDermott et al., 1998), is the standard syntax for such descriptions, used by the International Planning Competition since 1998. A domain file defines the predicates and action schemas; a problem file lists the objects, the initial state and the goal. In the blocks world, blocks sit on a table or on each other and one clear block can be moved at a time. One of its three actions, written in PDDL:
(:action move-to-table
:parameters (?x ?y)
:precondition (and (on ?x ?y) (clear ?x))
:effect (and (on-table ?x) (clear ?y) (not (on ?x ?y))))
The other two move a clear block from a block or from the table onto another clear block. A problem:
(:init (on C A) (on-table A) (on-table B) (clear C) (clear B))
(:goal (and (on A B) (on B C)))
Worked example. Breadth-first search over the sets of facts, from this initial state, applies the 18 ground actions of three blocks and finds the three-step plan: move C to the table, move B onto C, move A onto B. It reaches all 13 states of the three-block world on the way, as the Code section prints. This little problem, the Sussman anomaly, is famous for another reason. A planner that achieves one goal at a time fails on it: putting A on B first means moving C off A and then A onto B, after which B cannot be put on C without taking A off again; putting B on C first buries A under C and B. The goals interact, and only a search over whole states finds the plan.
The number of states of the blocks world grows faster than exponentially: 13 for three blocks, 501 for five, 58,941,091 for ten. Planners therefore search with heuristics, and the factored form gives them for free. The most useful relaxation ignores the delete lists: once true, a fact stays true. The cost of the optimal relaxed plan, , is admissible but NP-hard to compute; its approximations, the admissible and the more informative but inadmissible and the FF heuristic, made heuristic forward search the dominant approach to classical planning (Bonet and Geffner, 2001; Hoffmann and Nebel, 2001).
Why this matters for language-model planners#
A language model asked to plan in text does none of this explicitly: it writes a plan in one pass, without a frontier, without a goal test and without backtracking. On problems that need search, such as the blocks world with more blocks, its plans are often invalid (Valmeekam et al., 2023). The ideas of this note return in three ways, each developed in Planning with language models.
- The model formulates, a planner searches. In LLM+P (Liu et al., 2023) the model translates a problem stated in natural language into a PDDL problem file, a classical planner finds a plan, and the model translates the plan back. The planner contributes the guarantees of this note; the model contributes the formulation, which is the part people find hard to automate.
- The model is the successor function and the heuristic. Tree of Thoughts (Yao et al., 2023) runs breadth-first or depth-first search over partial solutions, the “thoughts”. The model proposes the successors of a node and also rates how promising each one is, playing the part of . On the Game of 24, combining four numbers with arithmetic to reach 24, GPT-4 prompted to reason step by step solved 4% of the test problems, and the same model inside a breadth-first search that keeps the five best partial solutions at each step solved 74% (the paper’s own test set of 100 hard puzzles, 2023). The model’s ratings are not admissible, so the optimality argument above does not apply; the search makes the model’s mistakes recoverable instead.
- Something must check the plan. A heuristic may be wrong; a goal test and the preconditions of each action may not. Systems that pair a model that proposes with an external verifier that checks, the “LLM-Modulo” pattern (Kambhampati et al., 2024), are the planning version of the separation between the agent and its environment.
What changed#
| breadth-first | uniform-cost | A* | |
|---|---|---|---|
| expands next | the shallowest node | the cheapest | the smallest |
| optimal when | all step costs are equal | step costs are at least | is consistent (graph search) or admissible (tree search) |
| goal test | when generated | when expanded | when expanded |
| uses knowledge of the goal | no | no | yes, through |
| on the grid | 139 states reached | 136 cells expanded | 80 cells expanded |
And from problem-specific code to planning: a factored state of facts, action schemas with preconditions and add and delete lists, one general search, and heuristics computed from the description itself.
Limitations#
- Memory. A* keeps every reached state. Its time can be acceptable while its memory is not; variants such as iterative-deepening A* trade time for memory.
- Exponential in the end. A heuristic shrinks the exponent but rarely removes it: when its error grows in proportion to the true remaining cost, as it does for most practical heuristics, the number of nodes A* expands still grows exponentially with the solution length.
- The assumptions are strong. Full observability, determinism and a known model are rare outside puzzles, games against nature and logistics. When outcomes are random, a plan must branch; that is the subject of the next note.
- Formulation is done by people. The state space, the actions and the costs are given; deciding what to leave out is the hard part, and the part a language model is now asked to do.
- Planning languages are rigid. Classical STRIPS cannot express time, resources or uncertainty; extensions of PDDL can, at the price of harder planning.
What you should remember#
- A search problem is a state space with an initial state, a goal test, actions, a transition model and action costs; a solution is a path, an optimal one is cheapest.
- Breadth-first search is optimal only for equal costs; uniform-cost search is optimal for positive costs and tests the goal when it expands a node.
- A* expands the smallest . With a consistent , never decreases along a path, every node is expanded with its cheapest , and the first goal expanded is optimal. Admissibility suffices for tree search.
- Good heuristics are exact costs of relaxed problems; a dominating heuristic expands fewer nodes. Weighting by saves work at a cost of at most a factor .
- STRIPS and PDDL describe states as sets of facts and actions by preconditions, add lists and delete lists; ignoring delete lists gives planning heuristics. Language-model planners reuse these pieces: the model formulates, proposes or evaluates, and a search or a verifier supplies the guarantees.
Code#
A best-first search with (uniform-cost search, A* and weighted A*), run on the graph of the worked example and on the grid, breadth-first search on the grid, and a STRIPS planner for the blocks world. NumPy and the standard library only; the script runs in well under a second and has no randomness.
import heapq, itertools
from collections import deque
from math import comb, factorial
import numpy as np
# 1. best-first search: f = g + w h. w = 0 is uniform-cost search, w = 1 is A*, w > 1 is weighted A*
def best_first(start, goal, neighbours, h, w=1.0):
tie = itertools.count()
frontier = [(w * h(start), 0, next(tie), start)] # (f, -g, insertion order, state): ties go to deeper nodes
g, parent, closed = {start: 0}, {start: None}, []
while frontier:
f, _, _, n = heapq.heappop(frontier)
if n in closed: continue # a stale entry: n was reached more cheaply before
closed.append(n)
if n == goal: # the goal test, at expansion
path = [n]
while parent[path[-1]] is not None: path.append(parent[path[-1]])
return path[::-1], g[n], closed
for m, cost in neighbours(n):
if m not in closed and g[n] + cost < g.get(m, np.inf):
g[m], parent[m] = g[n] + cost, n
heapq.heappush(frontier, (g[m] + w * h(m), -g[m], next(tie), m))
return None, np.inf, closed
# 2. the graph of the worked example, with a consistent heuristic
edges = {('S','A'): 2, ('S','B'): 3, ('A','C'): 3, ('B','C'): 1, ('A','D'): 4, ('C','G'): 4, ('D','G'): 1, ('B','E'): 2, ('E','G'): 6}
adj = {}
for (u, v), c in edges.items():
adj.setdefault(u, []).append((v, c)); adj.setdefault(v, []).append((u, c))
H = dict(S=6, A=5, B=4, C=4, D=1, E=5, G=0)
assert all(H[u] <= c + H[v] and H[v] <= c + H[u] for (u, v), c in edges.items()) # consistent
for w in (0, 1):
path, cost, closed = best_first('S', 'G', lambda n: adj[n], H.get, w)
print(w, path, cost, ''.join(closed))
# 0 ['S', 'A', 'D', 'G'] 7 SABCEDG
# 1 ['S', 'A', 'D', 'G'] 7 SBADG
# 3. a grid with walls: 4 moves of cost 1, Manhattan distance as the heuristic
MAP = ["................",
"...........#....",
".....####..#....",
"........#..#....",
"........#..#....",
".S......#..#..G.",
"........#..#....",
"........#.......",
".....####.......",
"................"]
wall = np.array([[ch == '#' for ch in row] for row in MAP])
S = next((r, c) for r, row in enumerate(MAP) for c, ch in enumerate(row) if ch == 'S')
T = next((r, c) for r, row in enumerate(MAP) for c, ch in enumerate(row) if ch == 'G')
def grid_neighbours(n):
for dr, dc in ((-1, 0), (1, 0), (0, -1), (0, 1)):
r, c = n[0] + dr, n[1] + dc
if 0 <= r < wall.shape[0] and 0 <= c < wall.shape[1] and not wall[r, c]:
yield (r, c), 1
manhattan = lambda n: abs(n[0] - T[0]) + abs(n[1] - T[1])
for w in (0, 0.5, 1, 1.5, 2, 3, 5):
path, cost, closed = best_first(S, T, grid_neighbours, manhattan, w)
print(w, cost, len(closed), end=' | ')
print()
# 0 21 136 | 0.5 21 123 | 1 21 80 | 1.5 23 75 | 2 25 68 | 3 25 65 | 5 25 60 (w, path cost, cells expanded)
def bfs(start, goal, neighbours): # optimal here: every step costs 1
depth, queue = {start: 0}, deque([start])
while queue:
n = queue.popleft()
if n == goal: return depth[n], len(depth)
for m, _ in neighbours(n):
if m not in depth: depth[m] = depth[n] + 1; queue.append(m)
print(bfs(S, T, grid_neighbours)) # (21, 139): path length, states reached
# 4. STRIPS: a state is a set of facts; an action has preconditions, an add list and a delete list
blocks = 'ABC'
def actions():
for x, y, z in itertools.permutations(blocks + 'T', 3): # move block x from y onto z; T is the table
if x == 'T': continue
pre = {f'on {x} {y}', f'clear {x}'} | ({f'clear {z}'} if z != 'T' else set())
add = {f'on {x} {z}'} | ({f'clear {y}'} if y != 'T' else set())
dele = {f'on {x} {y}'} | ({f'clear {z}'} if z != 'T' else set())
yield f'move({x},{y},{z})', frozenset(pre), frozenset(add), frozenset(dele)
ACTIONS = list(actions())
init = frozenset({'on C A', 'on A T', 'on B T', 'clear C', 'clear B'}) # C sits on A; A and B are on the table
goal = {'on A B', 'on B C'}
def plan_bfs(init, goal):
parent, queue = {init: None}, deque([init])
while queue:
s = queue.popleft()
if goal <= s:
plan = []
while parent[s]: s, a = parent[s]; plan.append(a)
return plan[::-1], len(parent)
for name, pre, add, dele in ACTIONS:
if pre <= s: # applicable: Pre(a) is a subset of s
t = (s - dele) | add # Result(s, a) = (s minus Del(a)) union Add(a)
if t not in parent: parent[t] = (s, name); queue.append(t)
print(len(ACTIONS), plan_bfs(init, goal))
# 18 (['move(C,A,T)', 'move(B,T,C)', 'move(A,T,B)'], 13)
# the number of states of the blocks world: ways to arrange n labelled blocks into stacks
print([sum(factorial(n) // factorial(k) * comb(n - 1, k - 1) for k in range(1, n + 1)) for n in (3, 5, 10)])
# [13, 501, 58941091]
Next#
Search assumed that every action has one known outcome, so a plan is a fixed sequence that can be executed with closed eyes. In most worlds that agents meet, an action can fail or have several outcomes, and the agent must decide what to do in every state it might end up in, weighing outcomes by their probabilities and rewards that arrive over time. The next note sets up that problem as a Markov decision process and solves it with the Bellman equations.
References#
- S. Russell, P. Norvig. Artificial Intelligence: A Modern Approach, 4th ed. Pearson, 2021. Chapter 3 (solving problems by searching): section 3.1 (problem formulation), sections 3.4–3.5 (uninformed search, A* and its optimality), section 3.6 (heuristic functions); chapter 11 (automated planning).
- P. E. Hart, N. J. Nilsson, B. Raphael. A formal basis for the heuristic determination of minimum cost paths. IEEE Transactions on Systems Science and Cybernetics, 4(2):100–107, 1968.
- E. W. Dijkstra. A note on two problems in connexion with graphs. Numerische Mathematik, 1:269–271, 1959.
- I. Pohl. Heuristic search viewed as path finding in a graph. Artificial Intelligence, 1(3–4):193–204, 1970.
- R. E. Fikes, N. J. Nilsson. STRIPS: a new approach to the application of theorem proving to problem solving. Artificial Intelligence, 2(3–4):189–208, 1971.
- D. McDermott, M. Ghallab, A. Howe, C. Knoblock, A. Ram, M. Veloso, D. Weld, D. Wilkins. PDDL — the Planning Domain Definition Language. Technical report CVC TR-98-003, Yale Center for Computational Vision and Control, 1998.
- B. Bonet, H. Geffner. Planning as heuristic search. Artificial Intelligence, 129(1–2):5–33, 2001.
- J. Hoffmann, B. Nebel. The FF planning system: fast plan generation through heuristic search. Journal of Artificial Intelligence Research, 14:253–302, 2001.
- K. Valmeekam, M. Marquez, A. Olmo, S. Sreedharan, S. Kambhampati. PlanBench: an extensible benchmark for evaluating large language models on planning and reasoning about change. NeurIPS Datasets and Benchmarks, 2023.
- B. Liu, Y. Jiang, X. Zhang, Q. Liu, S. Zhang, J. Biswas, P. Stone. LLM+P: empowering large language models with optimal planning proficiency. arXiv:2304.11477, 2023.
- S. Yao, D. Yu, J. Zhao, I. Shafran, T. L. Griffiths, Y. Cao, K. Narasimhan. Tree of Thoughts: deliberate problem solving with large language models. NeurIPS, 2023. Section 4.1 (Game of 24).
- S. Kambhampati, K. Valmeekam, L. Guan, M. Verma, K. Stechly, S. Bhambri, L. Saldyt, A. Murthy. LLMs can’t plan, but can help planning in LLM-modulo frameworks. ICML, 2024.
- CS188, Introduction to Artificial Intelligence. University of California, Berkeley. Lectures on uninformed search, A* and heuristics.