IamBishal

Chapter 12 · Part III: Context, models and testing

Agent frameworks landscape: when to use one, when to write the loop yourself

Maps each part of your hand-written agent loop to what five current agent frameworks document for it, with the open questions listed and the facts dated. Names what frameworks add and cost, applies a build-or-adopt checklist to three Kestrel requests, and records why the capstone stays framework-free.

35 min read · from Agentic AI Foundations

You already have a working agent. Chapter 7 gave you run_agent, a bounded agent loop with a run budget, a step log and a StopCause for every way a run can end. Chapter 8 redesigned its tools and moved them into registry.py. Chapter 9 gave tool results a single rendering path, Chapter 10 built ConversationState with trimming and compaction for long conversations, and Chapter 11 added a second model client adapter and strict tool arguments. You can explain every line of it.

That leaves a narrow question: what would an agent framework do for you that this code doesn't already do? I'll use one test throughout. Judge a framework by what it does for you compared with the loop you already wrote, not by its feature list or its popularity.

By the end you will have mapped each part of your loop (model client, tool registry, state, budget and step log) to what five current options document for it. You'll know what frameworks add and what they cost, you'll have run a build-or-adopt checklist on three Kestrel requests, and you'll have the record that keeps this book's capstone framework-free.

This chapter compares frameworks without teaching any, and the companion repo installs none. Every cited behaviour links to its official page or repository and was checked in November 2026. Anything I mark as my reading has not been verified. These APIs change quickly, so check again before you rely on one.

The code is in ch12-agent-frameworks/: an annotated copy of your loop, a demo of the edge cases the checklist asks about, an @beta_tool demo, the checklist, four decision records and a checker for them. Every model reply in it comes from the fake model, so no API key is needed.

1. What an agent framework is, and the three shapes it comes in

An agent framework is a library that provides an agent loop, tool abstractions, state handling and related plumbing, so you write less of it yourself but work inside its abstractions. Both halves matter. You maintain less code. You also take on someone else's idea of how a loop is structured, how a tool is declared, where state lives and what happens when something fails.

Adopting a framework doesn't turn a program into an agent. Chapter 1 drew the line: in a workflow, code fixes the sequence of steps; in an agent, the model picks the next step inside limits your code enforces. You can build a workflow with a framework, and you built an agent without one. So the first question is always where the task sits on the autonomy spectrum, and the checklist starts there.

The options compared here come in three shapes. The shapes help you sort what you find. They aren't a ranking.

  1. Loop helpers inside a provider SDK. The provider's client library gains a helper that runs the call-tool-result cycle for you. The example is the tool runner in the Anthropic Python SDK, which you already have installed.
  2. Runtimes. A runtime bundles the model client, built-in tools and context handling with the loop. The example is Anthropic's Claude Agent SDK, a library that runs the Claude Code binary with its tools, permissions, sessions and hooks.
  3. Standalone agent libraries. A separate package you add next to your own code, with its own loop, tool and state abstractions. The examples are the OpenAI Agents SDK, Pydantic AI and, for graphs, LangGraph. For each, this chapter cites only the behaviours listed in the table below, not the product as a whole.

This isn't a market survey; leaving a library out says nothing about its quality.

The further right a shape sits, the more of your loop it owns, and the more you have to trust its defaults.

2. Your loop, part by part, against current frameworks

run_agent has five parts. The model client sends messages and tool definitions and returns content, stop reason and usage, and since Chapter 9 it can count a request's tokens. The tool registry holds definitions and dispatches calls. Conversation state is the message history: a plain list in the loop, ConversationState in Chapter 10's assistant. The run budget checks steps, tokens and wall time before each model call; money, its fourth limit, is designed in Chapter 14 and enforced in Chapter 16 with its own stop cause. The step log records each model call and its tool calls. For each part, a framework either provides it or leaves it to you.

flowchart LR
  subgraph ours["Your agent loop"]
    RB["Run budget check"] --> MC["Model client call"]
    MC --> TR["Tool registry dispatch"]
    TR --> CS["Conversation state update"]
    CS --> SL["Step log entry"]
    SL --> RB
  end
  MC -.-> F1["SDK client, or a bundled runtime"]
  TR -.-> F2["Decorated tools, built-in tools"]
  CS -.-> F3["Sessions, checkpoints"]
  RB -.-> F4["Per-run usage limits"]
  SL -.-> F5["Hooks or tracing"]

