Agents and Memory

When the model chooses the next step itself: tools, plans, the ways they break, and what the agent remembers.

Lesson 7 · Previews Chapter 6, second half · about 25 min

Your win today Given an agent's step-by-step trace, you'll find the first step that went wrong and name the failure: a planning error (wrong tool, bad parameters, wrong values, missed goal, false “done”) or a tool error. You'll also be able to say why a 20-step agent fails far more often than a single prompt, and where each kind of information should live in its memory.

Warm-up · spaced review

1 · What makes something an agent

Huyen borrows the textbook definition: an agent is anything that can perceive its environment and act on it. Two things characterize it: the environment it works in (a game, the internet, a code repository) and the actions it can take, which its tools extend. In an AI agent, the model is the brain. It plans a sequence of actions, reads the feedback, and decides when the task is done. Ch6 · Agent Overview

By that definition you built one last lesson. A RAG system is an agent whose tools are retrievers, and the tabular one with text-to-SQL had three actions: generate SQL, execute it, write the answer. Asked to project next quarter's sales, it might fetch five years of sales, decide that isn't enough, also fetch past marketing campaigns, and only then answer. The model chose that path. Ch6 · Agent Overview

Anthropic draws a useful line here. In a workflow, LLM calls follow code paths you wrote (classify → retrieve → draft). In an agent, the model picks the path. Their advice is to start with the simplest solution that works and reach for an agent only when the steps can't be predicted in advance. Anthropic 2024

2 · Tools and function calling

Huyen sorts tools into three groups. Ch6 · Tools

KindWhat it gives the modelExamples
Knowledge augmentationContext it doesn't have: private data, fresh dataRetrievers, SQL, inventory API, web search (keeps the model from going stale)
Capability extensionSkills it's bad atCalculator (199,999 ÷ 292), unit and time-zone converters, code interpreter, image generator
Write actionsThe power to change thingsSend email, update a database, transfer money, merge code

The first two are mostly read-only: the agent perceives. Write actions let it act, which is where the value is and where the danger is. Huyen's comparison: you wouldn't let an intern delete your production database. And the agent's inputs include retrieved pages and emails, so every injection attack from Lesson 5 now reaches real actions. Simon Willison names the worst mix the lethal trifecta: access to private data, exposure to untrusted content, and a way to communicate externally. With all three, an attacker can trick the agent into sending your data out, so don't combine them. Ch6 · Write actions; Willison 2025

Mechanically, a tool is a function. You declare each one (name, parameters, a description of what it does), choose which tools a request may use, and optionally force the choice: required (must call a tool), none, or auto (the model decides). The model doesn't run anything itself. It replies with a request, and your code executes it and feeds the result back: Ch6 · Function calling

user:      How many kilograms are 40 pounds?
model:     finish_reason = "tool_calls"
           tool_calls = [ lbs_to_kg( {"lbs": 40} ) ]   ← the model's choice
your code: lbs_to_kg(lbs=40) → 18.14                   ← you execute it
model:     40 pounds is about 18.1 kg.

The API can guarantee the function exists, but not that the parameter values are right. Huyen's tip: log every call with its parameters, and read them.

3 · Why agents fail more often

The rule: if each step succeeds with probability p, a task of n steps succeeds with probability p × p × … (n times) = pn. Think of a relay race: each of ten runners drops the baton only 1 time in 20, but the team finishes clean only 60% of the time. Ch6 · Agent Overview

Per-step accuracy1 step10 steps100 steps
99%99%90%37%
95%95%60%0.6%
90%90%35%≈ 0%

So agents need stronger models than single prompts do, for two reasons: mistakes compound, and with write tools the stakes are higher. It also explains why every extra step needs to earn its place, and why cost and latency grow with the step count. Ch6 · Agent Overview

4 · Plan, check, act, reflect

You could ask the model to plan and execute in one go, but what if it writes a 1,000-step plan that doesn't reach the goal? It burns hours of API calls before anyone notices. So Huyen decouples planning from execution. A planner proposes a plan. A validator rejects bad ones, either with simple heuristics (it uses a tool the agent doesn't have, or it has more than N steps) or with an AI judge. Only then do the steps execute. For risky steps such as database updates or merges, a human approves first. Ch6 · Planning overview

