Maya Okafor, Support Lead at Kestrel Outfitters, wants help with late-delivery tickets: something that finds the order, checks the shipment and drafts a reply her team can review. Before anyone writes model code, there is a decision to make: should that help be a workflow, where our code fixes every step, or an agent, where a language model picks the next step itself?
By the end you will have a definition of an agent you can check against real code, a test that tells a workflow from an agent, and five Kestrel requests placed on the autonomy spectrum by cost, risk and predictability. You will also have the companion project running, with the mock API and the seeded data that the rest of the book, including the capstone, builds on.
There is no model call yet, so no API key. You need Python, JSON and HTTP APIs; the hands-on section uses git and uv.
1. Maya's late-delivery ticket
Kestrel Outfitters sells home and outdoor goods through an online store and a trade portal for hotels, campsites and schools. The company is fictional; its records run on your machine as one local, read-only mock API with tickets, orders, shipments, stock and policies.
Ticket T-000407 arrives in Maya's queue: "Where is my order?" It names order O-0006066, which hasn't arrived. Maya wants a drafted reply that says where the order stands, where the shipment is and what Kestrel will do next.
Someone on Maya's team would open the ticket, find its order and check the shipment's carrier, status and promised date. If the parcel looks lost, they might read the shipping policy or check stock for a reship, then decide: wait, reship or refund.
Some of those steps happen on every such ticket; others depend on what earlier steps returned. A ticket may not mention an order at all, or the order may not have shipped yet. So who decides the next step: code a developer wrote beforehand, or a model reading the results as they arrive?
2. Agent, tool, loop, stop: the four words this book is built on
This book uses one definition of an agent throughout:
An agent is a program in which a language model decides, step by step, which tools to call and when to stop, inside limits (steps, tokens, time, money) enforced by ordinary code.
Take away any clause and you get a different kind of program:
- No model deciding: code picks every step, so it is a workflow.
- No tools: the model can only answer from what it was given, so it is a single model call.
- Not step by step: the model chooses once, say a label, and code paths the developer wrote do the rest, so a surprising result can't change what happens next. That is a workflow with a model step.
- No limits in code: the run ends only when the model says so, and a confused model may never say so.
A tool is a function the program offers to the model, described by a name, a description and an input schema: the tool definition, which Chapter 6 teaches you to write. For Maya's ticket, a tool might be get_order. One detail matters from the start: in this book the model never runs anything. The model can only produce a tool call, a request naming a tool and its arguments. The program reads the call, decides whether to allow it, runs the function itself and sends back a tool result. Each tool call carries an id, and the tool result names that id, so the model can match every result to its call. Chapter 6 covers this cycle in depth.
The loop, which this book calls the agent loop, turns tool calls into work. The program sends the model the conversation so far plus the tool definitions. The model replies with either a final answer or a tool call. If it is a tool call, the program checks and runs the tool, adds the result and calls the model again. Chapter 7 develops the agent loop in five phases: perceive, reason, act, observe and stop.
Stop is where the definition earns its last clause. Either the model signals that it has finished and gives its final answer (Chapter 3 shows how a response says so), or the program ends the run because a limit was reached. Those limits are the run budget: a maximum number of steps, tokens, seconds and amount of money for one run. A step is one model call plus any tools it asked for; a token is the unit in which model input and output are counted and billed (Chapter 2). The loop checks the budget in code before each step, so no new step starts once a limit is reached (Chapter 7 shows what happens to the step that crosses one). Writing "please don't take more than five steps" in the instructions is not a budget; it is a request, and a model can ignore it.
So the program owns the loop: the model asks, and code decides whether the call is allowed, how it runs and when the loop stops, the split PromptLayer's guide to an Anthropic agent loop also describes.
flowchart LR
P["Program<br/>(owns the loop)"]
B{"Budget check"}
M["Model"]
T["Tools"]
S(["Stop"])
P --> B
B -->|"within budget:<br/>messages + tool definitions"| M
M -->|"tool call or final answer"| P
P -->|"runs the function"| T
T -->|"tool result"| P
P -->|"final answer → stop"| S
B -->|"budget exceeded → stop"| SFigure 1.1: The smallest agent loop. The model only asks; the program checks the budget, runs the tools and decides when the run ends.
3. Who picks the next step: workflows versus agents
A workflow is a program where code fixes the steps, even when some steps call a model. A pipeline of three model calls is still a workflow: the third call follows the second because a developer wrote it that way.
Anthropic's Building effective AI agents draws the line in the same place. Workflows are systems where models and tools are orchestrated through predefined code paths. Agents are systems where the model dynamically directs its own process and tool use, and keeps control over how it accomplishes the task.
That gives you one test for any design: at runtime, who selects the next step: code written in advance, or the model's tool call? A Hugging Face post on workflows and agents asks the same question: who controls orchestration at runtime. The test classifies a program; the autonomy spectrum, later in this chapter, places a design.
A workflow can still branch. It may branch on data, as the order-status code in this chapter branches on the shipment's status, or on a label a model produced. It is still a workflow because the developer wrote every possible path. In an agent, the model's tool call selects the next step from whatever tools the program offers.
Neither side is better in general. In Anthropic's view, workflows offer predictability and consistency for well-defined tasks, and agents are the better choice when flexibility and model-driven decision-making are needed at scale.
flowchart LR
subgraph WF["Workflow: code fixes the steps"]
direction TB
W0["Read ticket"] --> W1["Look up order"]
W1 --> W2["Look up shipment"]
W2 --> W3["Apply hard-coded rule"]
W3 --> W4["Draft reply (model step)"]
end
subgraph AG["Agent: the model picks the next step"]
direction TB
M["Model"] -->|"tool call"| P["Program: checks budget, runs tool"]
P -->|"runs"| T["Tools: ticket, order, shipment, shipping policy"]
T -->|"tool result"| P
P -->|"tool result"| M
M -->|"final answer"| S["Stop"]
endFigure 1.2: The same ticket handled two ways. On the left, the arrows are fixed in code. On the right, the model chooses each next tool and when the run is done, but the program still runs every tool.
4. Maya's ticket two ways
The workflow version reads the ticket, looks up its order and shipment, and applies one rule: delivered, lost, or in transit and late or on time against the promised date. Adding a model step that drafts the reply gives the left side of Figure 1.2. The companion code stops at the verdict, with no model call; it is Request 1 below.
The agent version offers the model four read-only tools, named here only for this sketch: get_ticket, get_order, get_shipment and get_policy (Chapters 7 and 8 define the real tool set). Under a run budget enforced in code, the model asks for whichever tool it needs next and stops when its final answer, the draft reply, is ready. Here is one sequence it might produce for Maya's ticket and for T-000007, a "Where is my order?" ticket that names no order. Both tickets are in the seeded data; the sequences are written by hand to show the shape, not output from a model:
Illustrative tool-call sequences (written by hand, not model output)
T-000407, today pinned to 2025-12-16
1. get_ticket("T-000407") -> order O-0006066
2. get_order("O-0006066") -> shipped, promised 2025-12-05
3. get_shipment("O-0006066") -> Swiftway Parcel, in_transit
4. get_policy("shipping-policy") -> "late when it is delivered after its promised date"
5. final answer: draft apology with tracking and a carrier trace
T-000007
1. get_ticket("T-000007") -> no order ID
2. final answer: draft reply asking the customer for the order numberOn T-000407 the agent makes the workflow's three lookups plus one it chose itself, the policy read. On T-000007 the paths split: the workflow stops with an error and hands the ticket to a person, while the agent drafts a reply nobody wrote a branch for. One extra branch would cover this ticket too; the agent pays off only when such tickets are many and varied. Another run may also choose differently, for example skipping the policy. One trap waits in the data: the mock API serves an outdated shipping policy next to the current one, so the policy tool must offer only the current version.
The workflow handles the common case cheaply and testably; the agent handles cases nobody wrote a branch for, at a cost and path that vary per run.
5. The autonomy spectrum is a design choice, not a ladder
The autonomy spectrum runs from code that fixes every step to agents that direct their own steps. Where a system sits is a design decision, made per request, and you can get it wrong in either direction. This book uses five points:
- A workflow with no model step: fixed code only.
- A single model call: code gathers the input, one call does the work, and the output goes straight to a person.
- A workflow with model steps: code runs a fixed sequence with its own logic (rules, branches, routing, one call per item), and the model fills one or more fixed steps in it.
- An agent with narrow tools and a tight budget: the model picks among a few read-only lookups into internal systems.
- An agent with a wider tool set: open-ended sources such as the public web, more systems, or tools that write.
The line between points 2 and 3 is whether code does anything with the model's output or around it. If code only fetches the input and shows the result, it is point 2. If code applies rules, routes cases or acts on what the model returned, it is point 3.
Between points 4 and 5 the difference is reach: where an agent's tools can go, meaning which systems, whether they only read or also write, and how open-ended the sources are. Reach is not the number of tools. A write tool, even an internal one, moves a design toward point 5, because a wrong call now changes something.
The five points are this book's own scale. They broadly follow the progression in Anthropic's article, from the augmented LLM (a single model call with extras such as retrieval and tools) through simple compositional workflows to agents.
Moving right is not progress. Anthropic says that for many applications, optimising single model calls with retrieval and examples in the prompt is usually enough, and plenty of useful software stops at point 2. In this book retrieval is only a kind of tool, taught in Book 2, and Chapter 4 covers examples in prompts.
Placing a request means weighing three criteria:
- Cost: model calls, tokens and engineering time per request. A workflow puts its cost into design and maintenance; an agent puts it into every run, and it varies from run to run.
- Risk: what a wrong step can damage (money, customer trust, data), and whether it can be undone. A misread status in a reviewed draft is a nuisance; a replacement sent twice is lost stock and money.
- Predictability: how much you need the same input to give the same path and output, and how easily you can test it.
Claude Academy's lesson on workflows and agents lists the same tension: workflows are less flexible and need more design up front; agents complete fewer tasks, are harder to test and evaluate, and behave less predictably.
flowchart LR
P1["1. Workflow,<br/>no model step"] --> P2["2. Single<br/>model call"] --> P3["3. Workflow with<br/>model steps"] --> P4["4. Agent: narrow tools,<br/>tight budget"] --> P5["5. Agent: wider<br/>tool set"]
L["Cheaper per request<br/>easier to test<br/>less flexible"] -. "tends to move this way" .-> R["Costlier per request<br/>harder to test<br/>more flexible"]Figure 1.3: The five points, and the direction in which cost, testing effort and flexibility tend to move along them.
Risk is kept off the figure on purpose: it depends on what the tools can change, so a read-only agent can carry less risk than a workflow that issues refunds.
6. Placing five Kestrel requests
Claude Academy recommends implementing workflows where you can and using agents only when they are truly required. So each placement below starts at the left and moves right only when the argument supports it.
Request 1: Maya asks, "What's the status of the order on this ticket?" Point 1, a workflow with no model step. The steps never change, and a wrong status misleads a customer, so the answer must be the same for the same input and testable with fixed data. It's the code you run in this chapter.
Request 2: Daniel Reyes asks, "Summarise the ticket this trade customer raised before my call." Point 2. Code fetches one ticket with its message thread, one model call turns it into a brief, and the brief goes straight to Daniel. Code does nothing with the output and there is no tool choice, so a loop would add only cost. Risk is low because Daniel reads the summary first.
Request 3: Priya Nair asks, "Check the open 'Refund not received' tickets against the returns policy and flag the ones where we may be in breach." Point 3. Code fetches the open tickets and the returns policy, keeps the refund tickets, sends each thread to the model and collects the flags into one list. The returns policy that GET /policies/returns-policy serves promises a refund within 5 working days of receiving a damaged or wrong item. The model handles the fuzzy part, reading the thread for whether the item was damaged or wrong and when Kestrel received it; code then counts the working days and decides the flag. Money is involved, so every flag goes to Priya and the program never issues or refuses a refund.
Request 4: Tomasz Wójcik asks, "'Where is my order?' tickets are piling up. Is it one carrier, one warehouse, or orders that never shipped?" This is the first request where an agent earns its place: point 4, an agent with narrow tools and a tight budget. The tools are ticket, order and shipment lookups and the late-shipments list by carrier: read-only reach into Kestrel's own systems. The path depends on what each lookup finds: if the shipments cluster on one carrier, the agent pulls that carrier's late shipments; if many orders never shipped, the question changes. A wrong step wastes a lookup and changes nothing; a wrong conclusion is still possible, so the answer lists the evidence each tool returned.
Request 5: Sam Adeyemi asks, "Which carriers had the most late deliveries last quarter, and what do public sources say about their service?" This is the capstone you build at the end of the book. It is an agent because the model judges which exported files and web searches to use and when the evidence is enough. It sits at point 5: web search reaches the open web, an open-ended source whose results no one can list in advance. Every tool only reads, which keeps the risk low but does not make it point 4. A hard run budget ends the run, and every citation must be a URL or file path a tool returned during that run. Chapter 14 designs it in full.
| Request | Placement | Cost | Risk | Predictability |
|---|---|---|---|---|
| 1. Order status (Maya) | Point 1: workflow, no model step | No model calls | A wrong status misleads a customer | Must be identical every time |
| 2. Ticket summary (Daniel) | Point 2: single model call | One call per summary | Low; Daniel reads it first | Wording varies, which is acceptable |
| 3. Refund checks (Priya) | Point 3: workflow with a model step | One call per ticket | Money; every flag goes to review | Fixed path, auditable |
| 4. Late tickets (Tomasz) | Point 4: agent, narrow tools | Several calls, capped | No changes to systems; evidence is listed | Path varies with findings |
| 5. Carrier research (Sam) | Point 5: agent, open-web reach (read-only) | The most calls; hard budget | Unsupported claims; citations required | Path varies; hardest to test |
If Tomasz's tickets almost always come down to the same three causes, a workflow that checks those three in order is cheaper, easier to test and defensible. Either placement can be right if the argument rests on the three criteria, not on which option sounds more advanced.
Back to Maya's late-delivery ticket. Request 1 is only its status lookup; the drafted reply adds a model step, so I would place the whole ticket at point 3 to start. It is point 3, not point 2, because code does more than gather input: it computes the verdict with a fixed rule, sends off-path tickets (no order, never shipped, a refund question) to a person with what it found so far, and only then asks one model call to draft the reply. A person on Maya's team reviews every draft, so nothing the model writes reaches a customer unchecked. Review is not a complete control, though: the ticket text is written by customers and goes into the model, and reviewers tire when most drafts are fine.
Two conditions would justify point 4, a narrow read-only agent: off-path tickets take more of the team's time than the common case, and a wrong action stays cheap because the agent only reads and drafts while reshipping and refunds stay with a person. If either fails, adding branches to the workflow is the better trade.
7. What goes wrong at either end
Too little autonomy fails slowly. Edge cases arrive one at a time, each becomes another branch, and the code turns into a hand-built decision tree that still misses cases nobody predicted.
Too much autonomy fails differently. PromptLayer's guide warns that a weak loop can run forever, call tools it should never have been allowed to call, hide broken state, or let the model make up data that should have come from a tool. The last matters most for the capstone: a model can produce a plausible URL as easily as a plausible sentence, so a citation counts only if a tool returned it.
So the limits live in code: the model finishes when it gives its final answer, with a step limit behind that check so a run that never finishes on its own still ends (Loop Engineering on stop conditions).
8. Hands-on: the companion project and the mock API
Before you start
You need git and uv (which manages Python, the virtual environment and the dependencies). The book's code targets Python 3.12 (the version in its .python-version file). Install uv with the uv installation guide and git from your system's package manager, then check both:
uv --version
git --versionGet the project
In the repo, agentic-ai-foundations/ is one uv project: its uv.lock pins the libraries every chapter uses (httpx, pydantic, the anthropic Python SDK and the shared kestrel package that provides the mock API). Each chapter has its own folder with a package named after it, so this chapter's code is ch01-what-agentic-means/ch01/. Nothing in this chapter imports the SDK.
git clone https://github.com/bishal-saha/books-code.git
cd books-code/agentic-ai-foundations
uv sync
cd ch01-what-agentic-meansuv sync creates the virtual environment and installs the versions recorded in uv.lock; that is the whole project setup.
Start the mock API
From the chapter folder, run:
uv run kestrel upThis writes a .kestrel/ folder (kestrel.sqlite, CSV exports under exports/ and policy documents under docs/), then serves one read-only API at http://127.0.0.1:8700. Its endpoints are GET /health, /orders/{id}, /orders/{id}/shipment, /shipments?carrier=&late=&limit=, /stock/{sku}, /tickets/{id}, /tickets?status=&limit=, /policies and /policies/{name}; an unknown ID returns 404. A fixed seed gives every reader the same records. The seeded data is historical, so the examples pass a fixed date instead of today's.
Leave it running and use a second terminal, in the same folder:
curl http://127.0.0.1:8700/healthIt prints {"status": "ok"}.
The workflow
Here is Request 1 as code, with no model call. Pydantic models parse the API's JSON into typed objects and declare only the fields the workflow reads (plus channel, for Exercise 3); Chapter 5 covers validation properly. The listing is the complete file; the package's __init__.py is empty.
"""Deterministic order-status workflow for a support ticket. No model call."""
import sys
from datetime import date, datetime
from enum import StrEnum
from typing import Literal
import httpx
from pydantic import BaseModel
BASE_URL = "http://127.0.0.1:8700" # the single mock API server
USAGE = "usage: python -m ch01.order_status TICKET_ID YYYY-MM-DD"
class WorkflowError(Exception):
"""A known state the workflow refuses to guess about."""
class TicketNotFound(WorkflowError):
"""The API has no ticket with this ID."""
class NoOrderOnTicket(WorkflowError):
"""The ticket is not about an order (a general enquiry)."""
class OrderNotFound(WorkflowError):
"""The API has no order with this ID."""
class NotShipped(WorkflowError):
"""The order exists but has no shipment yet (placed, or cancelled)."""
class UpstreamUnavailable(WorkflowError):
"""The API could not be reached, timed out or answered with an error."""
class Ticket(BaseModel):
ticket_id: str
order_id: str | None
class Order(BaseModel):
order_id: str
channel: Literal["store", "trade"] # exercise 3 uses it
class Shipment(BaseModel):
carrier: str
status: Literal["in_transit", "delivered", "lost"]
promised_by: datetime
class Verdict(StrEnum):
DELIVERED = "delivered"
LOST = "lost"
LATE = "late"
ON_TIME = "on_time"
class OrderStatus(BaseModel):
ticket_id: str
order_id: str
carrier: str
shipment_status: str
promised_by: date
verdict: Verdict
next_step: str
def get_order_status(client: httpx.Client, ticket_id: str, today: date) -> OrderStatus:
ticket = Ticket.model_validate(_get(client, f"/tickets/{ticket_id}", TicketNotFound))
if ticket.order_id is None:
raise NoOrderOnTicket(ticket_id)
order = Order.model_validate(_get(client, f"/orders/{ticket.order_id}", OrderNotFound))
shipment = Shipment.model_validate(
_get(client, f"/orders/{order.order_id}/shipment", NotShipped)
)
promised = shipment.promised_by.date()
if shipment.status == "delivered":
verdict, next_step = Verdict.DELIVERED, "Confirm the delivery date with the customer."
elif shipment.status == "lost":
verdict, next_step = Verdict.LOST, "Open a carrier trace; a person decides on a reship."
elif today > promised:
verdict, next_step = Verdict.LATE, "Apologise, share tracking and open a carrier trace."
else:
verdict, next_step = Verdict.ON_TIME, "Share tracking and the promised date."
return OrderStatus(
ticket_id=ticket_id,
order_id=order.order_id,
carrier=shipment.carrier,
shipment_status=shipment.status,
promised_by=promised,
verdict=verdict,
next_step=next_step,
)
def _get(client: httpx.Client, path: str, not_found: type[WorkflowError]) -> dict:
"""Return the JSON body; raise not_found on 404, UpstreamUnavailable on other failures."""
try:
response = client.get(path)
except httpx.TransportError as exc: # timeouts, refused connections, ...
raise UpstreamUnavailable(f"mock API unreachable for {path}") from exc
if response.status_code == 404:
raise not_found(response.json().get("error", path))
if response.is_error:
raise UpstreamUnavailable(f"{path} returned HTTP {response.status_code}")
return response.json()
def main(argv: list[str]) -> int:
if len(argv) != 3:
print(USAGE, file=sys.stderr)
return 2
try:
today = date.fromisoformat(argv[2])
except ValueError:
print(USAGE, file=sys.stderr)
return 2
with httpx.Client(base_url=BASE_URL, timeout=5.0) as client:
try:
status = get_order_status(client, argv[1], today)
except WorkflowError as exc:
print(f"error: {exc!r}", file=sys.stderr)
return 1
print(status.model_dump_json(indent=2))
return 0
if __name__ == "__main__":
raise SystemExit(main(sys.argv))today is a parameter rather than date.today(), so a test or the command line pins it. The shipment's own late flag goes unused for the same reason: the caller controls the date.
The code fixes the whole path. The same ticket and date always give the same OrderStatus, a run costs three local HTTP requests, and each branch takes one test to cover. Known failure states are explicit exceptions; _get turns transport errors and HTTP error statuses into UpstreamUnavailable, and the client's timeout=5.0 stops a hung server from hanging the workflow (Chapter 3 returns to timeouts). A ValidationError is left as a traceback on purpose: it means the code and the API disagree, which is not a ticket state.
The lost branch shows how workflows grow. Without it, a parcel marked lost before its promised date would come back on_time. Someone had to know the third status existed and write a branch for it. Plenty of cases still have no branch, such as returned orders or trade customers who need a different reply. Each means another branch, lookup and test. None is hard; the trouble is that you write them one ticket at a time, after a ticket has gone wrong.
Run it on Maya's ticket
uv run python -m ch01.order_status T-000407 2025-12-16The date pins "today" to a day inside the seeded data. The output:
{
"ticket_id": "T-000407",
"order_id": "O-0006066",
"carrier": "Swiftway Parcel",
"shipment_status": "in_transit",
"promised_by": "2025-12-05",
"verdict": "late",
"next_step": "Apologise, share tracking and open a carrier trace."
}With 2025-12-03 the verdict is on_time. Keep the same date and the result never changes. Now the refusals:
$ uv run python -m ch01.order_status NO-SUCH-TICKET 2025-12-16
error: TicketNotFound('no ticket NO-SUCH-TICKET')
$ uv run python -m ch01.order_status T-000007 2025-12-16
error: NoOrderOnTicket('T-000007')
$ uv run python -m ch01.order_status T-000009 2025-12-16
error: NotShipped('order O-0012769 has not shipped')Each prints to standard error and exits with status 1.
Run the tests
uv run pytestIt should end with 19 passed, whether pytest used your running server or started its own. The smoke test below checks /health and one seeded record from each endpoint the chapter relies on, including the returns policy Request 3 quotes:
import httpx
import pytest
SEEDED_PATHS = [
"/tickets/T-000407",
"/orders/O-0006066",
"/orders/O-0006066/shipment",
"/stock/SKU-00061",
"/policies/shipping-policy",
"/policies/returns-policy",
]
def test_health(kestrel_url: str) -> None:
response = httpx.get(f"{kestrel_url}/health", timeout=5.0)
response.raise_for_status()
assert response.json() == {"status": "ok"}
@pytest.mark.parametrize("path", SEEDED_PATHS)
def test_seeded_record(kestrel_url: str, path: str) -> None:
response = httpx.get(f"{kestrel_url}{path}", timeout=5.0)
assert response.status_code == 200, f"{path} returned HTTP {response.status_code}"
assert response.json()The kestrel_url fixture in the chapter's conftest.py uses your server at port 8700 if it answers, and otherwise starts the same seeded API inside the test process. tests/test_order_status.py covers each workflow branch with httpx's MockTransport, a fake HTTP layer that answers from a dictionary, plus one end-to-end run of T-000407. This excerpt (imports and the error-case tests omitted) shows the pattern:
TICKET = {"ticket_id": "T-1", "order_id": "O-1"}
ORDER = {"order_id": "O-1", "channel": "store"}
def shipment(status: str) -> dict:
return {"carrier": "Swiftway Parcel", "status": status, "promised_by": "2025-12-05T10:00:00"}
def fake_client(routes: dict[str, dict | None]) -> httpx.Client:
"""A client whose API answers from `routes`; None or a missing path is a 404."""
def handler(request: httpx.Request) -> httpx.Response:
body = routes.get(request.url.path)
if body is None:
return httpx.Response(404, json={"error": f"no {request.url.path}"})
return httpx.Response(200, json=body)
return httpx.Client(base_url="http://kestrel.test", transport=httpx.MockTransport(handler))
def routes_with(status: str) -> dict[str, dict | None]:
return {"/tickets/T-1": TICKET, "/orders/O-1": ORDER, "/orders/O-1/shipment": shipment(status)}
@pytest.mark.parametrize(
("status", "today", "verdict"),
[
("delivered", date(2025, 12, 16), Verdict.DELIVERED),
("lost", date(2025, 12, 1), Verdict.LOST), # lost before the promised date
("in_transit", date(2025, 12, 16), Verdict.LATE),
("in_transit", date(2025, 12, 5), Verdict.ON_TIME), # the promised day itself
],
)
def test_verdicts(status: str, today: date, verdict: Verdict) -> None:
result = get_order_status(fake_client(routes_with(status)), "T-1", today)
assert result.verdict is verdict
assert result.promised_by == date(2025, 12, 5)When it doesn't work
Every later chapter folder runs its own kestrel up with the same seed, so the records you met here stay the same through the capstone in Chapter 16.
9. Exercises
1. Classify three programs. For each, say workflow or agent, and name the one fact that decides it.
- (a) A fixed ticket pipeline: look up the order, look up the shipment, then a model drafts the reply.
- (b) A model labels each new ticket "late delivery", "refund" or "other", and code sends each label to a fixed queue.
- (c) A program where the model picks among order, shipment and policy lookups until it gives a final answer, inside a run budget enforced by code.
Expected: (a) is a workflow: code fixes the steps and the model only drafts text. (b) is a workflow at point 3: the model fills in a label, and the branches the developer wrote decide where it goes. (c) is an agent: the model chooses the next tool and when it has finished; without the budget it would fail the definition's last clause.
2. Place a new request. Grace Lin, the People Partner, wants help answering staff questions about the shipping, returns and expense policies that GET /policies serves. Place this request on the autonomy spectrum and justify the placement by cost, risk and predictability. Hint: one policy name, shipping-policy-v2-OUTDATED, marks a superseded version. Also ask who acts on the answer. One defensible answer: point 2. Code fetches the current policies (dropping the one whose name marks it outdated), one model call answers and quotes the policy it used, and the answer goes to the member of staff who asked. If code first routed each question to one policy, or checked the quote against the policy text, the design would move to point 3.
3. Extend the workflow. Add a branch to get_order_status that gives trade-portal orders (order.channel == "trade") a different next-step message. Ticket T-000022 refers to a trade order. Write a test with a pinned date that asserts the new message (copy the fake-transport tests) and confirm the others still pass. Reflect: how many branches like this would you add before you considered an agent?
4. Design a budget on paper. Write the run budget you would set for Tomasz's late-tickets investigation, covering steps, tokens, wall time and money. Decide what the program returns at a limit: which limit stopped the run and what the tools found, without guessing a conclusion. Chapter 2 shows how to estimate tokens; for now, a rough guess is fine. Check: every limit has a number and a one-line reason, the step limit leaves room for the lookups a normal investigation needs, and the result at a limit names that limit and lists the evidence so far. Chapter 7 adds the first three limits, and Chapters 14 and 16 add money.
10. Summary and what comes next
A workflow fixes its steps in code, even when it branches or calls a model. An agent lets the model choose which tool to call next and when to stop, inside a run budget that ordinary code enforces. Where a request sits on the spectrum is a design decision made per request by cost, risk and predictability; the five Kestrel requests span all five points.
From here on the book uses these terms as defined: agent, tool, tool call, tool result, agent loop, stop, run budget, workflow and autonomy spectrum. Chapters 6 and 7 go deeper.
Chapter 2 looks at the model inside the loop: tokens, context windows, sampling and reasoning models, the mechanics behind cost and predictability. Chapter 3 then puts model calls behind a small client of your own.