One step of the loop and the kind of framework feature that can replace each part.

The table maps your loop onto each option. The middle column holds only what the linked source documents. The right column lists the parts those sources didn't settle; that's a gap in the evidence, not a missing feature, and the checklist turns each gap into a question to answer before you adopt.

OptionWhat the cited docs settleNot settled by those docs
Our loop (Chapters 3–11)Model client with two adapters; registry with schemas from pydantic, strict arguments and failures as error results; message history; budget checked before each call; one step record per model call and its tool calls; StopCause, where only finished is an answerNothing survives a process restart
Anthropic SDK tool runnerModel client: the SDK's own. Tools: @beta_tool builds the schema from arguments and docstring. Stop handling: iterates on the stop reason and yields the final message when the model stops asking for toolsBudget, step log, state
Claude Agent SDKModel client: the bundled Claude Code CLI. Tools: built-in tools and permissions. State: context management and sessions. Step log: hooks at points of the loopBudget, stop handling
OpenAI Agents SDKTools: an unknown tool raises ModelBehaviorError by default. Step log: tracing, on by default. Stop handling: guardrail tripwires raise and halt the runModel client, state, budget
Pydantic AIBudget: UsageLimits caps tokens, requests and cost for one run(), with a default request_limit of 50. Stop handling: reaching it raises, even when the model has its answerModel client, tools, state, step log
LangGraphState: a checkpointer saves graph state at each super-step, per thread_id, and supports human-in-the-loop resumeModel client, tools, budget, step log

Read the table against your own code. For budget, tool errors and stop handling, the documented behaviour mostly covers ground your loop already covers, with different defaults; UsageLimits also caps cost, which your loop adds only in Chapter 16. Sessions, hooks and checkpoints are the entries that point to capabilities you lack. The defaults are where the options really differ: what happens at a limit, and whether a bad tool call becomes an exception or a tool result. They decide how a run ends in production.

The loop itself. The tool runner is an iterator driven by the stop reason. When the model asks for tools it runs them; for a few provider-specific stop reasons it resends the request; for any other it yields the final message and stops. Your loop agrees on the first and the last, but a truncated reply or an unknown stop reason ends your run with its own StopCause (truncated, unexpected_stop) and a partial result. The runner documentation describes no step, token or time budget, so check its parameters before you assume either way.

Library or runtime. A loop helper runs inside your process, and you still own the messages, the budget and the stop rules around it. The Agent SDK takes more: its Python package bundles the CLI, which runs its own tools, agent loop and context management, and your code configures it and receives its output.

Tool errors. By default, the OpenAI Agents SDK raises an exception when the model calls a tool that doesn't exist. Since Chapter 6 your dispatcher has returned invalid arguments, a ToolError, HTTP failures and an unknown tool name as tool results with is_error=True, and since Chapter 11 an invented argument too. An exception unwinds the run to the caller, and the model gets no chance to recover. An error result lets the model try something else on the next step.

The budget. Pydantic AI's UsageLimits applies to one run(). It doesn't cover periods longer than one run, per-tenant allowances or counters shared across workers. A run with no usage_limits still gets the default request limit, and reaching it raises instead of returning output. When your loop reaches a limit, it returns a partial result labelled with the StopCause, plus the step log, and the caller decides what happens next. Be precise about what "before each call" means in your own loop: it checks the tokens left and caps the call's output at that amount, but the call's input tokens are counted only when it returns, so the last call can overshoot. Chapter 9's inspector can count a request first, but it only warns. A test in the repo pins this: a 1,000-token budget ends at 1,200 tokens after two calls, and no third call is sent. Ask any framework the same question.

3. Hands-on: your loop, annotated with framework equivalents

ch12-agent-frameworks/ch12/annotated_agent.py is run_agent as the book stands after Chapter 11: Chapter 7's loop with Chapter 9's optional inspector, over Chapter 11's registry (Chapter 9's rendering, strict arguments). Comments starting with # framework: were added, nothing else. The loop keeps a plain message list; Chapter 10's ConversationState belongs to its long-conversation assistant. Either is what a framework's sessions or checkpoints would replace. The step log's annotation is on StepRecord, above this excerpt.

