Lesson 05 · Core Skills

Tool Use & the Agent Loop

An agent is a while loop. The engineering is deciding when to write one.

FDE skill · match the architecture to the problem, not the hype
🎧 Listen to this lesson · ~5 min · narrated audiobook edition

⏱ ~7 min read · 🎧 5 min listen · ✎ 3 quizzes · 🧪 ~40 min lab

Lesson 04 ended on a cliffhanger: the model can request a tool call, get the result, and request another. Put that cycle in a loop and you have the year's most hyped word — an agent. The mechanics will take you ten minutes, and the lab has you build one from scratch. The real FDE skill is the judgment around it: knowing when a customer problem needs an agent, when a plain workflow beats it, and what guardrails keep a loop from burning money at 2 a.m.

The agent loop is a while loop

Here is the entire mechanism, in the pseudocode style of Lesson 01:

messages = [task]
loop:
    response = model(messages, tools)
    if response has no tool calls: break   # the model decided it's done
    for call in response.tool_calls:
        result = your_code.execute(call)   # YOU still execute everything
        messages.append(result)

That's it. The model plans, requests actions, sees results, and decides what to do next — using environmental feedback instead of a script you wrote in advance. Everything from coding assistants to research agents is this loop with better tools and prompts.1 Note what did not change from Lesson 04: your code still executes every action. The loop hands the model initiative, never authority.

A definition that stuck After years of "agent" meaning everything and nothing, Simon Willison declared the industry had finally converged: "An LLM agent runs tools in a loop to achieve a goal." Thirteen words, and every one of them maps to a line of the pseudocode above. If a vendor's "agent" doesn't fit that sentence, ask what they're actually selling.

Workflows vs. agents — the distinction that earns you money

Anthropic's engineering guide draws the line an FDE should tattoo somewhere: a workflow orchestrates model calls through predefined code paths — you decide the steps. An agent directs its own process — the model decides the steps.1 Workflows are predictable, testable, and cheap; agents are flexible, meandering, and expensive.

Most customer problems dissolve into a handful of workflow patterns the guide names: prompt chaining (steps in sequence, each consuming the last output), routing (classify, then dispatch to a specialist prompt), parallelization (fan out, then aggregate or vote), orchestrator–workers (one model delegates subtasks), and evaluator–optimizer (one model drafts, another critiques, repeat). Notice these are just Lesson 04's building blocks arranged by your code.

Agents earn their cost on open-ended problems where you can't predict the number of steps — debug this failing build, research this question across many documents — and where success is verifiable, so the loop knows when to stop. Without a checkable goal, an agent is a random walk with an invoice.1

The guide's first advice is "don't" "Building Effective Agents" opens not with architectures but with restraint: find the simplest solution, and only add agentic complexity when the simpler one demonstrably fails. The most successful production deployments, it notes, use simple composable patterns — not frameworks stacked on frameworks.

Guardrails: engineering the loop for production

Three guardrails turn a demo loop into something a customer can run. Bound it: a max-iteration cap and a budget cap, because a confused agent's failure mode is an infinite, token-burning loop. Gate the side effects: reads can be autonomous; writes — refunds, emails, deletes — pause for human approval or run in a sandbox first. Make success checkable: define what "done" looks like so both the agent and your monitoring can tell finished from stuck.

And one cost note straight from Lesson 02: the loop re-sends the growing conversation every iteration. Twenty turns in, each call carries the whole trail of tool results — so agent cost grows roughly with the square of the transcript, not linearly. Scoping an agent feature without modeling that curve is the classic first-project mistake.

You've been inside one all course If you've used an AI coding assistant that reads files, runs tests, and edits code until the build passes — that's this exact loop. Anthropic's guide lists coding agents as the archetypal case: open-ended steps, but a verifiable goal (tests pass). Notice both halves; the verifiability is what makes it work.

🧪 Lab: build an agent from scratch — no framework

The lab file is labs/0005-agent-loop.py. In ~80 lines you'll build a support agent with three tools — look up an order, search a tiny knowledge base, and issue a refund — and the while loop from this lesson, instrumented so every iteration prints what the model requested and what your code did.

Then you'll watch the three guardrails work: a task that finishes in two turns, a MAX_TURNS cap, and the refund tool gated behind a y/n human approval — you are the authorization step. Run the multi-step task and read the trail: the model chains lookups you never scripted. That moment — unscripted but bounded — is the whole lesson in one screen of output.

🤖 Get your work reviewed

No chat here — this box replaces it. Copy the prompt into any AI assistant (Claude, ChatGPT, Gemini…), then paste your work after it.

You are a senior AI engineer reviewing my work: the printed trail of my from-scratch agent lab (labs/0005-agent-loop.py) plus my written answers to two design questions: (1) for a given customer feature, would I build a workflow or an agent, and why; (2) which guardrails my agent has and what failure each prevents.

Grade each item as Strong / Adequate / Missing, with one sentence of evidence:
- My trail shows a genuine multi-step run: the model chose tool calls I didn't script, and the loop terminated on its own decision.
- My workflow-vs-agent call is argued from predictability of steps and verifiability of success, not from hype.
- I identify all three guardrail types (iteration/budget bounds, gated side effects, checkable success) and tie each to a concrete failure mode.
- I can explain why agent cost grows superlinearly with conversation length (the loop re-sends the growing transcript).

Be skeptical — challenge my weakest justification first. Then ask me 2–3 follow-up questions a customer's engineering lead would ask before approving an agent in production. Finish with the single highest-leverage improvement.

My work follows below.

Check yourself — architect the solution

Three customer requests. Don't scroll up — pick the architecture from the mechanism. Wrong picks stay live.

Scenario A

A customer wants every inbound invoice processed the same way: extract fields, validate against the PO, file it, flag mismatches. "We want an AI agent for this," they say. What do you build?

Scenario B

Your deployed agent occasionally gets stuck re-searching the same query for hours, and one incident cost $400 in tokens overnight. Which guardrail was missing?

Scenario C

Finance flags that your agent's per-task cost doubles when average task length goes from 10 to 15 turns, not +50%. Why?

Primary source — read this
The most-cited engineering guide on this topic: the workflow patterns, the workflows-vs-agents line, and the "start simple" discipline — from the team that builds the models. Twenty minutes, and you'll recognize every pattern from this lesson.
Your one tangible win A customer says "we want an agent." You can now ask the two questions that decide the architecture — are the steps predictable? is success verifiable? — sketch the workflow pattern or the bounded loop that fits, and price the difference. You've also built an agent with your own hands, so no framework can mystify you again.
Questions? Loop not terminating? Wondering how frameworks like LangChain relate to your 80 lines? Paste the relevant lesson section — or your agent's trail — into any AI assistant (Claude, ChatGPT, Gemini…) and ask. For a structured review of your lab, use the box above.

Recommended learning

Hand-picked follow-ups on agents. None are required — the primary source above comes first.

References

  1. Anthropic, "Building Effective Agents" (2024) — workflows vs. agents, the five workflow patterns, and when agents are worth it.
  2. Chip Huyen, AI Engineering (O'Reilly, 2025) — agent architectures, planning, and failure modes.
  3. Anthropic, Tool use documentation — the tool_use/tool_result cycle the loop is built on (verified July 2026).