Skip to book
Peanut learns to agent.An illustrated guide
GitHub ↗

An illustrated guide to AI agents

Peanut learns
to agent.

AI agents and the systems around them,
explained with a peanut.

Written & illustrated byAishwarya Ashok (& agentic teammates)

Open the book

12 chapters · 119 concepts · illustrated edition

Part II · Building agents people can use ↗

Part I · How agents work

Chapter 01 / 12

Peanut gets a job

Models and agents

Begin with the model, then follow what changes when software can act. A predictable workflow and an agent can use the same model; the difference is who decides the next step.

Language model (LLM)

A large language model is a machine-learning model trained on large amounts of data to process and generate language.

A builder peanut reads a repair suggestion from a language-model machine; the chair and repair tools remain untouched beside it.
The machine has suggested a repair. The chair is waiting.Peanut is the builder here. The machine represents the language model; the tools beside the chair would turn its suggestion into action.

A generative language model produces a response from the input it receives, using patterns learned during training. That response may be prose, code, or a structured tool request. To turn a proposed repair into an action, an application needs tools and software to run them. This distinction becomes useful as soon as we start building agents.

Source & further reading

Technical reference: Language models ↗

Training versus inference

Training adjusts a model's learned parameters; inference uses a trained model to produce outputs from new inputs.

In two scenes, builder Peanut adjusts a model machine using example cards and feedback, then feeds it a new job and reads the response without changing its settings.
First, adjust the machine using examples. Then give it a new job.Peanut is the builder in both scenes. Adjusting the machine stands for training; using its learned settings for a new job stands for inference.

Training is where the model's parameters change through an optimization process. Inference is where the trained model computes a response. A document added to a prompt supplies information for that response; retraining would change the model itself. For a builder, this helps separate two decisions: what information to provide now, and whether additional training is warranted.

Source & further reading

Technical reference: Training and inference ↗

AI agent

A system that uses an AI model to choose and carry out actions toward a goal.

Peanut inspects a wobbling chair, pushes an orange shim under one leg, and presses the seat again to check the repair.
You asked for a steady chair. Peanut worked out the steps.Peanut represents the whole agent system here, choosing a repair, using a tool, and checking the result.

In an agent system, the model chooses an action and the surrounding software executes it through a tool. The result returns to the model, which can choose another action, ask for help, or finish. You supply the goal and constraints. How much the agent can do along the way depends on its available tools, permissions, and stopping rules.

Source & further reading

Technical reference: Building effective agents ↗

Deterministic workflow

A workflow whose next steps are determined by predefined rules and its inputs or state.

Peanut moves an orange parcel toward a large box beside a scale displaying 7 kg. A packing rule assigns parcels above 5 kg to large boxes and the rest to small boxes.
Heavy parcel, large box. The rule was settled before Peanut arrived.Peanut follows the written packing rule here. The measured weight determines which box it uses.

A predefined workflow can include branches, loops, and error handling. What makes its control logic deterministic is that the same relevant inputs and state select the same path. This is useful when the process is understood well enough to encode. A variable model response or changing external data can still produce different outcomes inside that fixed structure.

Source & further reading

Related distinction: Workflows and agents ↗

Agentic workflow

A process that includes model-driven decisions or actions, often alongside predefined software steps.

Peanut inspects a dented orange parcel beside a fork in a packing conveyor while other parcels continue toward the packing station.
Most parcels keep moving. A few need a closer look.Peanut supplies the model-driven judgment at the inspection fork. The rest of the packing line follows its usual steps.

You can introduce model judgment at one useful point in an otherwise fixed process. An incoming request might follow standard intake steps, then use a model to choose its handler. “Agentic workflow” is used broadly, so identify the actual decision the model owns. That tells a builder more than the label alone.

Autonomy

The degree of freedom an agent has to make decisions and take actions without further human input.

A peanut gardens inside a fenced flowerbed while a reviewer peanut outside considers a move-fence card with an empty approval box.
Peanut may tend the flowerbed. Moving the fence is a separate conversation.The gardening peanut is the agent. The fence marks its permitted work; the reviewer peanut represents the person who can approve a change to that boundary.

You might let a research agent browse freely while requiring approval before it emails a customer. That is a choice about autonomy.

Make the permitted decisions explicit, then support those boundaries with tool permissions and review gates. The agent’s freedom should fit the job it has been given.

Agent loop

The repeated cycle of model decision, action execution, and observation that moves an agent's work forward.

Four scenes show Peanut tightening a dripping tap, observing that it still drips, replacing a washer, and checking the repaired tap above a dry basin.
Check the drip, change the repair, check again.Peanut is the agent throughout. Each check supplies the evidence for its next action, including the final check that the leak has stopped.

Each tool result supplies evidence for the next model decision. A failed repair may lead to a different action; a successful check may end the run. The surrounding software keeps this cycle moving and applies stopping limits. This is how an agent can adapt its next step to what actually happened.

Source & further reading

Technical reference: Agents ↗

Reasoning model

An AI model trained to use intermediate reasoning computation to work through problems before or while producing a response.

Peanut draws an orange route on a final map at a drafting table, with several discarded route sketches beside it.
A few route sketches before the final map.Peanut is working through a problem with a reasoning model. The sketches stand for intermediate computation, not a readable record of the model’s internal processing.

Some models are trained to spend intermediate reasoning computation on a problem before or while producing a response. That extra work can help with tasks that require several connected steps. It also uses time and compute, and correctness needs to be assessed from the result. A visible explanation is distinct from a complete record of internal processing.

Source & further reading

Research example: DeepSeek-R1 ↗

End of chapter 01

Part I · How agents work

Chapter 02 / 12

Peanut equips the workshop

The agent’s environment

The model needs somewhere to work. Harness, runtime, scaffold, and orchestration describe overlapping pieces of that environment. Read them together: the boundaries vary across tools and teams.

Agent harness

The surrounding software that connects a model to tools, manages its work, and applies execution controls.

A peanut repairs a stool at a bench equipped with tools, instructions, progress notes, and a guarded switch.
The stool gets repaired at a very well-equipped bench.Peanut is the agent. The bench, tools, job card, notebook, and guarded switch stand for the software that supports and controls its work.

A model needs a way to call tools, receive results, retain progress, and operate within permissions. The harness supplies that supporting software. When an agent loses track of a task or handles a tool failure badly, examine this setup as well as the model. Teams draw the harness boundary differently, but these supporting responsibilities have to live somewhere.

Source & further reading

Technical reference: Effective harnesses ↗

Agent runtime

The software that runs an agent's execution cycle and manages its active operations.

Peanut feeds an action card into a working machine with turning gears and an orange running light, while a result slip emerges from the other side.
An action card goes in. A result comes back. Work continues.Peanut is the agent. The operating workbench represents the runtime executing actions and returning results.

Someone has to make the model call, dispatch the requested tool, and deliver its result. Those are runtime responsibilities. A runtime may also manage concurrent operations, cancellation, and failures. The term emphasizes active execution, so it overlaps with the harness wherever the harness also handles running the work.

Agent scaffold

A supporting arrangement of prompts, code, and task structure used to guide an agent's work.

Peanut adds an orange block to a crooked tower inside a wooden guide frame, beside a clipped checklist.
A guide frame helps with the next brick.Peanut is the agent building the tower. The guide frame and checklist represent the structure supplied by prompts and code.

Prompts and code can give an agent useful structure: a planning stage, a checklist, or a review step before completion. That arrangement is often called a scaffold. The term has loose boundaries and can overlap with harness. When discussing a particular system, describe the structure it supplies rather than assuming everyone means the same component.

Orchestration layer

Software that coordinates the order, dependencies, and exchange of information between tasks, tools, or agents.

Peanut carries cut wooden pieces and a ready ticket from a cutting bench to a waiting stool-assembly bench.
Assembly is ready. The cut pieces are not.Peanut carries work between dependent steps here. The waiting assembly bench makes the dependency visible: its next step needs the cutting result.

Dependencies determine what can run next. An orchestration layer tracks those dependencies, passes results between steps, and coordinates the work. Some choices follow rules; others can be delegated to a model. A useful design makes it clear who decides the sequence and what happens when a required result never arrives.

Execution environment

The computing environment in which an agent's tools and code run, including its resources and access limits.

Peanut reaches for an orange-handled wrench on a bench in a workshop with supplies, a padlocked cupboard, and a closed service hatch.
The job happens with what is actually in the workshop.Peanut is the agent. The workshop represents where its tools run; the supplies, cupboard, and hatch show available resources and access limits.

Installed packages, files, compute resources, and network access all affect what a tool can do. Permissions further limit its reach. This is why a task that works in one environment may fail in another. Before blaming the model, check whether its tools can reach the files and services the job requires.

End of chapter 02

Part I · How agents work

Chapter 03 / 12

Peanut keeps the right things close

Instructions, context, and memory

Instructions tell the system what to do. Context supplies information for the next model response. State and memory preserve what the application needs as the job continues. The same fact may move between these places.

System prompt

Instructions supplied at the system level to guide a model's behavior across an interaction.

Peanut stirs an orange soup pot beside standing kitchen rules and a separate soup-order ticket.
Lunch comes with an order and a set of kitchen rules.Peanut is the agent. The kitchen rules represent standing instructions; the order ticket supplies the current task.