ch12-agent-frameworks/ch12/annotated_agent.py (excerpt; full file in the repo)
    # framework: state. A plain list in this process; nothing survives a restart.
    messages = [Message(role="user", content=user_message)]
    # framework: tool registry. @beta_tool would build these schemas from docstrings.
    tools = registry.definitions()  # read once: the tool set does not change mid-run
    tracker = BudgetTracker(budget, clock=clock)
    steps: list[StepRecord] = []
    final_text = ""

    for index in range(budget.max_steps):  # the step limit is the loop itself
        # framework: budget. Pydantic AI raises at request_limit; we stop with a StopCause.
        # Tokens are checked before the call, but its input is counted only after it returns.
        cause = tracker.check(MIN_CALL_TOKENS, MIN_CALL_SECONDS)
        if cause is not None:
            break
        started, context = clock(), None
        # framework: context. The inspector counts the request first (count_tokens); it warns,
        # it never stops a run, so it does not close the budget gap above.
        if inspector is not None:  # the request about to go out; its time counts too
            timeout = min(limits.timeout_seconds, tracker.remaining_seconds())
            context = measure(inspector, system, tools, messages, timeout)
            cause = tracker.check(MIN_CALL_TOKENS, MIN_CALL_SECONDS)  # measuring took time
            if cause is not None:
                break
        call_limits = CallLimits(  # shrink this call to what the run has left
            max_output_tokens=min(limits.max_output_tokens, tracker.remaining_tokens()),
            timeout_seconds=min(limits.timeout_seconds, tracker.remaining_seconds()),
        )
        sent = len(messages)
        try:
            # framework: model client. The tool runner wraps this call and the dispatch below.
            response = client.complete(
                system,
                list(messages),  # a copy: later appends must not change this request
                call_limits.max_output_tokens,
                tools,
                timeout=call_limits.timeout_seconds,
            )
        except ModelError:
            cause = StopCause.MODEL_ERROR
            break
        tracker.record(response.usage.input_tokens, response.usage.output_tokens)
        messages.append(assistant_message(response))

        results: list[ToolResult] = []
        if response.stop_reason == "tool_call" and response.tool_calls:
            # framework: tool errors. OpenAI Agents SDK raises for an unknown tool by default;
            # dispatch() returns it as an error result, like an invented argument (Chapter 11).
            results = [registry.dispatch(call) for call in response.tool_calls]
            messages.append(tool_results_message(results))  # all results, one message
        steps.append(
            step_record(index, sent, call_limits, response, results, clock() - started, context)
        )

        # framework: stop handling. Any step without tool calls ends the run with a StopCause.
        if not results:  # nothing to send back: this step ends the run
            final_text = response.text
            cause = stop_cause(response, call_limits, limits)
            break
    else:
        cause = StopCause.STEP_LIMIT

Tool definitions follow the same pattern. With a decorator, the description moves into a docstring. The text doesn't change, and you still have to write it. @beta_tool ships in the anthropic 2.8 SDK the book already pins, so this comparison runs without installing anything.

ch12-agent-frameworks/ch12/tools.py (excerpt; copied from Chapter 11)
        Tool(
            name="get_delivery_status",
            description=DELIVERY_STATUS_DESCRIPTION,
            args_model=GetDeliveryStatusArgs,
            function=partial(get_delivery_status, http),
            hints={"order_or_ticket_id": "Use O- and 7 digits or T- and 6 digits."},
        ),

Run the demo to see the schema the decorator builds and what a bad argument does:

bash
cd ch12-agent-frameworks && uv run python -m ch12.beta_tool_demo
text
schema from @beta_tool:
{
  "order_or_ticket_id": {
    "description": "The id the user gave: an order id (O-0013833) or a ticket id.",
    "pattern": "^(O-\\d{7}|T-\\d{6})$",
    "title": "Order Or Ticket Id",
    "type": "string"
  }
}
pattern kept: True
call with a bad id raises ValueError: Invalid arguments for function get_delivery_status

Two things are worth noticing. The id pattern from Chapter 8 survives into the schema, but only because the parameter carries it in an Annotated type; a plain str would lose it. And calling the tool with a bad id raises ValueError, where your registry returns an error result naming the field and a hint. I didn't check what the tool runner does with that exception during a run, so treat it as a checklist question.