Task Plandecompose Validaterules / judge Executetool calls Reflectdone? errors? Answer bad plan: try again not done yet: re-plan Human approves write actions
The agent loop, after Huyen's Figure 6-9. Humans can step in at any stage: write the plan, approve it, or run the risky step themselves.

Reflection is the cheap, high-value part: checking whether the request is feasible, whether the plan makes sense, whether each step stayed on track, and whether the goal was really met. The common pattern is ReAct (Yao et al., 2022), which interleaves reasoning and acting: Thought → Act → Observation, repeated until the agent decides it's finished. Reflexion adds a separate evaluator and a self-critique (“the code failed on all-negative arrays”) before the next attempt. The cost is tokens and latency, because every thought and observation is generated or read. Ch6 · Reflection and error correction

To make planning better, Huyen lists the levers you already know from Lesson 5, plus one specific to tools: better system prompts and examples, better tool descriptions, simpler tools (split a complex function in two), a stronger model, or finetuning. Anthropic adds that tool definitions deserve as much prompt engineering as the prompt itself. Their coding agent kept fumbling relative file paths, so they changed the tool to require absolute paths, and the errors stopped. Ch6 · Plan generation; Anthropic 2024

5 · Try it: debug six traces

Huyen's failure modes for agents come in three families. Planning failures are wrong decisions by the model: an invalid tool (not in the inventory), invalid parameters (wrong names or count), wrong parameter values, a goal failure (the task or one of its constraints isn't met), or a reflection error (the agent says it's done when it isn't). Tool failures are when the right tool was called correctly but returned something wrong. Efficiency is when it works, but with too many steps, too much money or too much time. Ch6 · Agent Failure Modes and Evaluation

For each trace, read the task and the tool inventory, click the first step that went wrong, and pick its failure mode.

To evaluate an agent at scale, count these. Build a set of (task, tool inventory) examples, generate plans, and measure the share of valid plans, the share of valid tool calls, how often each failure mode happens, and the average steps, cost and time per task. Then look for patterns: which tasks fail, and which tools trip the model up. Run an ablation too: remove a tool, and if performance doesn't drop, it goes. Ch6 · Planning failures; Tool selection

6 · Memory: where information lives

Huyen gives a model three memory mechanisms, and the right one depends on how often the information is needed. Ch6 · Memory

MemoryWhat it isPut here
Internal knowledgeThe model's weights. Changes only by training or finetuning.What every task needs
Short-termThe context window. Fast, but limited and gone after the task.What this task needs now: recent turns, the last tool output
Long-termExternal stores reached by retrieval, as in RAG. Persists across sessions; deletable without retraining.What's rarely needed, and what must outlive the session

A memory system decides what to add and what to delete from the limited short-term memory, moving the overflow to long-term memory. The simplest policy is FIFO: drop the oldest messages first. That can be fatally wrong, because the first messages often state what the whole conversation is for. Better policies summarize (with named entities kept), or use reflection: after each action, the agent decides whether the new information should be inserted, merged with an existing memory, or replace an outdated one that it contradicts. Ch6 · Memory

Practice: where should each piece of information live?

Check yourself

Primary source

Read next: Huyen, AI Engineering, Chapter 6, from “Agents” to the end. Read “Agent Overview,” “Tools,” “Planning overview,” “Function calling,” “Reflection and error correction,” “Agent Failure Modes and Evaluation” and “Memory.” Skim “Foundation models as planners” (the debate over whether LLMs can plan) and “Complex plans.”

From practitioners, about 20 min: Anthropic, “Building Effective Agents” (Dec 2024). It covers workflow vs. agent, five workflow patterns, and the tool-design appendix. Then Simon Willison, “The lethal trifecta for AI agents” (June 2025), a short follow-up to the post from Lesson 5.

Stuck or curious? Ask me anything. For example: “Is my product idea a workflow or an agent?”, “Show me a ReAct loop in 40 lines of Python” or “How does a coding agent remember things between sessions?” When you're done, send your first-try scores: the warm-up, the six traces, the memory sorter and the quiz.

Next: Lesson 8, Finetuning (Ch. 7)

Related ideas