An application can supply standing instructions about the model's role, behavior, and response requirements. Many platforms provide a system-level message for this purpose, with priority defined by their instruction hierarchy. Use it to describe how the model should behave. Access restrictions belong in software controls as well.

Instruction hierarchy

The priority order used to resolve conflicting instructions from different sources.

Peanut carries boxes away from an open exit. A building rule says to keep it clear, while a delivery note says to stack boxes in the doorway.
The delivery note has found a very inconvenient place for the boxes.Peanut is the agent resolving conflicting instructions. The building rule has higher authority than the delivery note.

Many AI platforms assign different authority to instructions based on their source. The model should follow that ordering when instructions conflict. A retrieved page is usually task material, so a command inside it should not acquire the authority of the application's own rules. Preserving that distinction is part of defending against prompt injection.

Tokens and tokenization

Tokens are units used to represent model inputs and outputs; tokenization converts content into those units.

Builder Peanut feeds word-fragment tiles from the sentence Peanuts work into a tokenizer machine, which produces numbered tiles. The split is labeled illustrative.
One sentence, several pieces. Some words need more than one.Peanut is the builder here. The word-fragment tiles and numbered output illustrate text tokens and their identifiers; the split and numbers are examples.

A text tokenizer converts text into token identifiers using a particular encoding. Its units may represent whole words, word parts, punctuation, or other fragments. Different tokenizers can split the same sentence differently. Those choices affect context capacity and usage accounting, which is why word counts are only a rough guide to token counts.

Source & further reading

Technical reference: Tokenization ↗

Context engineering

Designing how an application selects, assembles, and maintains the information supplied to a model.

Peanut packs job, measurements, and tool-result cards into a work tray while other-job papers stay on a shelf.
Pack for the next step. The unrelated papers can stay on the shelf.Peanut selects the information for the agent’s next step. The tray represents the supplied context; the shelf holds material left out of this call.

What does the model need to make the next decision? Context engineering turns that question into application behavior: selecting instructions, retrieving documents, retaining useful results, and removing clutter. The selection changes as work progresses. A good context strategy supplies relevant evidence when it is needed and gives the system a way to recover details later.

Source & further reading

Technical reference: Context engineering ↗

Context window

The maximum amount of tokenized information a model can handle within a single inference context.

Peanut reads a short section of a long paper roll through an orange rectangular frame labeled capacity, with most of the roll outside the opening.
The paper keeps going beyond the opening.Peanut is using the model’s available context. The opening represents its bounded capacity; the rest of the roll is information that exists outside that context.

A model has a finite capacity for the information involved in a single inference context. Supplied input and space needed for generation must fit the model's limits. Information stored elsewhere has to be brought into context to be used directly. Increasing the window gives you more capacity; choosing useful content remains part of the job.

Context compaction

Reducing accumulated context while retaining the information needed to continue a task.

Peanut selects destination, completed work, and a detour question from a trip diary, then travels with a small summary card while the full diary stays on a shelf.
Keep the destination, the completed stops, and that unresolved detour.Peanut is the agent continuing its task. The card is compacted context, including the detour question; the retained diary represents the fuller record.

Long-running work accumulates more history than the next step needs. Compaction reduces that history, often by summarizing earlier messages and removing redundant material. Preserve decisions, constraints, and unfinished work with care. Since compression loses detail, retain a way to consult the underlying records when the summary leaves an important question unanswered.

Source & further reading

Technical reference: Compaction ↗

Session state

Data that records the current interaction or run and its progress.

Peanut writes on a laundry ticket listing towels, the gentle cycle, and washing status beside a running washing machine.
Towels. Gentle cycle. Still washing. The ticket keeps track.Peanut is the agent. The ticket represents the application's record of the current job.

Session state lets an application keep track of the current interaction. It may include messages, intermediate results, progress, and a pending approval. Some state is supplied to the model; other parts remain in application storage. Keeping that distinction clear helps avoid stuffing every operational detail into the prompt.

Working memory

Information kept readily available for the agent's immediate task.

Peanut attaches a hinge to a wooden box while two nearby notes specify an M3 screw and an outward-facing hinge.
Screw size and hinge direction stay within reach.The two notes stand for information kept available for this step: which screw to use and which way the hinge faces.

An agent may keep immediate task information in its current context, a scratchpad, or task state. This is often called working memory, though implementations vary. Refresh the selection as the task progresses so the useful notes remain easy to find.

Persistent memory

Information stored beyond a single interaction so it can be retrieved and used later.

On Monday, Agent Peanut files a customer's paper-wrap preference. On Friday, the agent retrieves the same card beside a new parcel and wrapping paper.
Friday's parcel gets Monday's packing preference.The drawer is application storage. Retrieving the saved card makes the preference available on the later visit.

Useful information can survive a session in a file or database. Later, the application retrieves relevant records and supplies them to the model. That retrieval is what makes a saved preference available for the current response. Storing the record changes application memory, not the model's trained parameters.

Checkpointing

Saving task state at defined points so execution can recover or resume from recorded progress.

Peanut closes a clear-lidded tray labeled saved progress, containing a partly assembled wooden model, loose parts, and assembly notes.
Save the parts and the progress notes together.The tray stands for a checkpoint: saved task state and completed results, kept together for recovery.

Imagine a run stopping halfway through a long job. A checkpoint gives its recovery logic a recorded place to begin, including state and completed results.

External changes need separate attention. Restoring a local checkpoint does not undo an order already submitted to another service.

Source & further reading

Technical reference: Persistence ↗

Resumability

The ability to continue interrupted work using retained state and progress.

After power returns, Peanut opens a saved-progress tray holding notes and a base with two attached uprights. In the next scene, Peanut adds a crossbar to that same intact base.
The lights return. Start with the next part.Peanut is the agent resuming work. The base and its two uprights stay assembled; the saved notes guide the next step.

Resuming means restoring the work well enough to continue from retained progress. That involves more than reading a saved file: tools may need to reconnect, permissions may have changed, and an external operation may have completed during the interruption. Recovery logic reconciles those conditions with what the application last recorded.

End of chapter 03

Part I · How agents work

Chapter 04 / 12

Peanut puts tools to work

Tools, connections, and computer use

A proposed action becomes useful when software can carry it out. Start with tool calls and service connections, then look at agents working through browsers, applications, and development tools.

Tool use

An AI system invoking an external capability to obtain information or perform an action.

Peanut writes 2 kg on a job card while parcel 7 rests on a scale showing the same weight.
The scale supplies the weight.Peanut is the agent. The scale performs the measurement; the job card carries its returned result into the next decision.

Tools connect an AI system to capabilities beyond generating a response. A model can request a calculation, search, or record update, and an application or hosted service performs the operation. Its result then becomes available for the next decision. Good tool design makes the purpose, inputs, and returned information easy to interpret.

Side effects

Changes an operation makes to state outside the value it returns, such as updating a record or sending a message.

In two scenes Peanut reads a parcel’s weight, then sends it through a delivery hatch and records it as sent.
Reading the weight leaves the parcel here. Dispatching it changes that.Peanut is the agent in both scenes. The weighing step reads information; the dispatch step changes the world outside the agent.

Sending a message, modifying a file, and creating an order all change external state. These side effects deserve attention because an operation can take effect even if its reply gets lost. Before retrying, establish what happened or use the service's duplicate-protection mechanism. Approval rules should be applied before the protected change occurs.

Function calling

A mechanism for a model to request a named function or tool using structured arguments.

Peanut submits a card specifying weigh and parcel 7, then receives a 2 kg result after the service weighs the parcel.
“Weigh parcel 7” is a request the service can execute.Peanut requests the operation with a tool name and arguments. The service mechanism represents the software that executes it.

The model produces a tool name and structured arguments. Software receives that request, checks it, and invokes the corresponding function. Keeping request and execution separate makes errors easier to locate: the model may choose bad arguments, or a perfectly good call may reach an unavailable service. The returned result lets the workflow respond to either case.

Source & further reading

Technical reference: Tool design ↗

Tool schema

A machine-readable description of a tool's accepted inputs and, where supported, its outputs.

Peanut fills a request with item 7 and destination A while consulting a blank template marking both fields required.
The form asks for an item and a destination. Both boxes matter.Peanut is preparing a tool request. The blank form represents the schema; the filled form is one request that follows it.

Schemas give software an explicit contract for a tool's data. They can declare field names, types, required inputs, and permitted values, often using JSON Schema. Descriptions explain what those fields mean and when the tool is useful. Together, they make a request easier for the model to construct and for the application to validate.

Tool routing

Selecting the tool or execution path appropriate for a request.

Peanut carries a measure job card past paint and cutting tools and reaches for an orange ruler.
A measurement job reaches the ruler station.Peanut is selecting a capability for the task. The ruler is the chosen tool; constructing its particular request comes next.

A stock question belongs with the inventory tool; a calculation belongs with a calculator. Routing makes that selection through rules, a classifier, or model judgment, after which the caller constructs the arguments required by the selected tool.

Tool registry

A catalog that lets software discover available tools and the information needed to invoke them.