Now the edges themselves. ch12/edges.py runs your loop twice against the mock API, with Chapter 11's read-only tools and scripted fake-model replies: once with a model that invents an argument and then asks for a tool that doesn't exist, and once with a model that never ends its turn.

bash
uv run kestrel up            # in one terminal
uv run python -m ch12.edges  # in another, from ch12-agent-frameworks/

The model replies below are fake-model output; the tool calls are real.

text
== an invented argument, then an unknown tool (fake model)
step 1  tool_call 1x get_delivery_status     in=900    out=40    400 ms
step 2  tool_call 1x get_delivery_status (1 ERR) in=900    out=40    400 ms
step 3  tool_call 1x track_parcel (1 ERR)    in=900    out=40    400 ms
step 4  finished  -                          in=187    out=21    400 ms
stopped: finished  steps 4/4  tokens 3028/20000  time 3.4/60 s
tool result 2: is_error=True Invalid arguments for get_delivery_status. verbose: Extra inputs are not permitted; got True.
tool result 3: is_error=True Unknown tool: track_parcel. Available tools: get_delivery_status, list_shipments, get_ticket, get_policy, get_stock.

== a model that never ends its turn (fake model)
step 1  tool_call 1x get_delivery_status     in=900    out=40    400 ms
step 2  tool_call 1x get_delivery_status     in=900    out=40    400 ms
step 3  tool_call 1x get_delivery_status     in=900    out=40    400 ms
step 4  tool_call 1x get_delivery_status     in=900    out=40    400 ms
stopped: step_limit  steps 4/4  tokens 3760/20000  time 3.4/60 s
answer: ''  (partial result, labelled step_limit)

The times come from the demo's fixed clock, which moves 0.2 s each time the loop reads it (several reads per step), so 3.4 s is a property of that clock, not a measurement. The invented argument and the unknown tool both came back as error results and the run finished; the model that never stopped got a partial result labelled step_limit. These are the defaults the checklist asks about, and uv run pytest (13 tests) pins them along with the token, model-error and tool-failure exits.

4. What frameworks add: persistence, hooks and graph orchestration

Persistence. Your ConversationState lives only in the running process, so a crash halfway through a run loses it. The Claude Agent SDK lists sessions; what a session stores, and where, should come from its documentation before you count on it surviving a restart. LangGraph's documentation is explicit about the trap: its in-memory savers keep checkpoints in RAM and lose them all when the process restarts, so production needs a persistent checkpointer.

Hooks. In the Agent SDK, a hook is a Python function that the Claude Code application, not the model, calls at specific points of the agent loop (claude-agent-sdk-python). This book has relied on the same split since Chapter 7: code enforces limits, and the model is never asked to respect them. As I read it, a hook point is where you would record a step, check a tool's input or refuse a call. Your loop has the same points, as lines inside one function rather than named extension points.

Tracing. In OpenAI's Agents SDK, tracing is on by default, and you can turn it off with an environment variable, in code or for a single run. Before real ticket text goes through it, find out where trace data goes and who can read it. Chapter 13 (pending) builds your own trace.

Graph orchestration. A graph describes a run as nodes and edges. In LangGraph, a checkpointer saves the graph's state at each super-step, keyed by a thread ID. The docs say checkpointers are needed for human-in-the-loop work, because a person must be able to see the state and the graph must resume after they change it. Here is Maya's return request drawn that way, as our own design:

flowchart LR
  A["Agent step: model picks lookups"] --> C{"Model proposes a return?"}
  C -->|no| F["Reply to customer"]
  C -->|yes| D["Human approval"]
  D -->|approved| E["create_return_authorisation"]
  D -->|rejected| F
  E --> F

Fixed edges move a design toward the workflow end of the spectrum. Inside the first node the model still picks its lookups and decides whether a return is warranted, so Maya's design stays an agent with a wider tool set. What the graph fixes is the path to the write: the only edge into create_return_authorisation comes from the approval node. When a step writes data, that edge is usually the reason to draw a graph at all.

Each of these is work you would otherwise build and maintain: storage and a serialisation format for ConversationState that keeps tool calls paired with their results; a stable event model for hooks; a saved state at each step so a paused run can resume after a restart. If you need one of these now, a framework can pay for itself.

5. What frameworks cost: abstraction, lock-in and upgrade churn

