Blurry Photo of Lines of Code on Screen

Build an AI Agent From Scratch: Five Python Scripts That Show the Loop

Why a first agent feels like a black box

A chat application is, at heart, elaborate autocomplete. You send a prompt, the model returns text, and the program stops. Most LLM applications never move past that shape, as a walkthrough of the OpenAI Agents SDK and the agent loop it wraps explains.

An agent loop adds three moves: reason about the state, act through a tool, observe the result. Frameworks wrap that cycle in planners, executors, memory managers and callback systems. Those abstractions are useful at scale, but on a first build they hide the very thing you need to debug. Writing the cycle yourself in plain Python means every tool call, every validation retry and every re-plan is a line of code you can print, step through and inspect.

Script 1: the ReAct loop

The first script implements the reason, act, observe pattern in its most literal form. The model writes a thought and picks a tool, the script runs the tool, and the result is fed back as an observation. The loop repeats until the model produces a final answer or hits a hard max_steps cap that guarantees termination.

Three small tools keep it concrete: a calculator, a word counter and a date lookup. The model must reply in a strict Thought / Action / Action Input format, and the script parses replies with regular expressions. When the model breaks format, it is told so and gets another chance rather than crashing the program.

Two details carry most of the engineering weight. First, a stop sequence on Observation: prevents the model from inventing tool results; the script always supplies a valid observation itself. Second, the calculator parses expressions with Python’s ast module instead of calling eval, so the model cannot execute arbitrary code through a tool argument. If you only copy two habits from this article, make them these.

Script 2: structured outputs with Pydantic AI

Free text is fragile. If downstream code expects a priority of “high” and the model writes “urgent”, or omits a field entirely, the failure surfaces later and far from its cause. The second script triages customer support tickets into a strict Pydantic model with six fields: category, priority, summary, sentiment, an escalation flag and tags. The result is a real Python object, not a string.

The agent is created with output_type=TicketTriage. Pydantic AI passes the schema to the model and validates every reply, sending validation errors back so the model can correct itself up to a retry limit. A second layer, an @output_validator, enforces a rule the schema cannot express: critical tickets must be escalated.

The offline mock is deliberately unhelpful. It returns two bad answers before a good one, so you can watch both layers catch a problem and report how many retries were needed. That is the point of the exercise: validation is not a formality, it is a control surface you should see fire.

Script 3: plan, then execute

A step-by-step loop costs a model call per step and reveals its intent only after acting. Planning everything up front has the opposite weakness: the plan is written before any data is seen, so it can be confidently wrong. The third script accepts both costs and shows where they bite.

It analyzes a CSV file by writing a complete plan first, then executing it. If a step fails, the model is shown what has been done and what went wrong, and writes a new plan for the remaining work. A short report is assembled from the collected results at the end. The offline demo plans a step using a column name that does not exist, so you can observe the failure, the re-plan and the recovery in sequence.

The safeguards are the interesting part. The planner returns its plan as a JSON array, validated before anything runs. The executor itself is ordinary Python and makes no model calls, which keeps execution deterministic and cheap. The rules are worth scanning as a list:

  • Known tools only, with exactly the expected arguments and a maximum number of steps.
  • A malformed plan goes back to the model once, with the reason attached.
  • Tool failures raise a specific error type carrying a helpful message, such as a list of the columns that actually exist. That message is precisely what lets the planner fix its mistake.
  • Re-planning is capped at two attempts, and a global step limit stops the agent even if the model keeps producing bad plans.
  • File access is confined to a single workspace folder.

Script 4: three-layer memory

Language models are stateless, so a conversation only “remembers” what is resent with each call. Resending everything is expensive and eventually overflows the context window; dropping old messages makes the assistant forget details the user mentioned earlier. The fourth script splits the difference with three layers stored in a JSON file that survives restarts: a window of recent messages kept verbatim, a running summary of older ones, and a list of long-term facts the user adds with /remember.

The design question worth sitting with is what belongs in each layer. Recent turns need fidelity, summaries need compression without losing commitments, and long-term facts need to be explicit rather than inferred. Persisting to JSON also makes the memory inspectable, so you can read the assistant’s state directly instead of guessing why it forgot something.

Script 5: error recovery and safety

The fifth script is a small harness rather than a full agent, and it exists to make the safety layers explicit before you add them to anything real. It runs a tool that fails on purpose, then shows the three recovery paths side by side: a typed error that carries a fixable message, a bounded retry that gives up after a fixed count, and a hard step cap that terminates the run regardless of what the model wants to do next. The offline mode replays a scripted failure so you can watch each path fire without a model call.

The earlier scripts already gesture at the same concerns: retry limits, step caps, workspace confinement and an AST-based calculator are all safety measures in miniature. Script 5 is where you watch them work as a set. As the layers grow, watch for retry loops that mask persistent model confusion, validators that reject good output on formatting trivia, and any path where model-generated text reaches a file system, shell or network call without a fixed allowlist. The pattern from Script 3 generalizes: make the executor incapable of model calls, and make every failure message specific enough to be fixable.

If you are weighing how much machinery a tool layer really needs, the case for five lightweight alternatives to heavyweight agent protocols like MCP makes a similar argument at the protocol level: correct in spirit, often oversized in practice.

Running the scripts offline

Every script runs without an API key. The --mock mode in the ReAct and Pydantic AI scripts and the --demo mode in the plan-then-execute and error-recovery scripts replay scripted model responses and failures, so you can watch the loop iterate, validation retries fire, a planner recover from a bad column name and a retry cap terminate a bad run. Before plugging in a real model, check four things:

  • That your stop sequence is honored.
  • That the output schema is strict enough to reject plausible-but-wrong answers.
  • That every tool raises typed errors with actionable messages.
  • That your step and retry caps actually terminate a misbehaving run.

It is tempting to start at the top of the ladder, with orchestration frameworks and teams of specialist agents. But the engineers shipping these systems tend to describe a different reality, one that starts with a single loop you fully understand, as a four-level roadmap from single loops to multi-agent teams in production lays out. Five scripts, one loop, every decision visible: that is the foundation everything else is built on.

Similar Posts