Peanut reads a capability card from an indexed drawer; it describes a measuring tool and points to the ruler on shelf 3.
Find the capability card before hunting through the shelves.Peanut is discovering an available capability. The drawer represents the registry and the card describes how to find and use a tool.

A registry helps an application discover tools and their calling information, such as names, descriptions, schemas, and connection details. Think of it as the capability catalog: permissions determine which of its entries a particular task can actually use.

Agent skills

Reusable packages of instructions and supporting resources that guide an agent through a particular kind of task.

Peanut repairs a stool using a folder containing steps, a reference drawing, and a script card, with separate tools beside it.
The repair procedure lives beside the tools.Peanut is the agent. The folder represents a reusable skill package; the screwdriver and other equipment perform the operations it guides.

An agent can load a reusable package of instructions and resources when a task calls for it. In the Agent Skills format, that package centers on a SKILL.md file and may include scripts, examples, or reference material. A skill guides the work; tools perform the operations it requires. One procedure may draw on several capabilities.

Source & further reading

Technical reference: Agent Skills ↗

MCP (Model Context Protocol)

An open protocol through which AI applications discover and access capabilities provided by other programs.

Peanut presents matching request cards to library and tool hatches; the service peanuts return a page and a tool-result sheet.
Different service hatches, one agreed way to ask.Peanut represents the client side of the exchange. Matching cards stand for the common protocol; the hatches offer different capabilities.

MCP gives AI applications and supporting programs a common protocol for discovering and exchanging capabilities. An application's client talks to a server that can expose tools, data resources, or prompt templates. The application decides how to use what comes back. Standardizing the exchange reduces the need to invent a different conversation format for every integration.

Source & further reading

Technical reference: MCP architecture ↗

MCP server

A program that exposes supported tools, resources, or prompts to MCP clients.

A peanut labeled server takes a request at an archive hatch and returns a page, with records stored behind the counter.
At this hatch, the archive page is the service.Peanut represents a software component here: the MCP server providing a capability to a client. The archive supplies the requested data.

An MCP server is the program on the providing side of the protocol. It exposes supported capabilities and handles requests from clients. That program can run on the same computer as the application or on a remote service. Its job may be as straightforward as retrieving files; it need not contain a language model.

Source & further reading

Technical reference: MCP server role ↗

Connector

An integration component that gives an application a supported way to interact with another service.

Peanut retrieves a record through a fitted chute joining its desk to an external records hatch.
The records office now has a route to Peanut's desk.Peanut is using an integration. The fitted chute represents a connector that makes another service’s records accessible.

A connector packages the work of interacting with another service, including authentication and supported retrieval or actions. Its scope depends on the integration and granted permissions; MCP is one possible way to implement the exchange.

API integration

Software built to exchange data or actions with another system through its application programming interface.

An engineer peanut connects ordering and stock counters, then sends item 7 through one tube and receives stock 12 through the other.
Send the item number. Receive the stock count.Peanut is the engineer in this drawing. The connected counters represent programs exchanging API requests and responses.

An API defines an interface another program can call. Integration work makes that exchange usable: constructing requests, authenticating, interpreting responses, and handling failures. An agent can access the integration through a tool. The same connection can also support ordinary software that follows a fixed sequence of calls.

Worked example · Order 17 · installment 1 of 4

A replacement order begins

An agent peanut reads a customer’s damaged-order request, retrieves order 17, and prepares replacement steps beside an operator whose approval is still needed at the closed dispatch hatch.
Order 17 needs a replacement. Start by finding out what was ordered.Peanut is the agent investigating the request. The customer and support operator are people, also drawn as peanuts; the operator’s approval is required before dispatch.

The request is “Order 17 arrived damaged. Please arrange a replacement.” In this fictional workflow, the agent may investigate and prepare the action, while a support operator must approve dispatch.

The application supplies the goal, relevant instructions, and available tools. A replacement-handling skill provides the procedure. The model requests the order record, and the tool returns the details needed for the next decision. At this point, the useful outcome is a grounded understanding of the request and what needs checking next.

Concepts together: AI agent, context engineering, agent skills, tool use, side effects.

Next in the replacement-order example →

Browser automation

Software controlling a web browser to perform actions on web pages.

Peanut searches a browser catalog for a stool, opens the selected ST-001 record, and copies that same reference to its task sheet.
Search the catalog, open the record, copy the reference.The three steps represent browser observations and actions. Browser automation may also be driven by ordinary scripts.

A script or agent can use browser interfaces to navigate pages, fill forms, and read content. When a model chooses the actions, it also needs to interpret the resulting page and recover from unexpected states; browser automation itself does not require AI.

Computer use

An agent operating applications through user-interface observations and actions such as clicks, typing, and scrolling.

Peanut selects plan.pdf in a file window, then attaches that same file through another application's visible controls.
The file moves between applications through the controls on screen.The file crosses applications through their interfaces. An agent must check the screen again after each action.

An agent can observe an interface and act through clicks, typing, and scrolling. This is useful when a service lacks a convenient API. Each action changes the interface the agent will inspect next. Reliable execution depends on recognizing the right controls and recovering when a dialog, layout change, or unexpected state interrupts the route.

Coding agent

An AI agent that uses development tools and feedback to perform software tasks.

Peanut edits a paper program, feeds it into a test machine, and reads a result containing both passes and a failure.
Change the program. Run the check. Read what happened.The test result is feedback for the next decision. A failed check means the agent may have more work to do.

A coding agent uses development tools to inspect a project, make changes, and assess their effects. Tests and other feedback help it decide whether more work is needed. Choose checks that cover the requested behavior and relevant consequences. A passing command only answers the question that command was designed to test.

Sandbox

An execution environment that isolates work and restricts the resources or systems it can affect.

Peanut operates a miniature excavator inside a bounded tray of sand while the surrounding workshop floor remains clear.
The excavator gets a tray of its own.The tray represents restricted reach. Actual containment depends on the execution environment and its configuration.

Isolation limits the resources an operation can affect. A sandbox may restrict filesystem access, networking, processes, or permissions, depending on its design. Those boundaries make it possible to run work with a narrower reach. Assess the actual mechanism and configuration when deciding what protection it provides.

Terminal execution

Running commands through a shell or command-line interface in a computing environment.

Peanut enters ls on a laptop while an attached printer returns a list of project files and folders.
A command goes in; a file list comes back.The paper strip stands for command output. The command's result must be interpreted in the context of the task.

Through a terminal tool, an agent can run programs and operate on its environment. Commands execute with the permissions available there. Output and exit status help establish what happened, but their meaning depends on the program. A zero exit status can confirm successful execution while leaving the broader task unfinished.

Repository context

The project information relevant to making and assessing a code change.

Peanut works on a gear assembly beside a blueprint, workshop rules, and a previous-repair notebook.
Check the machine around the gear before replacing it.The surrounding records represent the project conventions, structure, and relevant history needed to make a change fit.

Source files are part of the picture. Tests, dependencies, project conventions, and relevant history explain how a change should fit. A coding agent needs to inspect the portions that bear on its task. Supplying repository access opens the door to that investigation; useful context comes from selecting and understanding the right material.

End of chapter 04

Part I · How agents work

Chapter 05 / 12

Peanut plans the work and calls for help

Planning and collaboration

Break the job into useful steps, inspect what happened, and decide when to stop. Extra agents can take on bounded work when their contribution justifies the coordination.

Task decomposition

Breaking a larger task into smaller pieces that can be assigned, executed, and checked.

Peanut cuts a host-dinner ticket into smaller tickets for shopping, cooking, and setting the table.
“Host dinner” becomes three jobs someone can begin.Peanut is the agent breaking a goal into subtasks. The tickets keep each smaller job connected to the dinner it is meant to produce.

For a dinner, shopping produces what cooking needs, while setting the table can happen independently. Decomposition exposes those smaller jobs and their dependencies.

Give each subtask a useful output and keep its relationship to the larger goal visible. Otherwise, an agent can complete every item on its list and still leave part of the actual job undone.

Planning

Choosing actions and their dependencies to work toward a goal under stated constraints.

Peanut stands on a stream bank, sketching a proposed route across stepping stones before starting the crossing.
A route is useful before stepping into the stream.Peanut is the agent planning its next work. The sketched route is a proposal that can change when the crossing reveals new information.

A code-change plan might identify the files to inspect, the edit to make, and the checks to run. It provides a starting sequence that can be revised when investigation reveals something new. Plan enough to guide the next work, with room to respond to what the tools find.

ReAct

An approach that interleaves model reasoning, actions, and observations while solving a task.

Peanut tests a dark lamp’s bulb, observes that the bulb works in a tester, then checks the lamp’s unplugged power cable.
The bulb works. Check the plug next.Peanut is the agent. The successful bulb test supplies an observation that changes what it checks next.

ReAct interleaves reasoning, action, and observation. An action gathers information that helps the model decide what to try next, instead of planning every move without feedback. The original method explicitly combines reasoning text with actions. It is one approach to structuring an agent, rather than a label for every system that uses a loop.

Source & further reading

Technical reference: ReAct paper ↗

Plan-and-execute

An agent pattern that creates a plan and then executes its steps, with replanning when needed.

