Build Your Own Coding Agent in Python — A Beginner's Step-by-Step Guide (Every Step Explained)
An AI agent is a program that thinks with an AI model and acts through tools. In this beginner-friendly build, you will write one small Python program — a coding agent — hand it a real failing test, and watch it find the
An AI agent is a program that thinks with an AI model and acts through tools. In this beginner-friendly build, you will write one small Python program — a coding agent — hand it a real failing test, and watch it find the bug, propose the exact fix, and then stop and wait for your permission before it changes anything. By the end, a test suite that starts at 1 failed, 3 passed ends at 4 passed, and the whole run costs less than one cent. Every step is explained in plain words, with a screenshot — no experience with agents is assumed.
This is the beginner-first edition of our coding-agent build. If you already know what an agent is and want the denser reference version, read the original build instead: Build Your Own Coding Agent in Python (It Fixes Real Code — Behind an Approval Gate). This post covers the same machine more slowly, and adds the two things beginners asked for: what every part means, and what to do when it breaks.
What you need (versions used in this post)
- Python 3.12 — the programming language everything here is written in.
- google-genai 3.0.0 — Google's software kit (an "SDK") for talking to Gemini from Python.
- pytest 9.2.0 — the test runner that checks our demo code.
- The model: gemini-3.8-flash — the current Gemini Flash model. (The older gemini-2.5-flash is being retired on December 1, 2026, so we do not build on it.)
- A free Gemini API key from Google AI Studio — step-by-step below.
- The companion code (free): the topic-09-coding-agent folder in our public repo. The demo run shown in this post was recorded on November 11, 2026, with exactly this code.
The whole machine, on one screen
Before any code, here is the map the whole build follows. Read it top to bottom:
- You hand the agent one task, written in plain English.
- The agent works in a loop: it runs a tool, looks at the result, and chooses the next tool — at most twelve rounds.
- It has exactly three tools:
read_file(read a file),run_tests(run the test suite), andwrite_file(change a file). The write tool's path runs through a gate, because writing is the one action that changes your code. - Every tool lands on your code and its tests — nothing else on your machine.
That is the entire design. Everything below is building this map, one piece at a time — and at the end, the agent runs on it for real.
Environment setup
1. Create the project folder and a virtual environment
A virtual environment (a "venv") is an isolated folder that holds one project's Python packages, so they never collide with the rest of your machine. Create one and step inside it:
python3.12 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
2. Install the two packages (pinned versions)
pip install google-genai==3.0.0 pytest==9.2.0
The versions are pinned — written with == — so your install matches this tutorial exactly, instead of drifting to whatever is newest.
3. Get your free Gemini API key (click by click)
- Go to Google AI Studio and sign in with a Google account.
- Open the API keys page (the key icon, "Get API key").
- Click Create API key, choose or create a project, and copy the key it shows you.
- Put the key in an environment variable — a setting your terminal session carries — named
GEMINI_API_KEY:
export GEMINI_API_KEY="paste-your-key-here" # Windows (PowerShell): $env:GEMINI_API_KEY="paste-your-key-here"
Never type the key into your code. Code gets shared, committed, and screenshotted; keys must not. The agent program reads the key from the environment only, and refuses to start without it. One honest warning about free keys: on Gemini's free tier, Google may use what you send to improve its products — so learn on demo code like ours, never on private code.
4. Verify your setup
Get the companion code (link above), open a terminal in the demo folder, and run the test suite yourself:
python -m pytest -q
You should see 1 failed, 3 passed. That failure is deliberate — it is the bug your agent is about to fix. If you see that line, your environment is ready.
Step 1 — Meet the patient: a cart, a test suite, and one planted bug
Our demo project is a tiny shopping cart in one small file, cart.py. Around it sits a test suite — a set of automatic checks. A test does something, then compares what happened with what should have happened. Here is the check that matters, as a worked example:
Add two notebooks to the cart. Add three more of the same. The cart should say five. Our cart says three — because when the same item arrives twice, Cart.add() replaces the quantity instead of adding to it:
def add(self, name, unit_price_cents, quantity=1):
# BUG (planted): this replaces the quantity instead of adding to it.
self._items[name] = [unit_price_cents, quantity]
The suite has four tests; exactly this one fails (test_add_same_item_twice_accumulates — the cart reports 3, the test expects 5). Adding a new item, totalling a mixed cart, and removing an item all pass. The bug is narrow: one method, one wrong idea about what "add" means. That one failure is the agent's job.
Step 2 — The skeleton: a brain, a connection, and a job description
The agent is one file, agent.py. Three things at the top define it:
-
A client — the connection to the Gemini API:
client = genai.Client()(it finds your key in the environment variable). -
The model —
MODEL = "gemini-3.8-flash". This model can do the one trick the whole build stands on: function calling. Function calling means the model never runs code itself. It asks our program to run a named tool — "read this file", "run those tests" — and reads the result that comes back. - The task, written in plain English and handed to the model as its instructions: "Run the test suite in this project. If a test fails, read the test and the code it tests, find the bug, and fix the source file so the whole suite passes. Do not edit the tests. When every test passes, stop and summarise what the bug was and what you changed."
Step 3 — Tool 1: read_file, and the guard inside it
Tool one does what it sounds like: the model names a file, the tool reads it and hands back the text. But look at the guard, because the guard is the lesson. Every path the model asks for is resolved — turned into its real, full location — and checked: if it lands outside the demo project folder, the request is refused.
def confine(path_text):
"""Resolve a model-supplied path and refuse anything outside the project."""
path = (PROJECT_DIR / path_text).resolve()
if not path.is_relative_to(PROJECT_DIR.resolve()):
return None
return path
The model can ask for anything. The code decides what it may touch. This pattern is called confinement, and every tool in this agent uses it. (One detail for later: reads are capped at 8,000 characters, so a huge file cannot flood the model.)
Step 4 — Tool 2: run_tests, the agent's eyes
When the model calls tool two, it runs the pytest suite inside the project folder and returns the tail of the output — the summary lines at the end, where the failures live:
def tool_run_tests():
proc = subprocess.run(
[sys.executable, "-m", "pytest", "-q"],
cwd=PROJECT_DIR, capture_output=True, text=True, timeout=120,
)
return {"exit_code": proc.returncode, "output": (proc.stdout + proc.stderr)[-3000:]}
That tail is how the agent sees the world: not a screenshot, not a guess — the same "1 failed, 3 passed" you saw in Step 1. Like read_file, this tool cannot change anything. Watching and reading are safe. The third tool is neither.
Step 5 — Tool 3: write_file, and the approval gate
Tool three is the dangerous one, so it is built differently. The model never writes. It proposes. The tool prints the complete proposed file in the terminal, where a human can read every line — and then the program stops and asks one question:
def tool_write_file(path, content):
"""THE GATE: the model only ever PROPOSES. A human decides."""
target = confine(path)
if target is None:
return {"error": f"refused: {path} is outside the project folder"}
if not target.parent.is_dir():
return {"error": f"refused: folder for {path} does not exist"}
print(f"\n--- The agent wants to write {path} ---")
print(content)
answer = input("Apply this change? [y/N] ").strip().lower()
if answer != "y":
print("--- Denied by the human. The file was NOT changed. ---")
return {"result": "DENIED by the human approver. Do not retry this write; "
"explain in your summary what you wanted to change."}
target.write_text(content)
print("--- Approved and written. ---")
return {"result": f"{path} written"}
That pause is the approval gate, and it is the heart of this build. Answer anything but "y", and the file stays byte-for-byte untouched — in our own testing, a denied write left the file's fingerprint (its SHA-256 hash) identical — and the model is told, in plain words, that a human refused and it must not retry. Answer "y", and only then does the file change. Every other tool in this agent can run all day. This one needs you.
Step 6 — The loop: ask, act, look, choose again
Around the tools sits the loop — the part that decides. The program sends the model the task and three tool declarations. A declaration is a small menu card: the tool's name, a plain-English description, and a strict schema — the exact arguments it accepts and their types. That menu is all the model ever sees of your code; the functions themselves stay yours.
Then the cycle repeats: the model replies with a tool call (or with words). A call runs here, in our program; its result travels back, and the model picks the next move. Ask, act, look, choose again — that cycle is all the word "loop" means, and it is the entire engine of every agent you will ever meet. Two safety rails are built in:
-
A step cap of 12 (
MAX_STEPS): after twelve model turns the loop stops, whatever the model believes — a confused model costs you twelve turns, never forever. - Words mean "done": when the model answers in words instead of a tool call, the job is finished, and it summarises.
One wrinkle, learned the hard way (it is also in the code's comments): tool results travel back to the model labelled with role "user". Label them "tool" — the obvious word — and this API refuses them with a 400 error. We hit that exact wall while building this tutorial; the shipped code carries the fix.
Step 7 — The real run
Now the agent runs — for real, exactly as it happened when we recorded it (November 11, 2026). Five steps:
-
run_tests— the agent's first move is to run the suite on its own. It sees the failure itself: 1 failed, 3 passed. -
read_filetest_cart.py — it reads the failing test. -
read_filecart.py — then the code the test checks. -
write_filecart.py → THE GATE — it proposes the complete fixed file and stops. The proposal is the whole file with one idea changed: if the item is already in the cart, add to its quantity —self._items[name][1] += quantity. (The[1]is the quantity slot: each cart entry is stored as a pair,[unit_price_cents, quantity], so slot 1 is the quantity.) The operator read the proposal — it touched only theaddmethod — and approved. -
run_tests— the write landed, and on its own the agent ran the suite again: 4 passed. Then it summarised, in its own words, exactly what the bug was and what it changed.
Found, diagnosed, proposed, approved, fixed, proven. (We independently re-ran the suite on the agent-fixed file afterwards: 4 passed — then put the planted bug back, so the repo ships the exercise, not the answer.)
Step 8 — The bill: what one fix costs
You pay for the text the model reads and writes, counted in tokens — pieces of text, roughly word-sized. The agent counts them as it runs, and prints the total at the end. This run:
- 7,017 tokens in — everything the model read (the task, the files, the test output).
- 1,202 tokens out — everything it wrote, including its thinking tokens, because the price list bills those as output too.
The prices, verified on Google's own pricing page: $0.75 per million input tokens and $3.75 per million output tokens for gemini-3.8-flash (standard tier, at those rates through December 31, 2026). The maths:
in: 7,017 × $0.75 / 1M = $0.0053
out: 1,202 × $3.75 / 1M = $0.0045
total = $0.0098
The whole fix cost less than one cent — and on a free AI Studio key, the same run costs $0 (with the free-tier data warning from the setup section attached). The lesson is not that it is cheap. It is that the cost is knowable, per run, from numbers the run itself prints.
Step 9 — The guardrails, named
Step back and name what keeps this agent safe, because these four are the difference between a tool and a liability:
- The gate — no write is ever ungated; a human reads the exact change first.
- Confinement — every tool is locked to one project folder, enforced by the code, not requested in a prompt.
- The step cap — twelve turns, then it stops, whatever it believes.
- What it does not have — no shell tool, so it cannot run arbitrary commands; no network tool, so it cannot send your code anywhere.
These are not our inventions: the serious tools work the same way — Claude Code, for instance, confines its writes and asks before the dangerous ones, and well-built agent products route risky actions to a human before they execute. The principle to keep: prompts are suggestions; code is enforcement. Build the enforcement.
Step 10 — The honest verdict
What it nailed: the diagnosis was exact, the fix was the smallest change that could work, and it stopped the moment the suite went green instead of polishing further.
Where it wobbled — and this is the real lesson: it rewrote the whole file to change three lines in one method (whole-file writes are simple, but blunt), and the file it saved still carries its header comment claiming "a bug lives here on purpose" — which stopped being true the moment the fix landed. A human reading the proposal at the gate catches that. An auto-approver ships it. That is why the gate exists.
The limits, plainly: this is a teaching agent, for small, well-tested code. A full tool like Claude Code brings a terminal, a map of your whole codebase, and years of hardening this one file does not have. Build one anyway — because once you have written the loop, the gate, and the confinement yourself, you understand what every agent product is actually doing under the hood. That understanding is the real deliverable.
Errors you may hit
- "Set GEMINI_API_KEY first" — the key variable is missing in this terminal. Set it (setup step 3) in the same terminal you launch the agent from, then run again.
-
A 400 error about the role "tool" — if you typed the loop yourself and sent tool results back with role
"tool", this API refuses them. Send them as role"user", like the shipped code does (Step 6). - The model repeats the same tool call — the step cap ends the loop at 12. Read the printed transcript; the fix is usually a clearer task sentence (say exactly what "done" looks like).
- A patch that breaks a different test — the suite goes red again and the loop continues; the gate hands you a second decision. Never approve a fix you have not read.
- pytest: command not found / module not found — your virtual environment is not active, or you are in the wrong folder. Activate the venv and run from the project folder.
The encore: the agent files its own report (issue #16)
After the fix, this same agent drafted a report of its own run — the bug, the change, the result — and a human reviewed the exact draft at a gate and approved it. The report was then posted through GitHub's official MCP server (MCP is the standard way agents connect to outside tools) as issue #16 in the companion repo — a public audit trail of everything the agent did. It is the same pattern as the write gate, one level up: the agent proposes, the human decides, and only then does anything leave the machine. The companion Short video shows this beat on screen.
FAQ
Do I need to pay for a Gemini API key?
No. A free AI Studio key runs this whole tutorial, and the demo run costs $0 on it. Just keep the free-tier warning in mind: do not feed the agent private code on a free key.
Why build an agent by hand instead of using a ready-made tool?
Understanding. A ready-made tool hides the loop, the tools, and the gates. Once you have written all three yourself — about 140 lines — every agent product you meet afterwards reads as variations on a machine you already know.
What stops the agent from going rogue?
Code, not promises: it can only see one folder (confinement), it cannot write without a human yes (the gate), it must stop after twelve steps (the cap), and it has no shell or network tool at all.
Can I give it more tools?
Yes — that is the natural next step. Add one tool at a time, keep each one confined, and gate anything that changes state. The moment a new tool can change something, it goes behind the same approval pattern as write_file.
Sources
- Gemini API pricing (rate card verified November 7, 2026): ai.google.dev/gemini-api/docs/pricing
- google-genai SDK documentation: googleapis.github.io/python-genai
- GitHub MCP server (remote endpoint, toolsets): github.com/github/github-mcp-server
- The run itself: demo transcript and companion code, recorded November 11, 2026 — topic-09-coding-agent and issue #16.
Get the code
The complete, free companion code — the agent, the demo project with the planted bug, and the test suite — lives in the topic-09-coding-agent folder of our public repo, with setup instructions in its README. Run the suite first (see the failure), then run the agent — and when the gate asks, try denying the first proposal on purpose, just to watch what the agent does with a refusal.
Disclosure: Visual Studio Learn is reader-supported. Some links may be affiliate links, which means the channel may earn a small commission at no extra cost to you. Only tools actually used in the tutorials are ever linked, and affiliate relationships never change a verdict.
Enjoying these tutorials?
Get new Visual Studio Learn posts by email — free, no spam:
Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.








![The approval gate live in the terminal, asking Apply this change? [y/N]](https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fhnhpxwgx2wmbjbtbegba.png)