Anthropic's guidance on building agents credits frameworks with simplifying low-level work such as calling models, defining and parsing tools, and chaining calls. It also warns that they often add abstraction layers that hide the prompts and responses underneath and make debugging harder (Building effective AI agents). Anthropic also ships the tool runner and the Agent SDK, and I read the warning as applying to them too. Your loop has no such layer. When a run goes wrong, you print the messages and read exactly what the model saw.

The same guidance recommends starting with model APIs directly and understanding the underlying code of any framework you adopt, and it names wrong assumptions about that code as a common source of customer error. The table shows which assumptions matter. If you assume a run is unbounded when it has a default request limit, or that it returns output when it raises at the limit, you find out in production rather than in a test.

Exceptions used as control flow are part of the same cost. In OpenAI's SDK, a guardrail tripwire raises an exception immediately and halts the run. Guardrails themselves belong to Books 6–8 (security hardening and governance); they come up here only because they show the style. Your loop counts only StopCause.finished as an answer, and every other cause returns a labelled partial result. Both designs are defensible, but callers differ: one needs try/except around every run, the other checks the stop cause. Pick a framework without noticing which style it uses, and your callers end up written for the wrong one.

Lock-in is the third cost. On my reading of the Agent SDK overview, the loop, the tools and the context handling all live inside one runtime, so leaving means rewriting all three, not swapping an adapter. That is fine when you choose it knowingly, for example when one provider is a settled decision and the runtime gives you something you would otherwise build.

Upgrade churn shows in names and version numbers:

  • The Claude Code SDK was renamed the Claude Agent SDK (npm package).
  • The Anthropic Python SDK's tool helpers appeared in beta in version 0.68.0 (discussion #1036), and the SDK has a v1 migration guide for users upgrading from 0.x (repository). The helper is still named beta_tool in the 2.8 release you just ran.
  • Pydantic AI Harness, the documentation section whose spend page covers UsageLimits, is on 0.x releases, and its API may change between minor releases (Spend).

Beta labels and 0.x versions mean code you will revisit, and that cost belongs in your estimate.

Your own loop has costs too: you maintain it, you build persistence, hooks and checkpoints yourself if you need them, and nobody else tracks provider API changes for you.

6. A build-or-adopt checklist

The build-or-adopt decision is the choice, for one specific system, between keeping a hand-written agent loop and adopting an agent framework. You make it per system, so one team can reach different answers for two agents in the same quarter. Three things drive it: the capabilities the system needs now, how much of the framework you can see and test, and the costs above. Fashion and star counts aren't on the list.

One question comes first: does this task need an agent at all? Chapter 1's autonomy spectrum has five points: a workflow with no model step, a single model call, a workflow with model steps, an agent with narrow tools and a tight budget, and an agent with a wider tool set. At the first three there is no agent loop to replace. Anthropic's guidance makes a related point: for many applications, a single well-built model call with retrieval (Book 2 covers retrieval) and in-context examples is usually enough. A workflow can still need durable state and approval steps, so it goes on to question 1 too; a graph library there is a workflow tool, not a loop replacement.

The repo keeps the checklist as a file, so every decision record answers the same questions:

ch12-agent-frameworks/checklist.md
# Build-or-adopt checklist

## 0. Placement (autonomy spectrum)
- Single model call, or a workflow with no durable needs: stop. No framework.
- Workflow that needs approval steps, pause/resume or persistence: go to 1.
  A graph library here is a workflow tool; there is no agent loop to replace.
- Agent: go to 1.

## 1. Need (now, not someday)
- Persistence: must run state survive a process restart?
- Hooks: must our code run at fixed points of the loop?
- Graph orchestration: fixed steps, approvals, pause/resume?

## 2. Visibility (hard gate)
- Can we see every prompt and response sent to the model?
- Can we run the unit tests with a fake model and no API key?

## 3. Limits (hard gate)
- Is the run budget checked before each model call?
- At the limit: exception, or a partial result with a stop cause and the step log?

## 4. Errors (hard gate)
- Unknown tool: tool result or exception?
- Tool failure: tool result or exception?

## 5. Reach (hard gate)
- Which built-in tools does it bring, and can we turn each one off?

## 6. Portability (weighed)
- Does it work with every provider our adapters support?

## 7. Churn (weighed)
- Beta, dated beta names or 0.x versions on the parts we would use?
- How many of our modules would import its types (exit cost)?