Peanut posts a shelf plan, discovers an uneven wall while measuring, and revises the mounting plan to include wedge spacers.
The wall is crooked. The plan needs a pencil mark.Peanut is carrying out a plan and reporting a surprise. The revised drawing represents the planning stage adjusting the remaining work.

Planning and execution can be separate stages. A planner proposes the work, an executor carries it out, and progress or problems feed back into revisions. Those stages may use different components or models. The practical question is how the executor reports a surprise and who is responsible for changing the remaining steps.

Reflection

A model-based review of an attempt or result used to guide a possible revision.

Peanut compares a leaning cake with a straight reference, marks the middle layer, then levels the cake and compares it again.
That middle layer explains the lean.Peanut is the agent reviewing its attempt. The marked layer is a specific critique; the final comparison checks whether the correction helped.

A model can review an attempt and propose a correction before trying again. Reflection is useful when the review identifies a specific problem the next attempt can address. Give it evidence such as a failed test or a mismatch with the requirement. The critique itself can be mistaken, so assess whether the revision actually improves the result.

Stopping condition

A rule or event that ends a run or a stage of execution.

Peanut sets down an orange polishing cloth beside a finished stool and completed agreed-work checklist, leaving optional polish untouched.
The checklist is complete. The mountain of optional polish remains.Peanut is the agent ending the run after the agreed checks pass. The unused polish represents work outside that stopping condition.

Define completion before the agent starts, and give the runtime clear limits on continued execution. A successful check, deadline, step limit, cancellation, or unrecoverable error can end a run. The final status should say which occurred. Reaching the time limit and completing the task are different outcomes that deserve different messages.

Multi-agent orchestration

Coordinating multiple agents, their responsibilities, and the information they exchange to complete work.

An orchestrator peanut sends a page to a drafter, a checker reviews that page, and the printer processes the checked version.
The draft, the check, and the print job need to meet in the right order.The print job depends on the draft and its check. The orchestrator represents the component coordinating those dependencies.

Multiple agents introduce a coordination problem as well as extra capacity. Someone must assign work, supply context, track dependencies, and combine the results. Separate agents can be useful when tasks benefit from distinct expertise or independent investigation. That benefit has to justify the communication overhead and the work of reconciling their outputs.

Supervisor agent

An agent that assigns, coordinates, or reviews work performed by other agents.

A supervisor peanut points out roof and gutter inspection areas, while two inspector peanuts return their checklists to a supervisor.
Two roof inspections return to one desk.The supervisor assigns bounded inspections and reviews their results. The role remains a model-driven participant whose judgments need evidence.

A supervisor agent decides what to assign and what to do with the responses. It can request more work, compare findings, or assemble a final result. Give it explicit review criteria and access to the relevant evidence. The supervisor is another model-driven participant, so the title alone adds no assurance that its judgment is sound.

Subagent

An agent invoked to handle a bounded part of another agent's larger task.

One peanut checks a cart wheel against a wheel-inspection card while another works on a separate wheel at the larger repair bench.
The assignment is the wheels. The whole cart belongs to a larger job.The wheel assignment is one bounded part of the broader cart repair; the caller integrates its result.

A subagent takes responsibility for a bounded part of another agent's task. It may receive specialized instructions, tools, or its own context. Specify what information travels with the assignment and what should come back. The parent can then evaluate the result and use it in the broader workflow.

Delegation

Assigning a task to another agent or worker with the context, constraints, and expected output needed to perform it.

Peanut hands a helper an orange folder containing a task sheet, stool drawing, and matching measurements.
Hand over the measurements with the job.The assignment travels with the measurements and expected result, so the recipient can act without guessing the missing context.

“Inspect this” leaves quite a lot for the recipient to guess. A useful delegation includes the goal, relevant context, constraints, and expected output. It also identifies what counts as finished. The caller remains responsible for integrating the returned work, including resolving gaps or contradictions with other parts of the task.

Handoff

Transferring control or responsibility to another participant, along with the context needed to continue.

An outgoing peanut passes a notebook and points to an unfinished bridge joint; the incoming peanut reads the notebook and works at that joint.
The next shift needs to know about that unfinished joint.The notebook carries context while responsibility for continuing the work moves to the incoming participant.

A handoff transfers responsibility for continuing the work. In an agent application, it may move a conversation and selected state to a specialist. Decide what control transfers, what context is carried, and where any later response should go. Delegation usually returns a subtask result to a caller; a handoff emphasizes who takes over next.

Parallel execution

Executing multiple pieces of work concurrently where their dependencies permit it.

Three peanuts inspect separate parcels under a shared clock.
Three independent parcels, one stretch of the clock.The parcels stand for independent tasks that can overlap in time. Dependencies and shared resources can still require coordination.

Three independent searches can run during the same period instead of waiting in a queue behind one another. That may shorten the task, even when total resource usage stays the same or rises.

Dependencies decide what must wait. Shared files and records also need coordination so concurrent workers do not overwrite one another’s changes.

End of chapter 05

Part I · How agents work

Chapter 06 / 12

Peanut visits the library

Retrieval and grounding

An answer needs the right evidence. Follow a document from representation and search to the claims it can actually support. Retrieval and generation can each fail, so inspect both.

RAG

Retrieval-augmented generation: retrieving relevant information and supplying it to a model to help generate a response.

Peanut writes beside an open kettle manual while the broken kettle sits unplugged on the workbench.
The relevant manual page earns a place beside the answer.The open manual is retrieved context supplied for the answer. Its relevance and the answer's use of it both need checking.

RAG adds retrieved material to the context used for generation. The application searches an external collection, selects results, and supplies them to the model. Retrieval might use keywords, vectors, or another method. The quality of the answer depends both on finding useful evidence and on using it accurately, so evaluate those steps separately.

Embeddings

Learned numerical representations of data that allow software to compare items by relevant features.

A builder peanut feeds a passage into an embedding machine, which produces a list of numbers; a peanut places the resulting marker on a two-dimensional map.
A passage becomes a point on the map.The map compresses a numerical vector into two dimensions. Nearby points mean similarity under the model and comparison method, rather than a universal map of meaning.

An embedding model turns data into a vector, a list of numbers encoding learned features. Software can compare these representations to find related text, images, or other items. The illustrated map compresses many dimensions into two. What proximity means depends on the embedding model and the similarity measure used.

Vector search

Retrieving items by comparing their vector representations with a query vector.

Peanut uses a large compass around an orange query marker to identify nearby document markers.
Start with the document markers closest to the query.The compass simplifies a similarity comparison between a query vector and stored document vectors.

Vector search compares a query representation with stored representations and retrieves nearby matches. Similarity measures such as cosine similarity define the comparison. Larger collections often use approximate search to keep retrieval fast. Judge the results against the actual query: a close vector is evidence of similarity, rather than proof that a document is relevant or true.

Source & further reading

Technical reference: Vector search ↗

Hybrid search

Combining different retrieval methods, commonly keyword search and vector search, into one search process.

Peanut combines cards from keyword and similarity trays into a central hybrid-results tray.
One pile matches the words. Another finds related wording.The two trays represent separate retrieval signals. The application combines their candidates or scores before choosing what to use.

Exact identifiers and broader meaning can both matter in a search. Hybrid retrieval combines methods, commonly keyword and vector search, so each can contribute candidates. The system then merges their results or combines scores. How those signals are balanced influences which documents reach the model, making that combination worth evaluating on real queries.

Source & further reading

Technical reference: Hybrid search ↗

Reranking

Reordering an initial set of search results using an additional relevance assessment.

Peanut checks a shortlist against a detailed checklist and moves a highlighted candidate to the front of the rack.
The shortlist gets a closer inspection.The closer inspection represents an additional relevance assessment applied after initial retrieval.

Retrieval produces candidates; reranking assesses their relevance again to improve the order. A reranker often reads the query alongside each candidate's content, spending more effort on a smaller set. This makes the initial shortlist important. A relevant document excluded at retrieval has no chance to move up during reranking.

Source & further reading

Technical reference: Semantic reranking ↗

Hallucination

Model-generated content that is presented as factual but is incorrect or unsupported by the available evidence.

Peanut writes a reference titled Quantum Peanut Routing on a sheet, then checks it against an archive shelf marked not found.
A very convincing reference to a book the archive has never owned.The sheet is an invented citation. A plausible reference needs verification against the source it claims exists.

Fluent output can contain invented facts, nonexistent citations, or claims that contradict the source. This is the failure usually described as hallucination. Check factual claims against appropriate evidence, particularly when the output will drive another action. Supplying reference material helps only when the generated answer actually follows what that material supports.

Source & further reading

Technical reference: Hallucination ↗

Grounding

Connecting a model's response to relevant source information or observations that support its claims.

Peanut pins a thirty-centimetre stool claim beside its matching measurement slip. A separate claim about the material has a question mark where supporting evidence should go.
This claim has a measurement behind it.The measurement supports the height claim. It supplies no evidence for the separate material claim.

Grounding connects an answer to information that supports it. That information might come from a document, a database, or an observation returned by a tool. Check the relationship between claim and evidence, including whether the source is reliable. A citation attached to an unrelated passage provides a link without providing support.

End of chapter 06

Part I · How agents work

Chapter 07 / 12

Peanut handles a difficult day

Reliability, permissions, and safety

