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
- Who decides the next step? Workflows and agents
- A tool is a schema, a function and an error message, and the model reads two of them
- One tool call, three wire formats
Advanced
- Parallel tool calls: reads commute, writes do not
- Retry the server, not the model: errors, backoff and jitter
- A step is not a unit of cost: four budgets and a stop reason
- An answer a program can read: schemas and one repair
- A streamed tool call is half a JSON object
Expert
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
- Anthropic. "Building effective agents." 2024. Workflows before agents.
- Xia, C. S., Deng, Y., Dunn, S. and Zhang, L. "Agentless: demystifying LLM-based software engineering agents." 2024.
- Kapoor, S., Stroebl, B., Siegel, Z. S., Nadgir, N. and Narayanan, A. "AI agents that matter." 2024. Cost beside accuracy.
- Yao, S. et al. "ReAct: synergizing reasoning and acting in language models." ICLR 2023. The loop's ancestor.
- Schick, T. et al. "Toolformer: language models can teach themselves to use tools." NeurIPS 2023.
- Patil, S. G., Zhang, T., Wang, X. and Gonzalez, J. E. "Gorilla: large language model connected with massive APIs." 2023. Wrong arguments and invented APIs, measured.
- OpenAI. "Function calling." API guide, read October 2026: the Responses format,
parallel_tool_calls, streamed argument deltas. - Anthropic. "Tool use with Claude" and "Parallel tool use." Documentation, read October 2026:
tool_useandtool_resultblocks, one user message for all results. - Ollama. "OpenAI compatibility." Documentation, read October 2026.
- Wright, A., Andrews, H. and Hutton, B. (eds.) "JSON Schema Validation." Draft 2020-12.
- Brooker, M. "Exponential backoff and jitter." AWS Architecture Blog, 2015.
- Beyer, B., Jones, C., Petoff, J. and Murphy, N. R. (eds.) Site Reliability Engineering. O'Reilly, 2016; chapter 21, "Handling Overload": per-client retry budgets and adaptive throttling.
- Fielding, R., Nottingham, M. and Reschke, J. (eds.) "HTTP Semantics." RFC 9110, 2022. Section 10.2.3, Retry-After.
- WHATWG. "Server-sent events." HTML Standard, section 9.2.
- Tam, Z. R. et al. "Let me speak freely? A study on the impact of format restrictions on performance of large language models." 2024.
- Willard, B. T. and Louf, R. "Efficient guided generation for large language models." 2023. Constrained decoding.
- Yao, S., Shinn, N., Razavi, P. and Narasimhan, K. "τ-bench: a benchmark for tool-agent-user interaction in real-world domains." 2024. pass^k.
- Sinha, A., Arun, A., Goel, S., Staab, S. and Geiping, J. "The illusion of diminishing returns: measuring long horizon execution in LLMs." 2025. Self-conditioning.
- Kwa, T. et al. "Measuring AI ability to complete long software tasks." 2025. The 50% time horizon.
- Wang, X. et al. "Executable code actions elicit better LLM agents." ICML 2024. CodeAct.
- Yang, J. et al. "SWE-agent: agent-computer interfaces enable automated software engineering." NeurIPS 2024.
- In practice: every agent framework implements this loop (E4 compares three); HTTP clients with retry policies (httpx transports, urllib3 Retry, tenacity); JSON Schema validators (jsonschema). Compare what each does at the limits with the lessons before trusting its defaults.