Pass rule for gates 3 and 4: our callers check StopCause, so a default that
raises passes only if a documented setting returns a tool result or a partial
result instead, and a fake-model test proves it. Raising is a valid design in
general; these gates test fit to our callers.

Gates not yet answered by the docs: spike first (fake-model tests against the
candidate), then adopt or build.
Partial adoption counts: a framework can own one capability (an approval pause,
checkpoints) while our loop stays the agent step.

The scoring rule is a recommendation, not an algorithm. Adopt when three things hold: the framework covers a question 1 need you have now and would otherwise build; it passes the four hard gates, by default or through a setting you found and tested; and its portability and churn are acceptable for this system. If a candidate covers the need but the docs leave its gates unanswered, spike first: test the gates with fake-model tests, then adopt or build. Otherwise build, and write down what would change the answer. A framework that only replaces code you already have, with tests, adds exit cost and no capability.

flowchart TD
  A{"Q0: where on the<br/>autonomy spectrum?"} -- "agent" --> B{"Q1: need persistence, hooks<br/>or graph orchestration now?"}
  A -- "workflow needing approval,<br/>pause/resume or persistence" --> B
  A -- "single call, or workflow<br/>with no durable needs" --> W["No framework"]
  B -- no --> BUILD["Build: keep your own code"]
  B -- yes --> C{"Hard gates pass by default<br/>or by a documented, tested setting?"}
  C -- no --> BUILD
  C -- "unknown" --> SPIKE["Spike: test the gates,<br/>then adopt or build"]
  C -- yes --> D{"Portability and churn<br/>acceptable?"}
  D -- yes --> ADOPT["Adopt the framework"]
  D -- no --> BUILD
  W --> R["Record the decision<br/>and what would change it"]
  BUILD --> R
  SPIKE --> R
  ADOPT --> R

Every path ends in a record, so the answer to "why is this loop hand-written?" doesn't depend on who is still on the team. The revisit conditions matter as much as the decision: "build, until runs must survive a restart" says when to come back.

7. Three Kestrel requests through the checklist

A checklist is only useful if it can reach different answers. Here it is applied to three requests from earlier chapters, and each one leaves a record in ch12-agent-frameworks/decisions/.

Priya Nair's expense claims

In Chapter 5 we extracted fields from Priya's free-text expense claims into a validated ExpenseClaim and flagged policy breaches. Code fixes the sequence: read the claim, call the model once to extract, validate with pydantic, retry with feedback if validation fails, then run the policy checks in Python. The model never chooses a next step, and nothing waits for approval. It's a workflow with model steps and no durable needs, so the checklist stops at question 0.

ch12-agent-frameworks/decisions/expense-claims.md
# Decision: expense-claim extraction

Decision: no framework; no agent loop.
Placement: workflow with model steps (code fixes the sequence).
Need: none. Nothing waits for approval or has to survive a restart.
Gates: not reached; the checklist stops at question 0.
Revisit if: the model must choose which records to fetch
(for example, looking up past claims on its own).

Tomasz Wójcik's late-shipment investigation

The operations agent from Chapters 7 and 8 really is an agent. The model decides whether to list late shipments, look up one delivery, read a ticket or check stock, and when it has enough to answer. Its tools are narrow and read-only, its budget is tight, and Tomasz runs it from the command line, one question at a time.

The need questions all come back empty. A single run needs nothing that outlives the process, and the model already picks the steps, so a graph adds nothing. Your own code meets the hard gates, and the edges demo you just ran shows it. Adopting a framework would mean rewriting those tests against someone else's defaults and taking on an exit cost, with no new capability.

ch12-agent-frameworks/decisions/late-shipments.md
# Decision: late-shipment investigation