Requests fail, replies disappear, and apparently useful data can carry hostile instructions. Reliable work needs recorded progress, limited authority, and a clear way to involve a person.

Retries

Repeating an operation after a failure or an uncertain result.

A ticket request meets a blocked service, Peanut waits while a worker repairs the obstruction, and Peanut submits another attempt after the barrier opens.
The jam clears. Now another attempt has a chance.The pause represents a retry delay. Another attempt is useful when the failure can plausibly change.

A temporarily unavailable service may recover before the next attempt. A request with a missing required field needs correction. Those failures deserve different responses.

A retry policy specifies eligible failures, spacing, and limits. For an operation with side effects, also account for the possibility that the first attempt took effect despite the reported problem.

Source & further reading

Technical reference: Timeouts, retries, and backoff ↗

Timeouts

Limits on how long software waits for an operation or allows it to run.

Peanut waits at a service hatch beside an hourglass; after it runs out, Peanut marks timed out while the clerk continues working.
The hourglass is empty. The clerk may still be working.The timeout ends the caller's wait. It does not establish whether the remote operation has stopped or failed.

A timeout ends an allowed wait or execution interval. From the caller's perspective, it says the result did not arrive in time. A remote service may continue working after that point. Before repeating a consequential request, check its status or use an appropriate duplicate-protection mechanism. This uncertainty is exactly why timeout handling matters.

Source & further reading

Technical reference: Timeouts and retries ↗

Idempotency

The property that repeating an operation has the same intended effect on system state as performing it once.

Peanut presents two copies of request 17. A clerk checks the ledger and makes only one parcel for that request.
Two copies of request 17. One parcel leaves the hatch.Matching identifiers let the service recognize repeated attempts as one operation under its duplicate-handling contract.

Suppose a service creates an order but its reply is lost. With a supported idempotency key, the caller can identify a retry as the same operation instead of a new order. The server implements that duplicate handling under its own contract. Idempotency concerns the intended effect on state; repeated calls need not produce identical response text.

Source & further reading

Technical reference: Idempotent requests ↗

Structured outputs

Model results produced in a defined machine-readable structure, often constrained by a schema.

Peanut writes a stool result into three labeled form fields: item, quantity, and status.
The answer arrives in the fields the next step expects.The form represents a machine-readable shape. The application still needs to check whether the values are right.

Suppose the next step expects an item identifier, quantity, and status. A structured response supplies those named values directly, with some systems enforcing the schema during generation.

The application can then parse the result predictably. Checking whether it names the right item is a separate task.

Schema validation

Checking data against rules for its structure, types, and permitted values.

A validator peanut compares a shipping form with its schema and marks the empty destination field.
One empty destination box is enough to stop this form.The template represents structural rules. Passing those rules would not establish that a destination belongs to the right customer.

A validator compares data with declared rules for fields, types, and permitted values. It can catch missing information before the next operation runs. The scope of that check matters: a correctly shaped address can belong to the wrong customer. Business rules and factual checks handle questions beyond the schema's contract.

Source & further reading

Technical reference: JSON Schema ↗

Fallback

An alternative path used when the preferred method is unavailable, fails, or cannot meet requirements.

Peanut turns a hand grinder beside an electric grinder bearing an unavailable tag.
The hand grinder is about to have a busy afternoon.The hand grinder is an alternate route permitted by the workflow when the usual route cannot be used.

When the preferred path fails, a fallback offers another acceptable way to proceed. That may mean another tool, another model, or a person taking over. Choose it with its capabilities and operating limits in mind. A slower route can be entirely suitable if it meets the task requirements and preserves the same access restrictions.

Durable execution

Executing a workflow with persisted progress so it can recover across failures and interruptions.

A parcel line pauses with two dispatches marked complete; Peanut consults a persisted ledger, then resumes handling the unfinished parcel.
The ledger remembers which parcels already left.The ledger records completed effects and remaining work so recovery can reconcile them before continuing.

Durable execution combines persisted progress with recovery behavior. After an interruption, the workflow uses recorded state and results to resume or replay work safely. Operations in external services need special care because recovery can otherwise repeat their effects. Recording progress and protecting those operations work together to make continuation dependable.

Source & further reading

Implementation reference: Temporal workflow execution ↗

Guardrails

Checks and constraints that aim to keep an AI system's inputs, actions, or outputs within defined bounds.

Peanut pushes a loaded cart along a guarded ramp toward a cargo inspection point.
The ramp has rails. The cargo gets checked too.The rails and inspection stand for constraints and checks around execution. They reduce particular risks under their actual design.

Guardrails can act at several points: incoming requests, proposed tool calls, and generated outputs. Some apply explicit rules; others use models to assess content and can make classification errors. Decide what each check covers and how the application responds to its result. A rule that only produces an ignored warning provides little control over execution.

Least privilege

Giving an actor only the permissions needed for its authorized work.

Peanut takes one orange key for the needed supply drawer while a large master-key ring stays on its hook.
The supply drawer needs one key. The master ring stays put.The single key represents only the authority required for the task.

Start with the access the task requires. If the work only reads a particular collection, grant read access to that collection rather than broad write permissions. Limits can apply to scope and duration. This reduces how far a mistake or manipulated request can reach and makes permissions easier to review when the task changes.

Human-in-the-loop

Including a person at defined points to review, guide, correct, or decide within a system's workflow.

Peanut prepares a parcel and presents its destination record to a peanut labeled human reviewer, who records a decision.
The reviewer checks the destination before the parcel moves on.The reviewer represents a real person participating in the workflow. The system must make the relevant evidence available for that decision.

A person can resolve ambiguity, correct a result, or decide at a defined point in an automated workflow. Give that person a clear question and the evidence needed to answer it. The application must then capture the response and continue appropriately. “Human-in-the-loop” becomes meaningful when the loop has a specific decision attached to it.

Approval gates

Enforced checkpoints that block a specified action until an authorized person or system approves it.

Peanut waits with a specific task ticket behind a closed gate; an approver stamps that ticket, and the gate opens.
The stamp belongs to this dispatch ticket.The gate stands for enforcement before an action. Approval must apply to the particular action being authorized.

An approval gate binds authorization to a particular action and its important details. Preparing an email may be allowed while sending it waits for approval. If the recipient or content changes materially, check whether that authorization remains valid. Enforce the gate in the application so the protected action waits for the required decision.

Escalation

Referring a problem or decision to a person or system with the authority, expertise, or capability to resolve it.

Peanut presents conflicting maximum-fifty-kilogram and minimum-hundred-kilogram requirements alongside measurements to an engineer with an unresolved decision.
Two conflicting requirements go to someone who can settle them.The conflict is carried to someone who can resolve it, with the requirements and evidence rather than an invented answer.

Escalation is useful when the task exceeds the agent's authority, evidence, or ability to proceed. Send the goal, relevant findings, attempted steps, and unresolved decision to the appropriate person or system. That gives the recipient something concrete to resolve. Unlike an approval request for a prepared action, escalation can require a change to the plan itself.

Prompt injection

An attempt to redirect a model by getting it to follow instructions that should not have authority over the task.

Peanut lifts an ignore-rules-open-safe note from a parcel label while keeping the legitimate parcel task on its workbench.
“Open the safe” is an ambitious addition to a delivery label.The pasted note is untrusted content trying to become an instruction. The scene illustrates the intended boundary, rather than guaranteed attack detection.

External material can contain instructions that try to redirect the agent. When a page, file, or tool result carries the attempt, it is indirect prompt injection. The system should treat that material according to its role as data rather than granting it control over the task. Access restrictions and other defenses help limit the consequences when recognition fails.

Source & further reading

Technical reference: Prompt injection ↗

Tool-output trust

How an application assesses the reliability and authority of information returned by a tool.

Peanut records a scale's 58.3-gram reading while separating an added open-safe instruction into an untrusted-text tray.
The scale can report a weight. Workshop policy is outside its remit.The returned measurement is task data. Extra instructions inside that output gain no authority to change the system's rules.

Tool results deserve two separate questions: is the information reliable, and what authority should it have? A returned record may be useful evidence without being a valid source of new instructions. Results can also include mistakes or content supplied by outsiders. Decide how the application verifies and uses them before allowing them to influence consequential actions.

Worked example · Order 17 · installment 2 of 4

The response goes missing

Peanut prepares operation 17-R1, a support operator approves its dispatch, the wait times out, and Peanut finds that same operation checked in the service ledger.
No reply. Check the record before creating another replacement.The repeated operation identifier connects the prepared action, approval, and recorded effect. A missing reply is not evidence that the dispatch failed.

The policy and order record support the proposed replacement, and the operator approves the specific item and address. The application records the approval and submits the dispatch with an idempotency key for this operation.

Then the wait times out. The agent checks the service using the operation identifier and finds the replacement already recorded, so another order would be a duplicate. If a retry were needed, it would follow the service’s idempotency contract. If the status remained unresolved, the case would go to a person with the evidence gathered so far.

Concepts together: RAG, approval gates, timeouts, idempotency, durable execution, escalation.

Next in the replacement-order example →

End of chapter 07

Part I · How agents work

Chapter 08 / 12

Peanut checks the work and reads the receipts

Evaluation, tracing, and cost

