Courses / AI Engineering: LLMs, RAG and Agentic System Design / Chapter 10
Module 5 · Agent design fundamentals · Chapter 10 of 24
Agent design fundamentals
Builds on AI agents and multi-agent systems, Building LLM applications: chains, tools and memory, Embeddings and vector databases and Retrieval-augmented generation. Next up: Case study: a multi-agent conversational recommender.
Part 1 · What makes a system agentic
Workflows and agents
Teams that add a model to a product soon ask whether to build a fixed pipeline or an agent. The answer decides how much of the behaviour you can predict, test and bound.
The previous chapter drew the line between the two designs. In a workflow, your code defines the steps. In an agent, the model decides the next step while your code supplies the tools and the limits. That chapter built the second kind. This chapter looks at how such systems are designed.
Think of a scale of autonomy rather than two boxes. At one end, a single model call does one job and your code does everything else. Next, a fixed chain of calls with checks between them. Next, a router where the model picks one of several fixed paths. Then a loop where the model picks tools and the number of steps. At the far end, the model sets sub-goals, spawns other agents and runs for a long time. This scale is a teaching device, not a standard. Each step to the right gives the model more freedom, and your code less control.
More freedom helps when the path cannot be known in advance. A request such as *compare these three orders and tell me which arrives last* needs a number of lookups that depends on the request. Freedom costs more when the path is known. A fixed path is cheaper, faster, easier to test and easier to explain. The sound default is the simplest design that works, and a move to an agent only when a fixed design measurably cannot do the job.
The same task built both ways
The comparison uses the made-up order desk from the application patterns chapter. The workflow does two fixed things: one model call extracts a single order id into a schema, code looks up the status, and a second call writes a one-sentence reply. The agent gets one tool, get_order_status, and the loop from the previous chapter. Both are given the same three messages, three times each. The script counts a run as correct when the reply contains the expected status words.
def workflow(text): r1 = client.chat.completions.parse( model=MODEL, response_format=Extract, max_tokens=50, messages=[{"role": "user", "content": "Extract the order id.\n" + text}], reasoning_effort="none") oid = r1.choices[0].message.parsed.order_id status = ORDERS.get(oid, "unknown") r2 = ask(f"Customer: {text}\nStatus: {status}\n" "Reply in one sentence.") used = r1.usage.total_tokens + r2.usage.total_tokens return r2.choices[0].message.content, 2, used def agent(text): r = run_agent(text, TOOLS) return r.answer or "", r.steps, r.tokens
CASES = [
("one order, AB-1042", "Where is order AB-1042?", ["delivered"]),
("one order, AB-2210", "Status of AB-2210 please",
["out for delivery"]),
("two orders", "Which is further along, AB-1042 or AB-2210?",
["delivered", "out for delivery"]),
]
for name, fn in (("workflow", workflow), ("agent", agent)):
for label, text, need in CASES:
ok = calls = tok = 0
for _ in range(3):
ans, c, t = fn(text)
ok += all(re.search(rf"\b{k}\b", ans.lower())
for k in need)
calls, tok = calls + c, tok + t
print(f"{name:<9}{label:<20} ok {ok}/3 "
f"calls {calls/3:.1f} tokens {tok/3:.0f}")workflow one order, AB-1042 ok 3/3 calls 2.0 tokens 105 workflow one order, AB-2210 ok 3/3 calls 2.0 tokens 98 workflow two orders ok 0/3 calls 2.0 tokens 131 agent one order, AB-1042 ok 3/3 calls 2.0 tokens 249 agent one order, AB-2210 ok 3/3 calls 2.0 tokens 244 agent two orders ok 3/3 calls 2.0 tokens 350
Output from one run; yours will differ.
On the two single-order messages both designs were correct every time. The workflow used about 100 tokens and the agent about 250, because the agent's request also carries the tool definition and its second call carries the tool result. Both made two model calls.
The third message mentions two orders. The workflow's schema holds one order id, so it extracts one and answers about one. The check failed in all three runs. The agent called the tool twice in one turn, saw both statuses and answered correctly in all three runs, for about 350 tokens. The fixed design is cheaper and exact on the cases it was built for, and it fails silently on a case its steps did not anticipate. The agent covers more cases and costs more on each one.
Choosing between them
Use a workflow when you can list the steps in advance and the inputs vary only in content. Order status, form extraction, classification and summaries are usually workflows. They are cheaper, their failure modes are enumerable, and a test suite can cover them. A model inside a fixed step still brings the usual model risks, but the structure around it stays under your control.
Use an agent when the number or kind of steps depends on what the model finds along the way. Research across several sources, debugging a failing build, and tasks that mix lookups with actions are examples. Accept the costs: variable latency, variable spend, and the need for budgets and guards, which the rest of this chapter covers.
Many production systems are hybrids. A fixed workflow handles the common cases, and a model-driven loop sits inside one step, or takes over only when the workflow reports that it cannot handle the request. The measured result above suggests a practical rule: build the fixed version first, record the requests it fails on, and add agent behaviour only for those.
| Question | Points to a workflow | Points to an agent |
|---|---|---|
| Are the steps known in advance? | Yes | No, they depend on findings |
| Is latency or cost tightly bounded? | Yes | Some slack exists |
| Is every failure enumerable? | Yes, and each is tested | No, new cases appear |
| Does the task act on the world? | Rarely, or behind fixed checks | Often, behind guards |
In the comparison, why did the workflow fail the two-order message while still using fewer tokens?
- Its fixed steps extract one order id, so a second order is never looked up. Fewer steps means fewer tokens, but also no way to handle a case the steps did not plan for.
Part 2 · Core components
The parts of an agent
Every agent system, whatever framework it uses, contains the same parts. Naming them makes designs easier to discuss and failures easier to locate.
- Model: the language model that reads the context and decides what to do. It is the only part that is not ordinary code.
- Instructions: the system prompt that states the role, the rules and the output format.
- Tools: functions the agent can call, each with a name, a description and a schema. They are how the agent reads and changes the world.
- Memory: what the agent keeps between steps and between sessions. The next lesson covers its types.
- Planner: the part that decides what to do next, from a single step to a multi-step plan. In many systems it is just the model's own reasoning. In others it is a separate call that writes a plan first.
- Perception: how the agent observes its environment: a user message, a page, a sensor reading, a tool result.
- Guard: deterministic checks around the model, on its input, its tool calls and its output. The model never judges its own permissions.
Two parts deserve emphasis. The guard is ordinary code, so it can be tested and cannot be talked out of a decision. And perception is a design choice: what the agent sees, and how much of it, controls cost and accuracy as much as the prompt does.
The components are not an architecture you must follow. A small agent may have no separate planner and no long-term memory. They are a checklist: for each part, decide whether your system needs it, where it lives, and how you will test it.
A runnable skeleton
The skeleton below wires every part into one small class. The guard and the memory are dataclasses. The agent holds instructions, tools, a guard, a memory, a function that perceives the environment, and the model call.
@dataclass class Guard: needs_approval: set def check(self, call): if call.function.name in self.needs_approval: return "needs human approval" @dataclass class Memory: items: list = field(default_factory=list) def add(self, m): self.items.append(m) def window(self, n=12): return self.items[-n:]
Guard returns a reason when a tool needs approval, and None otherwise. Memory is a list that returns only the latest messages, which is the simplest form of a context window. The agent class adds a trace so that each step can be inspected.
@dataclass class Agent: instructions: str tools: dict guard: Guard memory: Memory perceive: object model: object = real_model trace: list = field(default_factory=list) def log(self, part, text): self.trace.append(f"{part:<9}{text[:60]}") def plan(self, observation): msg, _ = chat([{"role": "user", "content": "Write a plan of at most 3 short steps for this " "request:\n" + observation}], max_tokens=120) return msg.content.strip().replace("\n", " ")
The run method follows the order of the components: perceive, plan, then loop. In the loop, the model decides, the guard checks each call, the tool runs only if the guard allows it, and the result goes into memory.
def run(self, max_steps=5): obs = self.perceive() self.log("perceive", obs) self.log("plan", self.plan(obs)) self.memory.add({"role": "user", "content": obs}) for _ in range(max_steps): system = [{"role": "system", "content": self.instructions}] msg, _ = self.model(system + self.memory.window(), self.tools) self.memory.add(msg) if not msg.tool_calls: self.log("answer", msg.content) return msg.content for c in msg.tool_calls: f = c.function self.log("model", f"{f.name}({f.arguments})") why = self.guard.check(c) if why: result = "denied: " + why else: result = run_tool(self.tools, c) self.log("guard" if why else "tool", result) self.memory.add({"role": "tool", "tool_call_id": c.id, "content": result})
The skeleton in use
The run configures the agent as a support agent for the order desk. It has two tools: the status lookup and issue_refund, which moves money. The guard marks the refund as needing approval. The request asks for both a refund and the order's whereabouts.
from skeleton import Agent, Guard, Memory from orders import TOOLS as ORDER_TOOLS, OrderArgs def issue_refund(order_id): return f"refund started for {order_id}" TOOLS = dict(ORDER_TOOLS) TOOLS["issue_refund"] = (issue_refund, OrderArgs, "Refund one order by id. Moves money.") request = ("Customer: AB-2210 is late. Refund it and " "tell me where it is.") agent = Agent( instructions="You are a support agent. Be brief.", tools=TOOLS, guard=Guard({"issue_refund"}), memory=Memory(), perceive=lambda: request, ) agent.run() print("\n".join(agent.trace))
perceive Customer: AB-2210 is late. Refund it and tell me where it is plan 1. Locate the current shipping status of order AB-2210. 2. P model get_order_status({"order_id":"AB-2210"}) tool out for delivery model issue_refund({"order_id":"AB-2210"}) guard denied: needs human approval answer I have checked your order (AB-2210). It is currently out for
Output from one run; each line is cut to 60 characters after its label.
The trace reads like the component list. Perception supplied the request. The planner wrote a short plan (in this sketch the plan is only logged, and a real planner would add it to memory), and the model then asked for the status, which the guard did not stop. The model then asked to refund the order, and the guard denied it with the reason needs human approval. The denial went back into memory as a tool result, and the model's answer told the customer what it could and could not do.
That last step is worth noticing. The model was never allowed to refund, and it did not need to be talked out of trying. The guard sat in code between the model's request and the tool. The next lessons return to the guard and to what the human step looks like.
Part 3 · How components interact, and memory
Memory types
An agent that forgets everything at the end of each call is limited. Memory is how it carries information forward, and it comes in several kinds. The paper *Cognitive Architectures for Language Agents* (Sumers et al., 2023), often called CoALA, borrows the kinds from cognitive science and applies them to language agents.
| Type | What it holds | Where it lives in an agent |
|---|---|---|
| Working memory | Information for the current decision cycle | The message list in the context window |
| Episodic memory | Experience from earlier cycles: what happened | A store of past interactions, searched when needed |
| Semantic memory | Knowledge about the world and the agent itself | Facts and documents, often in a vector store |
| Procedural memory | How to act: skills and rules | The agent's code and the model's weights |
Working memory is the context window, so it is small and every item in it costs tokens. The other three live outside the model and have to be brought back in. That makes memory a retrieval problem: given what the agent is doing now, which stored items belong in the prompt?
The simplest answer is to take the most similar items, as a RAG pipeline does. Similarity alone has a gap, though. A memory can be old and unrelated in wording, yet matter a great deal. A food allergy mentioned months ago does not look similar to a query about a dinner menu, but leaving it out is a serious error.
Scoring memories
The paper *Generative Agents* (Park et al., 2023) scores each memory on three signals. Recency is an exponential decay over the hours since the memory was last retrieved, with a decay factor of 0.995. Importance is a score from 1 to 10 that a language model assigns when the memory is created, with 1 mundane and 10 highly significant. Relevance is the cosine similarity between the embedding of the memory and the embedding of the current query. Each signal is scaled to the range 0 to 1 with min-max scaling and the three are added, with all weights set to 1. The top-scoring memories go into the prompt.
The code below follows that recipe. A model rates importance through a structured output. Embeddings come from the local embedding model, with the query and document prefixes that the vector databases chapter introduced. Recency uses hours since last access, which the demo sets by hand.
from llm import client, MODEL class Rating(BaseModel): score: int def rate(text): r = client.chat.completions.parse( model=MODEL, response_format=Rating, max_tokens=20, reasoning_effort="none", temperature=0, messages=[{"role": "user", "content": "On a scale of 1 (mundane) to 10 (very important to the " "person) rate this memory: " + text}]) return r.choices[0].message.parsed.score def minmax(x): x = np.asarray(x, dtype=float) span = x.max() - x.min() return (x - x.min()) / span if span else np.zeros_like(x)
class MemoryStore: def __init__(self): self.text, self.hours, self.imp, self.vec = [], [], [], [] def add(self, text, hours_ago): self.text.append(text) self.hours.append(hours_ago) self.imp.append(rate(text)) self.vec.append(embed([text])[0]) def top(self, query, k=3, use=("rec", "imp", "rel")): q = embed([query], "search_query: ")[0] V = np.array(self.vec) rel = V @ q / (np.linalg.norm(V, axis=1) * np.linalg.norm(q)) rec = 0.995 ** np.array(self.hours) parts = {"rec": minmax(rec), "imp": minmax(self.imp), "rel": minmax(rel)} score = sum(parts[u] for u in use) order = np.argsort(-score)[:k] return [(int(i), float(score[i]), float(rel[i])) for i in order]
Retrieval with and without the extra signals
Ten made-up memories of a user planning a family dinner are stored, with hours since last access from 20 to 500. The query asks for a menu for Saturday's guests. The script prints the ratings the model gave, then the top three memories by relevance alone, then by all three signals.
from memstore import MemoryStore DATA = [ ("Sister Kavya arrives Friday with her two children.", 30), ("Kavya's children are allergic to peanuts.", 200), ("The user wants to cook for six people on Saturday.", 20), ("The phone charger broke on Monday.", 60), ("The user likes filter coffee with no sugar.", 300), ("The user watched a cricket match on Sunday.", 40), ("The festival shopping budget is 8,000 rupees.", 90), ("The user's favourite colour is green.", 500), ("The user does not eat onion or garlic on Tuesdays.", 250), ("The user asked for a sweet shop near the metro.", 400), ] store = MemoryStore() for text, hours in DATA: store.add(text, hours) query = "Plan the Saturday dinner menu for the guests." print("importance:", store.imp) for label, use in (("relevance only", ("rel",)), ("all three", ("rec", "imp", "rel"))): print(label) for i, score, rel in store.top(query, 3, use): print(f" {score:.2f} rel {rel:.2f} imp {store.imp[i]:>2} " f"{store.hours[i]:>3}h {store.text[i][:32]}")
importance: [8, 10, 3, 2, 4, 2, 4, 2, 2, 2] relevance only 1.00 rel 0.78 imp 3 20h The user wants to cook for six p 0.42 rel 0.60 imp 2 250h The user does not eat onion or g 0.42 rel 0.60 imp 2 40h The user watched a cricket match all three 2.12 rel 0.78 imp 3 20h The user wants to cook for six p 2.09 rel 0.60 imp 8 30h Sister Kavya arrives Friday with 1.46 rel 0.51 imp 10 200h Kavya's children are allergic to
Output from one run; yours will differ.
Relevance alone put the plan to cook for six first, which is right, and then two memories that are only loosely related to the query: a Tuesday food rule and a cricket match, tied at the same similarity. The three-signal score kept the cooking plan, added the sister's arrival, and added the note that her children are allergic to peanuts. That note is 200 hours old and only moderately similar to the query, but the model rated its importance 10, which lifted it into the top three.
The result depends on the ratings, and a different rating model would produce different numbers. The weights of 1 come from the paper, and in practice you tune the signals against your own cases. Treat the score as a way to bring back what a pure similarity search misses, and test it on queries from your own users.
How the parts interact
The loop in the skeleton shows how the components exchange data. Perception turns the environment into text. Memory adds it to the history. The model reads a window of that history and produces either an answer or a tool call. The guard checks the call, the tool runs, and its result becomes new text in memory. Every arrow is a message list or a function call. There is no hidden channel.
This has a practical consequence. Whatever the agent knows at any step is what is in its context at that step. If a fact is not in the window, retrieved from memory or returned by a tool, the model does not have it. Debugging an agent therefore starts with printing the exact messages sent in the failing call.
What is the difference between working memory and episodic memory in an agent?
- Working memory is the context for the current decision cycle, held in the prompt. Episodic memory stores experience from earlier cycles outside the model and is searched when needed.
What three signals does the Generative Agents retrieval score combine, and how are they combined?
- Recency, importance and relevance, each scaled to 0 to 1 with min-max scaling and added with weights of 1.
In the run, why did the old peanut-allergy memory reach the top three?
- Its importance rating was 10, the highest. Added to a moderate relevance score, that outweighed its low recency.
Part 4 · Orchestration patterns
Five patterns from the agents article
Orchestration is how you arrange model calls and tools to get a job done. Anthropic's article on building effective agents describes five patterns that cover most designs. Each is a small, testable structure that you can combine.
| Pattern | What it does | Use it when |
|---|---|---|
| Prompt chaining | Splits a task into a fixed sequence of calls, each using the previous output, with checks between | The task divides cleanly into steps |
| Routing | Classifies the input and sends it to a specialised handler | Inputs fall into distinct categories |
| Parallelisation | Runs calls at the same time, either on separate parts of a task or on the same task several times for a vote | Parts are independent, or you want several attempts |
| Orchestrator-workers | A central model breaks the task into subtasks at run time and delegates them to worker calls | You cannot predict the subtasks in advance |
| Evaluator-optimiser | One call produces an answer and another evaluates it, in a loop | You have clear criteria and revision helps |
In the article's terms all five are workflows. In the first three, code fixes the structure. In orchestrator-workers a model decides the subtasks, as in the manager-led team of the previous chapter. Evaluator-optimiser is a loop whose exit condition comes from an evaluation.
The patterns build on the tool-calling and routing code from earlier chapters. What is new here is knowing which one fits a problem, and keeping each as simple as the problem allows. Most real systems use one or two of them, not all five.
Evaluator and optimiser in code
The loop below writes a one-line product description under four rules: at most 18 words, the phrase stainless steel, the price 499, and no use of the word best. A function checks the rules in code. If any fail, the failures are added to the next prompt, and the model tries again. A cap of three rounds bounds the loop.
import re from llm import chat BRIEF = ("Write a product line for a steel water bottle, 500 ml, " "priced at 499 rupees.") def check(text): problems = [] if len(text.split()) > 18: problems.append("use at most 18 words") plain = " ".join(text.lower().replace("-", " ").split()) if "stainless steel" not in plain: problems.append("say 'stainless steel'") if not re.search(r"(?<![\d,.])499(?![\d,]|\.\d)", text): problems.append("state the price 499") if re.search(r"\bbest\b", text, re.I): problems.append("do not use the word 'best'") return problems
The loop that uses it calls the model, checks the reply, and feeds the failures back.
def optimise(max_rounds=3): prompt = BRIEF for n in range(1, max_rounds + 1): msg, _ = chat([{"role": "user", "content": prompt}], max_tokens=60, temperature=0.7) text = msg.content.strip() problems = check(text) print(f"round {n}: {len(text.split())} words | {problems}") print(" ", " ".join(text.split())[:64]) if not problems: return text prompt = (f"{BRIEF}\nYour last try was: {text}\n" f"Fix these problems: {'; '.join(problems)}.") return None print("result:", optimise())
round 1: 39 words | ['use at most 18 words', "say 'stainless steel'", 'state the price 499', "do not use the word 'best'"] Depending on your brand personality, here are a few different op round 2: 15 words | [] Stay hydrated in style with this 500ml stainless steel bottle. P result: Stay hydrated in style with this 500ml stainless steel bottle. Premium quality for only 499.
Output from one run; yours will differ. Long lines are wrapped here.
In this run the first attempt ignored the length limit and offered several options in long form, so the check reported four failures. The second attempt met every rule and the loop stopped after two rounds. A fresh run may pass in one round or need all three, because the first answer varies. In another run of this script the model stayed over the word limit in all three rounds and the function returned None.
Reflection and topologies
An evaluator-optimiser loop is close to what the paper *Reflexion* (Shinn et al., 2023) calls verbal self-reflection: after an attempt fails, the agent writes a short reflection in plain text about what went wrong and keeps it in memory for the next attempt. The model's weights do not change. The text in the prompt does.
Patterns also combine into topologies: shapes of who calls whom. In a single-agent design, one model uses tools in a loop. In a pipeline, agents run in a fixed order, each passing output on. In a hierarchy, a manager delegates to workers and collects results. In a group, several agents contribute to a shared discussion or vote. More agents add calls, tokens and delay, and more places for a mistake to be copied. The previous chapter's measured example showed one call doing a small job as well as a team.
A good rule is to start with a single agent and a clear tool set. Add structure when a measured failure shows that one agent cannot cope: long contexts that confuse it, parts that could run in parallel, or a need for an independent check. Add one change at a time, and keep the test cases that justified it.
Which of the five patterns lets a model decide the subtasks at run time?
- Orchestrator-workers. A central model breaks the task down and delegates, so the structure is not fixed in advance.
Why does the evaluator-optimiser loop in the script have a cap of three rounds?
- Without a cap, a task the model cannot satisfy would loop forever. At the cap the function returns
Noneso the caller can decide what to do.
What changes in a Reflexion-style loop between attempts: the weights or the prompt?
- The prompt. The agent writes a text reflection on its failure and keeps it in memory, and the weights stay the same.
Part 5 · Guardrails and human oversight
Layers of control
A guardrail is a check that runs outside the model and limits what the system can do. Because the model's behaviour is not guaranteed, safety cannot rest on the prompt alone. Guardrails sit at three points: on the input (reject or clean requests before the model sees them), on the tool calls (decide whether an action may run) and on the output (check what is shown to the user).
Tool calls deserve the most care, because they change the world. A practical way to organise permissions is by tier, each defined by what the tool can do:
- Read: look something up. Allow freely, within data-access rules.
- Write: change reversible data, such as adding a note. Allow with logging.
- Money: spend, refund or transfer. Require approval, or a hard limit.
- Human: contact a person, close an account or anything hard to undo. Require a person to decide.
The tiers are a design convention, not a standard. What matters is that they are enforced in code, that unknown tools are denied by default, and that every decision is logged. An audit log that records the tool, the arguments, the verdict and the time is how you answer later questions about what the agent did and why.
A tier guard in code
The guard below holds a table from tool names to tiers. Read and write calls are allowed. A money call is allowed only when the caller says it was approved. Anything else, including a tool that is not in the table, is denied. Each decision is appended to an audit list.
import json import time TIERS = {"get_order_status": "read", "add_note": "write", "issue_refund": "money", "close_account": "human"} AUDIT = [] def decide(tool, args, approved=False): tier = TIERS.get(tool) if tier is None: verdict = "deny: unknown tool" elif tier in ("read", "write"): verdict = "allow" elif tier == "money" and approved: verdict = "allow: approved" else: verdict = f"deny: {tier} tier needs approval" AUDIT.append({"t": round(time.time()), "tool": tool, "args": args, "verdict": verdict}) return verdict
get_order_status -> allow issue_refund -> deny: money tier needs approval issue_refund -> allow: approved delete_database -> deny: unknown tool 4 audit rows; first: {"tool": "get_order_status", "args": {"order_id": "AB-1042"}, "verdict": "allow"}
Output from one run. Long lines are wrapped here.
The refund was denied the first time and allowed once the approval flag was set. A tool called delete_database, which is not in the table, was denied as unknown. Four decisions produced four audit rows. The approval flag in this code has to come from a real human decision, and the next page shows one way to get it.
Pausing for a person
A human-in-the-loop step needs the run to stop, wait for as long as the person takes, and then continue from where it stopped. LangGraph, a library for building agent workflows as graphs, supports this with an interrupt call inside a node. It needs a checkpointer, which saves the state of the run, and the same thread_id on every call that belongs to one run. The documentation notes that on resume the node that called interrupt runs again from its start, so side effects before the call would repeat.
The example graph has three nodes: propose picks an order, approve asks a person, execute acts on the answer. The propose and approve nodes each print a line so the restart is visible.
from typing import TypedDict from langgraph.checkpoint.memory import MemorySaver from langgraph.graph import END, START, StateGraph from langgraph.types import Command, interrupt class State(TypedDict, total=False): order_id: str approved: bool result: str def propose(state): print("propose runs") return {"order_id": "AB-2210"} def approve(state): print("approve starts") answer = interrupt({"action": "issue_refund", "order_id": state["order_id"]}) return {"approved": answer == "yes"} def execute(state): if state["approved"]: return {"result": f"refund started for {state['order_id']}"} return {"result": "refund cancelled"}
g = StateGraph(State) g.add_node("propose", propose) g.add_node("approve", approve) g.add_node("execute", execute) g.add_edge(START, "propose") g.add_edge("propose", "approve") g.add_edge("approve", "execute") g.add_edge("execute", END) app = g.compile(checkpointer=MemorySaver()) for thread, answer in (("t-1", "yes"), ("t-2", "no")): cfg = {"configurable": {"thread_id": thread}} out = app.invoke({}, cfg) print(thread, "paused:", out["__interrupt__"][0].value) print(thread, "next node:", app.get_state(cfg).next) out = app.invoke(Command(resume=answer), cfg) print(thread, "result:", out["result"])
propose runs approve starts t-1 paused: {'action': 'issue_refund', 'order_id': 'AB-2210'} t-1 next node: ('approve',) approve starts t-1 result: refund started for AB-2210 propose runs approve starts t-2 paused: {'action': 'issue_refund', 'order_id': 'AB-2210'} t-2 next node: ('approve',) approve starts t-2 result: refund cancelled
Output from one run.
The first call to the graph ran propose, started approve and paused, returning the pending request. The saved state shows that approve is the next node. The second call carried a Command(resume=...) with the answer. The line approve starts printed a second time because the node ran again from its top, while propose did not run again. With an answer of yes the refund started. With an answer of no, on a second thread, it was cancelled.
Part 6 · Key challenges and design strategies
Errors compound over many steps
An agent that takes many steps has many chances to go wrong. If each step succeeds with probability p and the steps are independent, the whole run succeeds with probability p to the power n for n steps. Independence is an approximation, since real errors often cluster, but the arithmetic shows the scale of the problem.
The script tabulates p to the power n for three values of p and three run lengths, then checks each by simulation with a fixed seed: 1,00,000 simulated runs per cell. It also computes how many steps it takes for the success rate to fall below one half.
import math import random rng = random.Random(7) TRIALS = 100_000 def simulate(p, n): wins = 0 for _ in range(TRIALS): if all(rng.random() < p for _ in range(n)): wins += 1 return wins / TRIALS print("p n p**n simulated") for p in (0.99, 0.95, 0.90): for n in (5, 10, 20): print(f"{p:.2f} {n:>3} {p**n:.3f} {simulate(p, n):.3f}") for p in (0.99, 0.95, 0.90): half = math.log(0.5) / math.log(p) print(f"p={p:.2f}: success drops below 50% after {half:.1f} steps")
p n p**n simulated 0.99 5 0.951 0.951 0.99 10 0.904 0.904 0.99 20 0.818 0.817 0.95 5 0.774 0.774 0.95 10 0.599 0.598 0.95 20 0.358 0.359 0.90 5 0.590 0.591 0.90 10 0.349 0.347 0.90 20 0.122 0.121 p=0.99: success drops below 50% after 69.0 steps p=0.95: success drops below 50% after 13.5 steps p=0.90: success drops below 50% after 6.6 steps
Output from one run; yours will differ.
The simulated values match the formula to within about two thousandths. A step that is right 95 times in 100 gives a 20-step run only about a 36 per cent chance of success. At 99 per cent per step, 20 steps still succeed 82 per cent of the time, and the success rate stays above one half until around 69 steps.
The design responses follow from the formula. Keep runs short, with fewer steps and more work in deterministic code. Raise per-step reliability with schemas, validation and tool errors that guide repair. Add checkpoints where a bad intermediate result is caught early. And measure p for your own steps, since it is the number that decides the design.
Cost, latency and non-determinism
Each model call costs tokens and takes time, and an agent's calls are in sequence. If each step takes two seconds (it varies by machine and model), a ten-step run takes twenty seconds before any tool time. The design levers are fewer steps, smaller prompts, a cheaper model for easy steps, running independent calls in parallel, and caching.
Model behaviour is not identical from run to run. The script below runs one three-order task eight times and groups the runs by how many model and tool calls they used.
from collections import Counter from agent import run_agent from orders import TOOLS task = ("Check AB-1042, AB-2210 and AB-3301 and tell me which one " "arrives last.") shapes, tokens = Counter(), [] for _ in range(8): r = run_agent(task, TOOLS) shapes[(r.steps, len(r.calls))] += 1 tokens.append(r.tokens) for (steps, calls), n in sorted(shapes.items()): print(f"{n} runs: {steps} model calls, {calls} tool calls") print("tokens per run:", sorted(tokens))
8 runs: 2 model calls, 3 tool calls tokens per run: [447, 448, 465, 475, 476, 478, 481, 483]
Output from one run; yours will differ.
All eight runs took the same path, two model calls and three tool calls, and used between 447 and 483 tokens. That is a stable result for a small task. It is not a promise: longer tasks leave more room for the path to differ, and a provider can change a model without notice. Do not assume a path. Record traces, and test the properties that must always hold, such as the final state and the limits.
Evaluation is the other half of this problem. A system whose behaviour varies needs a test set of real cases, checks that run on every change, and a way to judge outputs that code cannot check.
Security and a checklist
An agent reads text from places you do not control and can act on it. A web page, an email or a document can contain instructions aimed at the model, a risk called prompt injection. An agent with tools that touch money or private data has more to lose. The design strategy here is the one already in this chapter: keep permissions narrow, enforce them in a guard and require a person for actions that are hard to undo.
The challenges of this lesson map to design strategies.
| Challenge | Strategy | Where it appears |
|---|---|---|
| Errors compound over steps | Fewer steps, validation, checkpoints, measure p | The arithmetic above |
| Cost and latency | Smaller prompts, cheaper models for easy steps, parallel calls, caching | Budgets in the previous chapter |
| Non-determinism | Trace every run, test properties not exact text | The eight-run table |
| Evaluation | Test sets, code checks, validated judges | The checks above |
| Security | Tiered permissions, guards, approval, audit logs | The guard and the interrupt |
A short checklist closes the chapter. Is a fixed workflow enough? Which components does the design need? What does the agent remember, and who can read it? Which pattern fits, and what is its cap? Which tool tiers exist, and what requires a person? How many steps does a run take, and what is the success rate per step? What is logged, and how will you evaluate a change?