Defending AI Agents
עברית Join waitlist
Menu

E3 · Applied · 7 h · Building AI Agents

The agent loop from scratch

Statistical twin A Markov decision process whose policy is a sampled language model and whose horizon is a budget; a run's success is a product of per-step reliabilities, measured as a binomial proportion with a task-clustered interval.

Module 1 gave you an agent in under 100 lines and then spent the course attacking it. This module asks what it takes to make that loop one you could run unattended. It must not crash on a malformed call, die on the first 503, run until the money is gone, or return "about half a million" to a program that wanted an integer. None of that is security, and all of it is what the gateway in Module 3 sits beside. You build each piece by hand, test it against a scripted model, and then measure, on twenty lab tasks and your local model, what the pieces buy together over Module 1's loop.

The module is applied: the value is the loop in loop/, which the later engineering modules extend (E5 gives it retrieval, E6 MCP, E7 workers, E9 an evaluation suite, E11 traces). No framework is used. E4 rebuilds the same agent in three of them and diffs what they send.

You will be able to

Each line ends with badges: its tier, the engineering-track outcome it builds (EO1 to EO8, from the track's curriculum) and where it is assessed (a check group, a problem P, the build or a written answer).

  • Say for a given job whether a workflow or an agent should decide the next step, and what each choice does to cost, latency and testing. Foundations
  • Parse and check a tool call's arguments against its schema, and return errors that name the field and the fix. Foundations
  • Convert a tool-calling history and reply between Chat Completions and Anthropic Messages, both ways. Foundations
  • Run a turn's tool calls with reads in parallel, writes as barriers and results in the order asked, and say why "safe to reorder" is not "safe". Advanced
  • Retry the failures worth retrying with full-jitter backoff and Retry-After, predict a task's success from the per-call failure rate, and check the prediction by simulation. Advanced
  • Bound a run by steps, tokens, cost and wall clock, derive how prompt tokens grow with steps, and report why a run stopped. Advanced
  • Turn a final reply into a value checked against a schema with one repair, and report conformance and correctness separately. Advanced
  • Reassemble a streamed reply, fragments of tool calls included, and act on a call only when it is complete. Advanced
  • Measure your loop against Module 1's on twenty tasks with a paired, task-clustered comparison and pass^k. Advanced
  • Argue about how far a loop can go: compounding error and self-conditioning, the time-horizon trend and its validity, and what code actions gain and cost. Expert

Lessons

Foundations

  1. Who decides the next step? Workflows and agents
  2. A tool is a schema, a function and an error message, and the model reads two of them
  3. One tool call, three wire formats

Advanced

  1. Parallel tool calls: reads commute, writes do not
  2. Retry the server, not the model: errors, backoff and jitter
  3. A step is not a unit of cost: four budgets and a stop reason
  4. An answer a program can read: schemas and one repair
  5. A streamed tool call is half a JSON object

Expert

  1. How far can a loop go? Compounding error, code actions and the time horizon

Then: the build, at scale and problems.

Assumes Module 1 (the lab, the local model and lesson 9's intervals). Uses nothing from Modules 2 to 21. E1 and E2 help but are not required. Module 3 lesson 1 (the tool call as a record) and lesson 5 (the shell) are the security reading of lessons 2 and 9.

Check

make check-E3                                  # under a second: everything but the live test
export TOOLS_URL=http://127.0.0.1:8700         # your lab: the live test and the tasks study reset it
CHECK_E3_LIVE=1 make check-E3                  # with the live test: about two minutes
make loop-study PARTS="faults herd growth"     # the model-free numbers, about 4 seconds
make loop-study PARTS="tasks reps=3"           # the twenty tasks, both loops: about 100 minutes on qwen3:4b
Group Passes when
formats tool schemas and a history with parallel calls, an empty-arguments call and a system prompt convert to Anthropic Messages, all results in one user message; a malformed call kept in the history gets an empty input; a reply converts back with its usage renamed
schema malformed, empty, missing and non-object arguments are told apart; missing, mistyped, unexpected and out-of-enum fields are named, in the docstring's order; true is not an integer and 3.0 is
retry timeouts, refused connections, 429 and 5xx are retried, 4xx and bugs are not; backoff is uniform under its ceiling; Retry-After is honoured; attempts stop at the limit
budget each of steps, tokens, cost and seconds stops a run at its limit, and a second start keeps the first
parallel three slow reads overlap and return in call order; a write is a barrier; refused and failing calls become text; unknown tools and bad arguments are refused before running
structured JSON is found in prose and fences; a reply is checked against a schema
stream text and fragmented tool calls are reassembled in index order, whatever order they arrive in; a later fragment cannot change a call's id or name; whole calls as Ollama sends them pass too
loop the loop answers and records calls and usage; malformed arguments go back to the model and the tool never runs; each budget stops it; model failures are retried as often as retry allows and a permanent one reported; one schema repair, then schema; run(stream=True) asks the model for a stream, and the streamed reply runs
live asked for with CHECK_E3_LIVE=1 and TOOLS_URL: on your local model, your loop completes Module 1's task (summary e-mailed to the manager) in at least one of three tries

Written: your study table (both loops, pass rates with intervals, the paired difference, tokens and seconds per run), and one paragraph on the largest difference you found and whether you believe it.

Readings