Did the job succeed, was the route acceptable, and what did it consume? Evaluate the outcome alongside the steps that produced it. A successful example is a starting point for measurement.

Agent evals

Systematic tests that assess an agent's behavior and results against defined criteria.

Peanut pushes a cart through a test yard with ramp, rocks, and gap obstacles while an evaluator records the specified checks.
The cart gets the agreed obstacles, not the convenient ones.The yard represents a defined set of evaluation tasks and grading criteria, rather than an ordinary successful demonstration.

An evaluation suite pairs representative tasks with criteria for judging behavior and results. Graders may be code, people, or models. Include failures that matter in the intended use, and repeat trials where run-to-run variation is significant. The suite becomes useful engineering feedback when its results point to something the team can investigate or improve.

Source & further reading

Technical reference: Agent evaluations ↗

Task success rate

The proportion of evaluated tasks or runs that satisfy the defined success criteria.

Peanut checks ten numbered parcels against one checklist. Seven have pass marks and three have failure marks, with 7/10 explicitly labeled example.
Seven deliveries pass the complete checklist. Three need attention.This is fictional test data. A success rate needs a defined task set and consistent criteria for the whole task.

For this illustrative test, seven successes out of ten evaluated deliveries gives a 70% success rate. Be explicit about the denominator: tasks, runs, and attempts can produce different measures. Also state the criteria and how retries count. That information lets a reader interpret the percentage and compare it fairly with another result.

Trajectory evaluation

Assessing the sequence of an agent's actions and observations, rather than only its final output.

Peanut completes a delivery, then an evaluator identifies on the recorded map that its route crossed a prohibited garden bed.
The parcel arrived. The footprints cross a prohibited garden bed.The destination was reached, but the route violated a constraint. Outcome and trajectory need separate assessment.

The delivery succeeded, but the route violated a constraint. A final-output check would miss that.

Trajectory evaluation examines actions and observations for behavior such as missed approvals, unsuitable tools, or wasteful loops. Allow valid alternative routes unless the task specifically requires one sequence.

Source & further reading

Technical reference: Evaluation of agent runs ↗

Tool-call accuracy

A measure of whether an agent's tool requests use appropriate tools and arguments for the task.

Peanut compares a cut-ten-centimetres request with a cutter whose length control is set to ten centimetres.
Right cutter, right length, right job.The call is checked for both tool selection and arguments. A correctly formed request can still need an outcome check.

Evaluate the selected tool and its arguments against the task's requirements. This separates a mistaken request from an execution failure at the service. A valid call to the wrong record is a tool-call problem even if the service reports success. Clear scoring criteria help identify which part of selection or argument construction needs work.

Regression testing

Re-running established checks after a change to detect behavior that has worsened or broken.

Peanut bolts an attachment onto a cart, then checks that the modified cart passes through the existing doorway test.
The new attachment must survive the old doorway test.The old clearance check is rerun after the change to detect damage to previously working behavior.

Changes to a prompt, model, tool, or retrieval setup can disturb behavior that used to work. Re-run established checks to catch that deterioration. Keep the test conditions comparable and use repeated trials where necessary to account for variability. A stable evaluation set gives the team a shared basis for discussing whether the new version is better.

Tracing

Recording connected execution events so a request or run can be inspected across its steps and services.

Four vignettes follow Peanut's request, a drill operation, its recorded result on a receipt spindle, and the next action.
The receipts will be useful when someone asks what happened.The receipts represent recorded events from execution. They provide evidence for inspection, rather than a transcript of private model reasoning.

Tracing connects recorded operations from the same request or run. Model calls, tool results, timings, and errors become easier to investigate when their relationships are preserved. Instrumentation determines what is visible. Use a trace to reconstruct observed execution, without treating it as a complete account of the model's internal processing.

Source & further reading

Technical reference: Traces ↗

Execution trajectory

The ordered sequence of actions, observations, and relevant decisions made during a particular run.

Peanut arranges six action cards in order: plan, gather parts, fix a tool during a detour, assemble, test, and finish.
This particular job took a detour.The detour belongs in the record because a trajectory describes the route actually taken.

The trajectory is the path a run took through actions, observations, and relevant decisions. A trace can supply the records needed to reconstruct it. Comparing trajectories helps explain why similar requests produced different outcomes. Sometimes the difference is a tool failure; sometimes it is a different decision made from the available context.

Spans

Recorded units of work within a trace, each with timing and contextual information.

Peanut measures, wraps, and labels a parcel beneath a bracket for the entire packing job and smaller brackets for its steps.
Measuring, wrapping, and labeling each take their own slice of time.The long bracket represents a parent span; the shorter brackets represent child operations within it. The picture simplifies recorded timing.

A span records a unit of work with timing and contextual attributes. Parent-child relationships show operations performed within another operation. Concurrent spans can overlap, so adding their durations may exceed total elapsed time. This structure helps distinguish a slow tool from time spent elsewhere in the larger request.

Source & further reading

Technical reference: Spans ↗

Token budget

An allowance or limit on token usage for a defined model call, task, or period.

Peanut works with a finite stack of small text-piece tokens beside a used-and-remaining budget gauge.
There is a finite allowance for this job.The pieces stand for tokens, which can be parts of words or other encoded units. The gauge represents an allowance for model processing and generation.

Set the scope of the allowance first: one call, a whole task, or an accounting period. Then specify how input, output, and reasoning usage count toward it.

A task budget can cover many model calls. The context window constrains a single inference context; the token units themselves are explained in Tokens and tokenization.

Latency

The elapsed time between a defined start event and the corresponding response or completion event.

Peanut starts a stopwatch when handing over a stool order, waits through processing, and stops it when the stool arrives.
Start the clock at the request. Choose where to stop it.The interval includes the wait for the result, not only the time spent generating a model response.

Time to the first output and time to task completion measure different experiences. Pick the interval that answers your question, then account for model calls, queues, tool waits, and retries within it. A faster initial response may coexist with a slow overall workflow. Name the metric when comparing versions or describing performance to users.

Cost per task

The cost attributed to completing or attempting one task under a stated accounting method.

Peanut gathers model, tool, and compute receipts into a job envelope beside a totals sheet and a labeled example of average cost per task.
The model receipt is only one item in the envelope.The envelope collects the costs attributed to the work. The separate arithmetic is a fictional example, not a quoted service price.

Decide which expenses belong to a task before calculating its cost. Token charges, tools, compute, and human review may all be relevant. Cost per attempt and cost per successful task tell different stories when failures are common. Use a consistent accounting boundary so a seemingly cheaper approach is not just leaving part of the bill elsewhere.

Worked example · Order 17 · installment 3 of 4

Check the result and the route

An evaluation sequence checks the requested item and address, approval time, a single dispatch record, and the timeout record; a stopwatch and cost receipts sit at the end.
One replacement, the correct address, and approval before dispatch.The records are evidence for the evaluator. A lost reply is checked against the actual dispatch, approval, latency, and cost.

A successful dispatch answers only part of the evaluation. The reviewer also checks whether the agent used the correct details, obtained approval at the right time, and avoided a duplicate after the timeout. The recorded trajectory supplies evidence for those checks.

This run belongs in a broader suite with missing records, ineligible requests, and denied approvals. Repeating the suite after changes helps detect regressions. Timing and cost records answer a different question: what it took to complete the work.

Concepts together: Agent evals, trajectory evaluation, tracing, regression testing, latency, cost per task.

Next in the replacement-order example →

End of chapter 08

Part II · Building agents people can use

Chapter 09 / 12

Peanut learns how this place works

Customers, workflows, and constraints

The protagonist now plays an engineer. Before building, watch the work, identify the records people rely on, and learn who owns the decisions. A useful system must fit that setting.

Forward Deployed Engineer (FDE)

An engineer who works closely with customers to build and deploy solutions in their operational environment.

An engineer peanut brings a workbench into a customer's warehouse, observes an operator handling a parcel, and works beside the operator at the conveyor controls.
The workbench arrives in the customer's packing room.Peanut is the engineer here. The customer and operator are people whose real workflow shapes the technical work.

An FDE works closely with customers to turn technical capabilities into systems that fit their operations. That can involve discovery, integration, evaluation, implementation, and deployment. The exact remit varies by company. The common thread is proximity to the customer's problem and feedback, whether the engineer works on-site, remotely, or through a mixture of both.

Source & further reading

Role example: OpenAI’s deployment approach ↗

Customer discovery

Investigating customers' problems, needs, and constraints before deciding what solution to build.

An engineer peanut takes notes beside a customer confronting a difficult return parcel.
Sit beside the difficult return before proposing a new process.The conversation takes place at the point of difficulty so the engineer can investigate how the work actually happens.

Begin with evidence about the customer's problem: who encounters it, how often, and what they do today. Observation and interviews can uncover needs that a feature request leaves implicit. Record what you learned alongside what remains uncertain. That gives the build a concrete problem to address and assumptions to test.

Workflow mapping

Representing the steps, decisions, inputs, outputs, and handoffs in a process.

An engineer peanut traces an order route with orange string between marked handovers while customer and operator peanuts stand nearby.
Follow the order through every desk and handoff.The string follows movement of work and responsibility, including the places an order changes hands.

