Learn to build your first AI agent with 5 practical Python scripts covering tool use, planning, memory, error recovery, and safety.
Most beginners start using language models through a chat interface: enter a prompt, get a response, and move on. An AI agent works differently. It decides what to do next, uses tools to carry out actions, evaluates the results, and repeats the process until the task is complete.
That sounds like it needs a heavyweight framework, but the idea is simple to code. The more interesting questions are: how do you keep the model's output well-formed, let it plan ahead and recover from mistakes, make it remember things across sessions, and stop it from doing something you would regret?
The five scripts below walk through those questions in order, from a super simple loop to a supervised agent. Every script has an offline --mock or --demo mode that runs with no API key, so you can watch the mechanics first and plug in any model of your choosing afterwards.
You can find all the scripts on GitHub.
1. A Simple ReAct Loop #
The Pain Point
Agent frameworks hide the loop behind abstractions, which makes the first agent you build feel like a black box, and black boxes are hard to debug. When something goes wrong, you cannot tell whether the model reasoned badly, a tool failed, or the framework swallowed an error.
What the Script Does
Implements the "reason, act, observe" pattern in plain Python. The model writes a thought and picks a tool, the script runs it, and the result is fed back as an observation. This repeats until the model produces a final answer or hits a step limit. It ships with three small tools: a calculator, a word counter, and a date lookup.
How It Works
The model is instructed to reply in a strict Thought / Action / Action Input format. A stop sequence on Observation: prevents it from inventing tool results, so the script always supplies a valid one. Replies are parsed with regular expressions; if the model breaks format, it is told so and gets another chance. The calculator parses expressions with Python's ast module instead of calling eval, so the model can never execute arbitrary code through it. A hard max_steps cap guarantees the loop always terminates.
2. A Type-Safe Agent with Pydantic AI #
The Pain Point
Free-text output is fragile. If downstream code expects a priority of high and the model says urgent, or forgets a field, something breaks later and far from the cause. Parsing and re-prompting by hand is inefficient.
What the Script Does
Triages customer support tickets into a strict Pydantic model: category, priority, summary, sentiment, an escalation flag, and tags. The result you get back is a real Python object, not a string you have to trust.
How It Works
The agent is created with output_type=TicketTriage, and Pydantic AI passes that schema to the model and validates every reply. When validation fails, the error message goes back to the model so it can correct itself, up to a retry limit. A second layer, an @output_validator, enforces a rule a schema cannot express: critical tickets must be escalated. The offline mock deliberately returns two bad answers before a good one, so you can see both layers catch a problem and report how many retries were needed.
⏩ Get the Pydantic AI agent script
3. A Planner-Executor Agent That Re-Plans #
The Pain Point
A step-by-step loop like the ReAct loop above asks the model what to do next after every single action. That is flexible, but it costs a model call per step, and you cannot see what the agent intends to do until it has already done it. The opposite approach, planning everything up front, has its own problem: the plan is written before the agent has seen any data, so it will sometimes be wrong.
What the Script Does
Analyzes a CSV file by writing a complete plan first, then running 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. When every step has run, it writes a short report from the collected results. The offline demo plans a step with a column name that does not exist, so you can watch it fail, re-plan, and recover.
How It Works
The planner returns its plan as a JSON array, and the script validates it before anything runs: known tools only, exactly the expected arguments, and a maximum number of steps. A malformed plan is sent back to the model once with the reason. The executor is ordinary Python and makes no model calls while running steps. Tool failures raise a specific error type that carries a helpful message, such as listing the columns that do exist, and that message is 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 one workspace folder.
⏩ Get the planner-executor agent script
4. A Local Memory Manager #
The Pain Point
Language models are stateless, so a conversation only "remembers" what you resend. Resending everything is expensive and eventually overflows the context window. Dropping old messages makes the assistant forget your name halfway through.
What the Script Does
Gives a chat assistant three layers of memory, stored in a JSON file that survives restarts: a window of recent messages, a running summary of older ones, and a list of long-term facts you can add with /remember.
How It Works
Once the recent window exceeds a token budget, the oldest messages are folded into the summary and removed from the window; the cut point is moved so the window still starts on a user message, as the API requires. Facts are retrieved by keyword overlap with the current message, so only relevant ones are injected into the system prompt rather than all of them. Saves are atomic (write to a temp file, then replace), so a crash cannot corrupt the file. The summarizer is pluggable: a simple extractive version for the demo and an LLM-written one for real chats.
⏩ Get the memory manager script
5. A Human-in-the-Loop Gatekeeper #
The Pain Point
The moment an agent can write files, send email or delete things, a mistaken tool call stops being a bad answer and becomes a real-world side effect. You want the agent's autonomy for the safe steps and a human's judgment for the risky ones.
What the Script Does
Wraps every tool in a risk level. Safe tools run immediately, confirm-level tools for a y, n or a (always allow), high-risk tools require you to type yes, and blocked tools never run. Every decision lands in an audit log.
How It Works
A gatekeeper sits between the model's request and the tool call. If the human denies an action, the denial, plus an optional note such as n: use a different filename, is returned to the model as a tool result so it can adapt instead of retrying blindly. The gate fails closed: if input is unavailable, the action is denied. File tools are confined to a workspace folder, and the email tool is simulated, writing to an outbox file, so you can experiment safely.
Wrapping Up #
Here is a summary of all five scripts:
| Script Name | Purpose | Key Features | Best Use Case |
|---|---|---|---|
| ReAct Loop | Show the core agent loop | Text parsing, stop sequences, safe calculator, step cap | Understanding how agents work before using a framework |
| Pydantic AI Agent | Enforce structured output | Schema validation, retries, output validator | Feeding model output into other code reliably |
| Planner-Executor Agent | Plan first, then execute | JSON plan validation, re-planning on failure, step caps | Multi-step tasks where you want to inspect the plan |
| Memory Manager | Remember across turns and sessions | Rolling summary, fact recall, atomic saves | Long-running assistants and personal chatbots |
| Human-in-the-Loop Gatekeeper | Approve risky actions | Risk tiers, fail-closed, audit log, denial notes | Agents that write, send or delete |
Start with the offline modes to understand the basics, then switch to a model of your choosing and change one thing at a time. Happy building!
Bala Priya is a developer, educator, and technical writer based in India. She writes about programming, data science, machine learning, and AI, with a focus on making complex technical ideas practical and approachable. She creates tutorials, how-to guides, and deep dives that help developers build, solve problems, and understand complex technical concepts. Her technical interests include LLM applications, agentic AI, graph algorithms, computer vision, explainable AI, and ML systems. When she’s not writing or coding, Bala is usually reading classic literature, epic fantasy, or speculative fiction. She also enjoys talking about books, learning new things, and sharing what she learns with the developer community.