{"slug": "5-useful-python-scripts-for-building-your-first-ai-agent", "title": "5 Useful Python Scripts for Building Your First AI Agent", "summary": "A tutorial published on Machine Learning Mastery walks through five Python scripts for building a first AI agent, covering a ReAct loop, Pydantic AI type-safe output, planning, memory and safety, with every script offering an offline --mock or --demo mode that runs without an API key. The first script implements the reason-act-observe pattern in plain Python with three tools — a calculator, a word counter and a date lookup — parsing calculator expressions with Python's ast module instead of eval and enforcing a hard max_steps cap. The second uses Pydantic AI with output_type=TicketTriage to validate customer-support triage output against a strict schema, re-prompting on validation failure up to a retry limit, plus an @output_validator requiring critical tickets to be escalated.", "body_md": "# 5 Useful Python Scripts for Building Your First AI Agent\n\nLearn to build your first AI agent with 5 practical Python scripts covering tool use, planning, memory, error recovery, and safety.\n\nMost beginners start using [language models](https://machinelearningmastery.com/7-concepts-behind-large-language-models-explained-in-7-minutes/) through a chat interface: enter a prompt, get a response, and move on. An [AI agent](https://www.ibm.com/think/topics/ai-agents) 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.\n\nThat 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?\n\nThe 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.\n\n[**You can find all the scripts on GitHub**](https://github.com/balapriyac/data-science-tutorials/tree/main/building-your-first-ai-agent).\n\n## 1. A Simple ReAct Loop\n\n#### The Pain Point\n\n[Agent frameworks](https://www.kdnuggets.com/top-7-ai-agent-orchestration-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.\n\n#### What the Script Does\n\nImplements 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.\n\n#### How It Works\n\nThe 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](https://www.kdnuggets.com/5-tips-for-using-regular-expressions-in-data-cleaning); if the model breaks format, it is told so and gets another chance. The calculator parses expressions with **[Python's `ast` module](https://docs.python.org/3/library/ast.html)** instead of calling `eval`, so the model can never execute arbitrary code through it. A hard `max_steps` cap guarantees the loop always terminates.\n\n## 2. A Type-Safe Agent with Pydantic AI\n\n#### The Pain Point\n\nFree-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.\n\n#### What the Script Does\n\nTriages customer support tickets into a strict **[Pydantic](https://pydantic.dev/docs/validation/latest/get-started/)** 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.\n\n#### How It Works\n\nThe agent is created with `output_type=TicketTriage`, and **[Pydantic AI](https://pydantic.dev/docs/ai/overview/)** 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.\n\n⏩ **Get the Pydantic AI agent script**\n\n## 3. A Planner-Executor Agent That Re-Plans\n\n#### The Pain Point\n\nA step-by-step loop like the [ReAct loop](https://www.ibm.com/think/topics/react-agent) 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.\n\n#### What the Script Does\n\nAnalyzes 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.\n\n#### How It Works\n\nThe 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.\n\n⏩ **Get the planner-executor agent script**\n\n## 4. A Local Memory Manager\n\n#### The Pain Point\n\nLanguage 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.\n\n#### What the Script Does\n\nGives 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`.\n\n#### How It Works\n\nOnce 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.\n\n⏩ **Get the memory manager script**\n\n## 5. A Human-in-the-Loop Gatekeeper\n\n#### The Pain Point\n\nThe 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.\n\n#### What the Script Does\n\nWraps every tool in a risk level. Safe tools run immediately, confirm-level tools pause 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.\n\n#### How It Works\n\nA 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.\n\n## Wrapping Up\n\nHere is a summary of all five scripts:\n\n| Script Name | Purpose | Key Features | Best Use Case | \n|---|---|---|---|\n| ReAct Loop | Show the core agent loop | Text parsing, stop sequences, safe calculator, step cap | Understanding how agents work before using a framework | \n| Pydantic AI Agent | Enforce structured output | Schema validation, retries, output validator | Feeding model output into other code reliably | \n| 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 | \n| Memory Manager | Remember across turns and sessions | Rolling summary, fact recall, atomic saves | Long-running assistants and personal chatbots | \n| Human-in-the-Loop Gatekeeper | Approve risky actions | Risk tiers, fail-closed, audit log, denial notes | Agents that write, send or delete | \n\nStart 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!\n\n \n\n \n\n**[Bala Priya](https://github.com/balapriyac)** 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.\nShe 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.\nWhen 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.", "url": "https://wpnews.pro/news/5-useful-python-scripts-for-building-your-first-ai-agent", "canonical_source": "https://www.kdnuggets.com/5-useful-python-scripts-for-building-your-first-ai-agent", "published_at": "2026-11-30 13:00:00+00:00", "updated_at": "2026-11-30 13:15:04.365213+00:00", "lang": "en", "topics": ["ai-agents", "ai-tools", "large-language-models", "developer-tools"], "entities": ["Machine Learning Mastery", "Pydantic AI", "Pydantic", "Python", "GitHub"], "also_reported_by": [], "takeaway": "Build the agent loop in plain Python with a strict Thought/Action/Action Input format, a stop sequence on 'Observation:' so the model cannot invent tool results, and a hard max_steps cap, then validate structured output with Pydantic AI's output_type plus an @output_validator for rules the schema ca", "recommendation": {"advice": "Write the ReAct loop yourself with a stop sequence on 'Observation:' and a max_steps cap, and parse calculator input with Python's ast module rather than eval to block arbitrary code execution.", "playbook": "agent-architecture", "playbook_url": "https://wpnews.pro/playbooks/agent-architecture"}, "alternates": {"html": "https://wpnews.pro/news/5-useful-python-scripts-for-building-your-first-ai-agent", "markdown": "https://wpnews.pro/news/5-useful-python-scripts-for-building-your-first-ai-agent.md", "text": "https://wpnews.pro/news/5-useful-python-scripts-for-building-your-first-ai-agent.txt", "jsonld": "https://wpnews.pro/news/5-useful-python-scripts-for-building-your-first-ai-agent.jsonld"}}