A workflow map makes the process visible enough to discuss. Include inputs, decisions, owners, and exceptions, as well as the usual sequence. This helps identify where an AI component could fit and which upstream and downstream steps it depends on. The returns path may tell you more about the design than the cleanest happy-path example.

Process discovery

Finding out how work actually happens, including variations and undocumented steps.

An engineer follows the documented route of a file cart, then discovers an operator's additional sticky-note check.
The unofficial sticky-note desk is doing quite a lot of work.The extra stop represents a step revealed by observation that was missing from the documented process.

Processes often contain steps absent from their documentation. Following real work, interviewing participants, and examining event records helps uncover them. Discovery gathers that evidence; mapping represents the resulting understanding. Pay attention when the stated procedure and actual practice disagree, because the extra step may be compensating for a constraint the new system must address.

Use-case scoping

Defining the specific problem, users, boundaries, and deliverables for a proposed solution.

Peanut places an orange frame around sort incoming returns on a large warehouse floor plan while customer and operator peanuts watch.
This build covers incoming returns. The rest of the warehouse can wait.The frame bounds a specific problem and leaves the surrounding operation outside the first scope.

Scope defines the problem and the boundaries of the commitment. Identify the users, supported inputs, permitted actions, and expected deliverables, including how exceptions will be handled. These choices make implementation and evaluation possible to plan. They also give the team a basis for deciding whether a new request belongs in the current work.

Success criteria

The observable conditions used to judge whether a project or system achieves its intended outcome.

An engineer and a customer agree on an unchecked success list naming correct item, no duplicates, and operator review before building begins.
Agree on the finish checks while the workbench is empty.The empty checks are agreed conditions to assess later. They are not a claim that a system has already passed.

Success criteria connect the project to an observable outcome. They might concern correctness, turnaround time, operator effort, or failure handling. State how the result will be measured and over what period. Agreement early in the work gives everyone a common basis for judging the finished system, beyond whether its demonstration looked promising.

Systems of record

Systems designated as authoritative sources for particular business records or fields.

An engineer consults a designated inventory ledger while customer and operator peanuts hold separate stock notes.
Two stock notes disagree. Check the designated ledger.The ledger is the agreed authority for this record. Conflicting copies need reconciliation with that authority.

A business may designate one system for customer identity and another for invoices. Integration work needs to respect which system owns each record or field, both when reading data and when sending updates. That designation establishes authority for the record, while data-quality checks address whether its contents are accurate.

Data access

The authorized and technically supported ability to retrieve or use particular data.

An engineer presents an access pass at a customer-records hatch and receives a permitted folder.
The folder is available. This pass determines which one.The hatch represents controlled access to the required data, rather than unrestricted access to every customer record.

Useful data needs both a working access path and authorization to use it. Credentials, record scope, and allowed operations determine what an application can retrieve or change. Carry those boundaries through search and tool use. Reading one collection should not silently expand into access to every record held by the service.

Integration surface

The interfaces and supported touchpoints through which a system can connect with other software.

Peanut inspects a machine's service hatch, socket, and export drawer.
Inspect the available hatches before designing the connection.The accessible connection points represent supported ways to exchange data or actions with an existing system.

APIs, webhooks, exports, databases, and user interfaces offer different ways into a system. Each comes with its own capabilities and constraints. Establish what is actually supported before committing to an automation design. The available integration surface often determines whether a proposed workflow is straightforward, fragile, or dependent on further work from another team.

Stakeholder mapping

Identifying the people and groups affected by a project, along with their roles and decision authority.

An engineer arranges responsibilities at a workbench with customer, operator, and approver peanuts beside their cards.
The user, owner, and approver may be three different peanuts.The roles identify who uses the result, who owns requirements, and who authorizes decisions.

A project affects more people than its most visible user. Identify who operates the system, owns its data, authorizes changes, and supports it when something fails. Map their responsibilities and decision authority. This helps the team bring in the right people before an unresolved dependency becomes a late-stage surprise.

Domain constraints

Requirements and operating realities specific to the field or business in which a system is used.

An engineer measures cold-room door clearance beside a cart drawing and temperature requirements while a customer watches.
The cart has to fit through the cold-room door.Physical clearance and temperature stand for constraints from the operating domain that the design must satisfy.

Domain knowledge changes what counts as a valid solution. Operating deadlines, specialist terminology, data rules, and required decisions all shape implementation and evaluation. Gather these constraints from the people and systems doing the work. A technically successful prototype can miss its purpose if it solves a version of the problem that never occurs in practice.

End of chapter 09

Part II · Building agents people can use

Chapter 10 / 12

Peanut builds something worth trying

Building and proving value

Build beside the people doing the work. Use prototypes to test assumptions, a proof of concept to test feasibility, and a pilot to learn from real operation. Agree on what the evidence must establish.

Forward deployment

An engineering approach that brings implementation close to a customer's real operating context.

An engineer moves a workbench from the lab, then fits a control device beside an operator in the customer's warehouse.
Build beside the conveyor that will actually use it.The work moves into the customer's operating setting, where actual equipment and routines shape the solution.

Close contact with users and existing systems lets engineering respond to the customer’s actual operating constraints as the solution develops. That is the purpose of forward deployment. The arrangement can be remote or on-site; what matters is access to the real work and feedback.

Embedded engineering

Engineering work carried out as part of, or in close ongoing collaboration with, another team.

An engineer takes a seat at a shared operations bench and repairs a recurring tool problem while an operator continues nearby.
Peanut has a regular seat at the operations bench.The regular place at the bench represents ongoing participation in another team's work.

Embedded engineers participate in another team's ongoing work and develop context through that involvement. The team may be internal or customer-facing. Shared routines make it easier to notice recurring problems and understand why earlier fixes failed. The term describes the working relationship rather than a single standardized job description.

Solution engineering

Designing and validating a technical solution around a customer's requirements and existing systems.

An engineer fits a scanner and labeler onto an existing trolley while a customer points to the order requirements.
The scanner, labeler, and existing trolley have to work together.The equipment must work together around the customer's requirements and existing systems.

The work can include architecture, integrations, feasibility checks, and demonstrations, all organized around the customer’s requirements. Some companies place solution engineering mainly in pre-sales; others extend it into delivery. Clarify the responsibilities locally, especially where they overlap with an FDE role.

Rapid prototyping

Building a limited version of a solution quickly to test a specific assumption or design choice.

An engineer runs parcels down a taped cardboard chute while an operator records where they catch.
A cardboard chute can answer the first question.The temporary chute is enough to test an early assumption. Its shortcuts remain visible.

Choose the assumption you need to test, then build enough to test it. A prototype might reveal whether users understand a flow or whether a model can handle representative documents. Record the shortcuts and conditions behind the result. That gives the next stage useful evidence and a clear view of what remains to be built.

Proof of concept (PoC)

A bounded test of whether a proposed technical approach is feasible under specified conditions.

An engineer operates a small lifting rig with a representative crate off the ground while customer and operator peanuts observe.
The crate is off the ground. That answers the first question.The lift establishes feasibility for this bounded test. Wider operating conditions remain separate questions.

A proof of concept establishes feasibility within specified conditions. For an AI extraction task, that might mean testing required fields on a selected document set. Report the evidence and the boundaries together. Scale, integration reliability, and unfamiliar inputs can remain open questions even when the core technical approach works.

Pilot

A limited trial of a solution with real users or work in its intended operating environment.

An engineer and an operator test one marked pilot station while the surrounding warehouse continues its normal work.
One real station gets the first trial.The trial uses a limited slice of the real environment so its usefulness and exceptions can be observed.

A pilot puts the solution into a bounded slice of its intended environment. Real users and exceptions reveal how it fits into the workflow and what support it needs. Define the users, duration, operating limits, and success measures. The outcome should help the team decide whether to expand, revise, or stop.

Acceptance criteria

Specific, testable conditions a deliverable must satisfy to be accepted.

An engineer delivers a cart with agreed requirements; a customer checks its dimensions, load, and brakes before accepting it.
Check the delivered cart against the agreement.The requirement ticket defines what this deliverable must satisfy. The customer checks the delivered result against it.

Acceptance criteria translate requirements into tests for a particular deliverable. They may specify supported inputs, required behavior, or how failures are reported. Agree on them before delivery where possible. Broader success criteria describe the intended outcome; acceptance criteria establish what this piece of work must satisfy to be accepted.

Baseline

A measured reference point used to compare the performance or outcomes of a change.

An engineer times manual packing and records the baseline beside a marked future-test area.
Measure the current packing process before replacing it.The current process supplies a measured reference. The later comparison needs comparable cases and conditions.

Compare the new workflow with a measured reference: the existing human process, a simpler automation, or the current model version. Keep the workload and measurement conditions comparable.

If the new version gets easier cases, the result tells you less about the improvement than the headline suggests.

Business impact

The effect of a system or change on outcomes that matter to the organization.

Peanut compares before-and-after tally sheets alongside order records, effort logs, and operating-cost receipts.
Count the completed orders and the effort behind them.The records represent outcomes and the effort behind them. A comparison still needs to account for other causes of change.