Decision: build (keep run_agent).
Placement: agent with narrow tools and a tight budget; read-only reach.
Need: none now. One command-line run, short-term state only.
Gates: met by our loop (Chapter 11's version) and shown by fake-model tests:
budget checked before each call, partial result with a StopCause at a limit,
invented arguments, unknown tools and tool failures returned as error results
(tests/test_edges.py).
Revisit if: runs must survive a process restart, or the tool set gains a write.

Maya Okafor's return authorisations

Now extend Maya's support assistant so it can issue return authorisations through Chapter 8's idempotent create_return_authorisation, which writes to a local SQLite return store, not to the read-only mock API. The change brings two new requirements: a person approves before the write, and a run can pause for approval and resume after a process restart. Question 1 returns yes.

Building it yourself means versioned state saved after each step, a table of pending approvals, a new stop cause for "awaiting approval" and a resume path that reuses the idempotency key. Then come the failure modes: a crash between approval and execution, racing resumes, stale approvals and who may approve.

That is exactly what a graph library with durable checkpoints offers, so this time a candidate gets a real look. LangGraph's documentation covers the need: graph state saved step by step under a thread ID, so a run can stop for a person and pick up again, with the warning that the in-memory savers don't survive a restart. The gates are a different matter. The sources checked here don't say how it shows prompts, how it behaves at its limits or what it does with an unknown tool, and those answers come from a short spike with fake-model tests, not from reading. There is also a narrower option: keep run_agent as the agent node and adopt only LangGraph's graph and checkpointer for the approval pause. Your loop keeps its budget, stop causes and error results, so most gates stay answered by your own tests, and the spike shrinks to checkpoints and resume. The price is two layers to learn and state in two places: the loop's messages inside the node, the graph's state around it. Since checkpoints fall between steps of the graph, a crash inside the agent node reruns that whole node. The record tests this option first, then adoption as a whole:

ch12-agent-frameworks/decisions/return-authorisations.md
# Decision: return authorisations with human approval

Decision: spike, then adopt LangGraph if it passes gates 2 to 5; else build.
Spike first: run_agent stays the agent node; LangGraph owns only the graph,
checkpoints and approval edge. Then, if needed, LangGraph for the whole run.
Placement: agent with a wider tool set: the model picks the lookups and whether
to propose a return; code fixes one edge, approval before the write
(create_return_authorisation, local SQLite store, Chapter 8).
Need: persistence across restarts and an approval pause. Its docs cover both:
a checkpoint per super-step, keyed by thread_id, used for human-in-the-loop
resume. The in-memory savers lose everything on restart, so production needs
a persistent one.
Gates: to test in the spike, with fake-model tests: visibility of prompts,
limits (stop cause or exception?), unknown-tool handling, built-in tools.
Portability and churn: weighed after the spike.
Build cost if we fall back: versioned JSON state per step, a pending_approvals
table, a dispatcher check, a new stop cause for "awaiting approval", a resume
path that reuses the idempotency key, and answers for crashes between approval
and execution, racing resumes, stale approvals and who may approve. Stored
state holds customer data.
Revisit if: the spike fails a gate, or approval moves out of the agent.

Across the three requests, more autonomy wasn't progress in itself. Scenario 3 gained reach, a write, and more reach calls for more control, not more freedom. Approval steps and durable state are the controls that write needs, and graph libraries sell them, which is why adoption was live only here.

Each checklist answer depends on what the system needs now, not on how far right it sits on the spectrum.

8. Why the capstone stays framework-free

Sam Adeyemi's research assistant, which Chapters 14 to 16 build, goes through the same checklist. At question 0 it's an agent with narrow tools and a tight budget. Its four read-only tools are search_web, read_file (limited to one sandboxed folder of Kestrel exports), count_rows and calculate, with no shell; Chapter 14 designs them and Chapter 15 builds them.

Question 1 decides it. The assistant handles one question per run and keeps short-term state only. Nothing has to survive a restart, there's no approval step to pause on, there's no fixed sequence for a graph to enforce, and the step log records what your code needs. With no question 1 need, the checklist says build, and the hard gates never come into play.

Two further points support the answer without deciding it. The first is teaching: the book's capstone should be code you understand line by line. The second is portability, which the capstone requires: "any provider whose model supports tool calling". Your Chapter 3 and Chapter 11 adapters meet it for the providers they cover. The tool runner ships inside Anthropic's SDK and the Agent SDK runs the bundled CLI; I didn't check either against other providers, so neither would meet the requirement without that check.

This is the record Chapter 14 copies into its spec:

ch12-agent-frameworks/decisions/capstone.md
# Decision: research assistant agent loop

Decision: hand-written agent loop (run_agent), no agent framework.
Placement: agent with narrow tools and a tight budget; read-only reach.
Context: one question per run from the command line; four read-only tools
(search_web, read_file from the sandboxed folder, count_rows, calculate);
no shell;
run budget per question of steps, tokens and wall time, plus money (designed
in Chapter 14, enforced in Chapter 16); any provider whose model supports
tool calling.
Need: none (checklist Q1). No persistence, hook or graph need; one run,
short-term state only. No need means build.
Gates: not run against a named candidate; our loop meets them (late-shipments).
Separate reason: teaching goal; every line of the loop is readable and explained.
Portability: required; met by the Chapter 3 and Chapter 11 adapters. The
Anthropic tool runner ships inside Anthropic's SDK and the Agent SDK runs the
bundled Claude Code CLI; other providers were not checked for either.
Accepted costs: we maintain the loop; no built-in sessions or tracing UI.
We build these: retries and failure classes, and the money limit with its
cost_limit stop cause (Chapter 16).
Revisit if: runs must survive a process restart; a human approval step is
added; the work splits across several agents (Book 5).

The "We build these" line is part of the accepted cost. A framework might have supplied some of that handling; here it is your work, and Chapter 16 does it. The decision holds for this system and this book's teaching goals. It doesn't say frameworks are the wrong choice. If Sam later asks for a restart-proof run or an approval step, the "Revisit if" line tells the next engineer to run the checklist again rather than defend the old answer.

The records are checked too, so a new one can't skip a question:

text
$ uv run python -m ch12.records
capstone                 hand-written agent loop (run_agent), no agent framework.
expense-claims           no framework; no agent loop.
late-shipments           build (keep run_agent).
return-authorisations    spike, then adopt LangGraph if it passes gates 2 to 5; else build.
4 records, 0 problems

9. Exercises

Exercise 1: extend the mapping. Add a row to the mapping table for an agent framework of your choice. Fill it only from official documentation or the repository, date it once, and list what the docs leave open. Expected result: at least the budget-limit and unknown-tool questions answered, each with a link. Common mistakes: citing a blog post instead of the docs, or filling a cell from what you assume the framework does.

Exercise 2: a new request. Daniel Reyes wants a weekly summary of each trade customer's open orders and late shipments. Run checklist.md. Hint: answer question 0 first; a scheduled workflow with one model step and no durable needs may stop right there. Verify: write decisions/weekly-summary.md and run uv run python -m ch12.records; it should report 5 records and 0 problems.

Exercise 3: adapt a raising default. Suppose a library raised an exception when a run hit its request limit. Write a wrapper that catches it and returns a RunResult with StopCause.STEP_LIMIT, the messages so far and the step log, so your callers keep checking the stop cause. Verify: a fake-model test in which a scripted client raises at its fourth call and the wrapper returns a partial result instead of raising; uv run pytest -q.

Exercise 4 (reflection): estimate exit cost. Suppose the capstone had adopted a framework. List the modules that would import its types (the loop, tool definitions, adapters) and what you'd rewrite to remove it.

10. Summary and what comes next

An agent framework re-implements parts you've already built. Mapped onto five options, the documented budget, tool-error and stop behaviour mostly overlaps with what you have, with different defaults, while sessions, hooks and checkpoints point to capabilities you lack. Judge a framework by its defaults at the edges: what happens at a limit, whether an unknown tool becomes an error result or an exception, which built-in tools it brings, and whether you can still see every prompt and response.

Frameworks add persistence, hooks and graph orchestration, each documented by at least one option here, and each is work you would otherwise maintain. They cost abstraction and upgrade churn, and a runtime can also cost lock-in. The build-or-adopt checklist starts with the autonomy spectrum, applies four hard gates once a real need exists, weighs portability and churn, and ends with a written decision and its revisit conditions. The return-authorisation request reached a spike that can end in adoption; the capstone has no question 1 need, so it builds, and decisions/capstone.md is ready for the Chapter 14 spec.

Whichever way you decide, the next question is the same: how do you know the agent behaves correctly? Chapter 13, Testing your first agent: golden tasks, traces and simple evals, answers it with evidence rather than one good run.

Bishal SahaLet's build together

Have a system to design, or an AI feature to get right?

Tell me about the problem. You'll get a clear, honest view of the best way forward.

  • Reply within 24 hoursOn business days, with my honest view and a next step.
  • Accepting select engagementsArchitecture, AI features and full builds.
  • Remote, worldwideWorking with startups, SMEs and enterprises.