Technical performance becomes business impact when it changes an outcome the organization cares about. Look at service quality, effort, revenue, or rework alongside implementation and running costs. Use a comparison that accounts for other changes in the business. A before-and-after difference is useful evidence, but by itself it does not establish what caused it.

End of chapter 10

Part II · Building agents people can use

Chapter 11 / 12

Peanut keeps the doors open

Production and operations

A working demonstration needs operating support before it can become a dependable service. Access, recovery, monitoring, and ownership deserve deliberate engineering.

Productionization

Preparing a prototype or early system for reliable, supportable operation in its intended environment.

An engineer adds service access, fault indicators, and operating instructions to a working machine while an operator handles its output.
The prototype now needs a repair manual of its own.The operating mechanism needs ways to inspect, repair, and support it during regular use.

Regular operation asks more of a system than a successful demonstration. Productionization addresses the requirements for its actual workload: access control, recovery, monitoring, testing, deployment procedures, and support ownership. The list depends on the environment and consequences of failure. Real usage will continue to reveal operating needs after the first release.

Deployment

Putting a software version or system into a target environment where it can run.

An engineer installs a tested control device at its station; an operator uses it after it becomes available.
The tested device reaches its intended station.Installation puts the version into its target environment. Making behavior available to users can be a separate release step.

Deployment puts a version into an environment where it can run, whether development, staging, or production. Releasing its behavior to users can be a separate decision controlled by a feature flag or rollout process. Track which version is running and how to recover from a problematic change. Those details matter when several versions coexist.

Identity and access management

The policies and systems used to manage identities and control their access to resources.

An access-steward peanut checks an operator's identity and permitted tools, releases a hammer, and keeps the drill cabinet locked.
Check the badge, then the permission for this cabinet.The badge represents authentication; the per-resource permissions represent authorization enforced by the protected system.

Authentication establishes who or what is making the request. Authorization determines which actions that identity may perform on which resources. An agent application may use a service identity or delegated user access. The protected system should enforce those permissions, so a model's proposed action is subject to the same access checks as any other request.

Secrets management

Managing sensitive credentials throughout their storage, distribution, use, rotation, and revocation.

An engineer presents an access card to retrieve a credential from a controlled cabinet; later, the engineer returns an expired credential while its replacement waits on the cabinet hook.
Borrow the credential through the cabinet. Replace it when due.Peanut is the engineer managing credentials here. Access, replacement, and expiry belong to a controlled process; no secret values are shown.

Applications use API keys and access tokens to reach protected services. Secrets management governs their storage, distribution, rotation, and revocation. Supply credentials to the component that needs them and control who can retrieve them. Avoid spreading them into prompts or logs where their presence expands exposure without helping the task.

Monitoring

Continuously or periodically observing system signals to track operation and detect problems.

An engineer holds a clipboard and points to a running pump's pressure gauge, whose orange needle lies beyond the marked normal band.
The pressure needle moves outside its usual range.The abnormal signal prompts attention while the system operates. The drawing shows detection; the response depends on the situation.

Monitoring observes the system while it operates. Error rates, latency, and cost can reveal trouble; sampled quality checks can reveal poor answers from an otherwise available service. Choose signals that reflect the intended use and attach alerts to a response someone can carry out. A dashboard is most useful when its changes lead to informed action.

Incident response

The coordinated process of identifying, containing, and recovering from an operational incident.

An engineer closes a valve beside a leaking pipe, repairs the affected section, and checks restored service before reopening it.
Close the affected valve before repairing the leak.The sequence represents containment, repair, and recovery, with verification before normal service resumes.

During an incident, the team needs to understand impact, contain the problem, and restore service. For an AI application, the issue could involve failed dependencies, incorrect actions, or exposed data. Preserve evidence as the response proceeds and communicate with affected people. Once service is restored, investigate the cause and address what allowed the failure to occur.

End of chapter 11

Part II · Building agents people can use

Chapter 12 / 12

Peanut helps the next team use it

Adoption and reusable products

People need practice and support as their workflow changes. Use what happens in real work to improve the system, then decide which parts can serve other teams consistently.

Change management

Organizing how people and processes move from an existing way of working to a new one.

An engineer walks operators along a changed packing route with updated signs and an available help station.
The new route needs new signs and someone available on the first shift.The signs and first-shift support help people move from the old routine to the new one.

Introducing a system can change responsibilities, review steps, and exception handling. Change management prepares people and processes for that transition. Plan around actual workloads, provide support during the change, and listen to what becomes difficult in practice. The technical release date is only one part of moving a team to a new way of working.

User enablement

Giving users the knowledge, practice, and support needed to use a system effectively.

An engineer demonstrates a task to an operator, then remains available while the operator performs the next task with reference instructions.
Demonstrate one job. Help the operator do the next.Practice with support helps the user build judgment about using the system in real work.

Users need practice and judgment as well as access. Enablement can cover suitable tasks, effective inputs, interpreting results, and recognizing when to seek help. Use realistic examples and make support easy to reach. The aim is for people to use the system competently in their own work, including knowing its limits.

Workflow adoption

The sustained incorporation of a system into people's regular work.

An operator first handles work manually beside an idle station, then uses the station for the regular job.
The station is handling the morning's actual orders.The change in daily practice represents adoption. Activity still needs to be assessed against usefulness and outcomes.

Adoption appears in sustained use within the intended workflow. Look at repeat usage, coverage of eligible tasks, and where people abandon the process. Then connect those patterns to usefulness and outcomes. A mandatory tool can have high usage while adding effort, so activity alone gives an incomplete account of whether the change is working.

Feedback loops

Processes that use observed results or user input to inform changes and then assess their effects.

A customer reports a parcel snag, an engineer adjusts the chute, and they watch another parcel pass through the changed route.
The next parcel tests whether the chute adjustment helped.The loop closes when the effect of the change is observed, rather than when the feedback is collected.

Feedback becomes a loop when it informs a change and the effect of that change is assessed. In an AI application, the response might involve prompts, retrieval, tools, or workflow design. Assign responsibility for interpreting the evidence and checking the result. Simply collecting ratings leaves that work undone and does not automatically update the model.

Productization

Turning a solution into a repeatable offering that can serve a defined group of users consistently.

An engineer inspects a bespoke stool assembly, then builds from a repeatable kit with standard parts and supported adjustments.
The one-customer contraption becomes a kit other teams can use.The kit represents an offering designed for consistent reuse across a defined group of users.

Productization involves choosing what should be common across customers and what can vary. Supported options, onboarding, and ongoing support make the offering repeatable. Productionization addresses reliable operation; productization addresses serving a defined group consistently. A custom solution supplies useful evidence, but its assumptions may need substantial revision before reuse becomes practical.

Reusable components

Parts of a system designed to be used in multiple contexts through a defined interface.

Peanut attaches an orange label-holder clip to a bench; the same clip design already holds labels on a cart and shelf.
The same label holder fits a cart, a shelf, and a bench.The repeated clip represents one component used through a consistent attachment interface in several contexts.

A reusable component exposes a defined interface that several systems can rely on. It might be a connector, a validation function, or a user-interface element. Document its assumptions so callers know where it fits. Shared maintenance is useful, but changes deserve attention because their effects can reach every place that uses the component.

Configuration versus customization

Configuration selects supported settings; customization changes or extends a system's implementation.

Peanut moves a provided shelf peg in the configure scene and attaches a new bracket in the customize scene.
Move the provided peg, or make a new bracket.The provided adjustment is a supported setting. Fabricating a bracket changes the implementation and its maintenance needs.

Choosing a supported model option is configuration. Writing a new integration is customization.

Both can meet a requirement, with different implications for maintenance and upgrades. Check the product’s supported settings and extension points before estimating the work, because that boundary determines who owns the resulting behavior.

Product feedback

Evidence, observations, and requests from product use that inform product decisions.

An engineer brings three customers' latch problems to a product-team peanut, who examines the recurring difficulty at the workbench.
Three customers have encountered the same awkward latch.The shared difficulty supplies evidence for a product decision. The proposed fix still needs investigation and evaluation.

Product feedback helps a team decide which problems deserve attention. A request is one kind of evidence; observed difficulty and repeated patterns of use are others. Understand the underlying need and who is affected before choosing a solution. Several customers asking for the same outcome can be more informative than their agreement on a particular feature.

Worked example · Order 17 · final installment of 4

Make it work for the team

An engineer observes a replacement workflow, then discovers a customer's address update during a pilot. A revised procedure pauses pending dispatch, rechecks details, and requires approval before dispatch.
The address changed. The dispatch needs a fresh check.The changed details need a fresh check and approval of the actual action. The exception becomes evidence for evaluation and operating procedures.

During the pilot, the engineer discovers an exception the demonstration missed: an address can change while a dispatch is waiting for approval. The team adds a check that the action still matches the approved details. A material change requires approval of the revised action before dispatch.

That case joins the evaluation suite. The team compares operator effort and correction rates with the existing process, assigns ownership of unresolved dispatches, and establishes monitoring. Those findings guide the decision to expand the pilot and identify which parts are useful across other teams.

Concepts together: FDE, process discovery, pilot, acceptance criteria, baseline, monitoring, product feedback.

End of chapter 12

Peanut has done a fair bit of work.

Written and illustrated by Aishwarya Ashok. Illustrated handbook.