Skip to content

Build Your Own AI Coding Agent in Python (How Cursor Works)

Build your own AI coding agent from scratch in plain Python, with no framework and the free Gemini API. Learn the three parts of every agent, why the model never runs code itself, and the simple loop behind tools like Cursor and Claude Code.

Mahnoor 7 min read 12-item prompt pack

If you are learning to code, you are probably already using AI tools like Cursor or Claude Code. You tell them what is broken, and they open your files, run your code and fix it by themselves. It feels like something really complicated is happening inside. In this lesson you will build your own AI coding agent in Python, from scratch, with no framework, and you will see that underneath it is basically one simple loop. It is completely free: we use the Gemini free tier and about 80 lines of plain Python.

By the end you will have an agent that you can give one sentence, like "marks.py crashes, fix it", and it will look at your folder, read the code and the data, run the file, read the error, write a fix and run it again until it works.

Chatbot vs coding agent

Think about a student who is stuck on a coding assignment. The first student messages a friend, pastes the error, and the friend says what to change. The student copies the fix, runs it, gets a new error, and pastes that back again. A normal chatbot works exactly like that friend, because it can only tell you what to do.

The second student hands the friend their laptop. The friend opens the files, runs the code, reads the error, fixes it and keeps going until it works. That second friend is a coding agent. (If you want the bigger picture first, watch our Chatbot vs LLM vs AI Agent lesson.)

Every agent has three parts

  • The model (Gemini, GPT, Claude). This is the brain. On its own it can only write text.

  • Tools. These are just normal Python functions you write, like "run this file" or "read this file". They are its hands.

  • A loop that keeps asking the model what it wants to do next, until the job is done.

The part most people get wrong: the model never runs any code by itself. When it wants to run marks.py, it sends back a short message saying which tool it wants and with which input. Your Python code reads that message, runs the tool, and sends the result back to the model. The model decides, your code does the work.

Step 1: setup

mkdir coding-agent
cd coding-agent
python -m venv .venv
.venv\Scripts\activate
pip install google-genai python-dotenv

Create a free Gemini API key in Google AI Studio (no credit card needed, see our step-by-step guide to getting a free Gemini API key) and put it in a file called .env:

GEMINI_API_KEY=paste-your-key-here

Never put the key directly in your code, and add .env to your .gitignore so it never ends up on GitHub.

We also need something to fix: a folder called project with marks.py, which reads students' marks from marks.csv and prints each average and grade. It is broken on purpose (a missing bracket, plus two hidden problems in the data).

Step 2: talk to the model once

from dotenv import load_dotenv
from google import genai

load_dotenv()
client = genai.Client()
MODEL = "gemini-3.5-flash-lite"

response = client.models.generate_content(
    model=MODEL,
    contents="Run my file marks.py and tell me what it prints.",
)
print(response.text)

The model replies that it does not have access to your files and offers to run the code "in its mental interpreter", which means it is going to guess. That is a brain with no hands.

Step 3: the first tool, run_python

import os
import subprocess
import sys

FOLDER = "project"  # the agent can only touch files in this folder


def run_python(filename):
    result = subprocess.run([sys.executable, os.path.basename(filename)], cwd=FOLDER,
                            capture_output=True, text=True, timeout=10)
    return (result.stdout + result.stderr)[-2000:] or "Ran with no output."

os.path.basename keeps only the file name, so the agent cannot reach outside the project folder, and timeout=10 stops any run after ten seconds. We return the errors too, because an error message is exactly what the model needs to fix the code.

Step 4: the menu (tool descriptions)

The model cannot see your Python code, so you describe each tool like an item on a menu: a name that matches the function, a description, and its parameters. Pass the menu in a config, and print response.function_calls instead of the text. The model does not run anything; it asks you to call run_python with marks.py. Running it is your job. This is called function calling, and we explain it with a small Python example in What is function calling?

Step 5: the loop

def run_agent(task, max_steps=15):
    messages = [types.Content(role="user", parts=[types.Part(text=task)])]

    for step in range(1, max_steps + 1):
        response = client.models.generate_content(model=MODEL, contents=messages, config=config)
        messages.append(response.candidates[0].content)

        if not response.function_calls:  # no tool needed: this is the final answer
            return response.text

        results = []
        for call in response.function_calls:
            print(f"Step {step}: {call.name} {call.args.get('filename', '')}")
            result = TOOLS[call.name](**call.args)
            results.append(types.Part.from_function_response(name=call.name, response={"result": result}))
        messages.append(types.Content(role="user", parts=results))

    return "Stopped: the agent took too many steps."

The messages list is the agent's memory: the model starts from zero on every call, so we send the whole list every time. max_steps is the limit, so a confused agent stops after fifteen rounds instead of running forever. These lines are the same loop every agent framework runs underneath.

Step 6: more hands and the full run

Add three small tools, list_files, read_file and write_file (all fenced into the project folder), plus a system instruction: run the file again after every change, keep going until there are no errors, and change as little as possible. Then run it:

What should the agent do? marks.py crashes when I run it. Fix it, and if a mark is missing, just skip it.
Step 1: list_files
Step 2: read_file marks.py
Step 3: read_file marks.csv
Step 4: run_python marks.py
   -> SyntaxError: '(' was never closed
Step 5: write_file marks.py
Step 6: run_python marks.py
   -> Mia: 91.7 (A)

Nobody told it to read the data in step 3, but because it did, it also fixed two problems that had not crashed yet: Jake was "absent" for physics (turning "absent" into a number crashes) and Noah has no marks at all (dividing by zero crashes).

Why the memory list matters

If you remove the two messages.append lines, the agent calls list_files fifteen times and stops, because every round it only sees your first message and thinks it is just starting. Those fifteen calls also use up the free limit for that minute. If you see a 429 error, wait a minute; a 503 means the free model is busy, so try again. We explain both in our Gemini API 429 and 503 errors guide.

One honest safety note

This agent runs code that an AI wrote. That is why it only touches the project folder and every run stops after ten seconds. Never point it at your whole computer. Cursor and Claude Code add a lot on top of this, but underneath it is the same loop. For more ways to code with AI, see our 7 GitHub repos for AI coding.

Prompt pack

Every prompt from this lesson

Add a new tool to your agent
Here is my AI coding agent in Python (google-genai, manual tool-calling loop):
[paste agent.py]

I want to add a new tool: [describe it, e.g. 'count the lines in a file' or 'search the project for a word'].
Give me:
1. The Python function (keep it inside the FOLDER, use os.path.basename like the other tools).
2. The tool declaration for the menu (name, a clear description, parameters).
3. The one line to add to the TOOLS dictionary.
Then give me one task sentence I can type to test that the agent actually uses the new tool.
Keep it beginner friendly and explain each new line in one short sentence.
Explain the agent loop line by line
Explain this agent loop to me like I am a beginner, one line at a time:
[paste the run_agent function]

For each line, tell me in one sentence what it does and why it is needed.
Then answer: what would break if I removed the two messages.append lines, and what is max_steps protecting me from?
Finish with a 3-question quiz to check I understood it, and wait for my answers.
Link Get your free Gemini API key (Google AI Studio) (opens in new tab)

9 more items in the full pack

Free. Sign in once and every prompt pack on Morow Global unlocks.

Sign in free to unlock

Already a member? Sign in

FAQ

Do I need LangChain or another framework to build an AI agent?

No. An agent is a model, a few Python functions as tools, and a loop that keeps asking the model what to do next. This lesson builds it in about 80 lines of plain Python with the google-genai package.

Is it free?

Yes. It uses the Gemini free tier, and you can create a key in Google AI Studio without a credit card. The free tier allows around 15 requests a minute, which is plenty for this project.

Does the AI run my code by itself?

No. The model only sends back a short message saying which tool it wants and with which input. Your Python code runs the tool and sends the result back. The model decides, your code does the work.

Why does the agent need a messages list and max_steps?

The model remembers nothing between calls, so the messages list is its memory and is sent every time. max_steps is the limit, so if something goes wrong it stops after 15 rounds instead of running forever and using up your free quota.

Is it safe to run an agent that writes and runs code?

Only with limits. This agent can only touch files inside one project folder and every run stops after 10 seconds. Never point it at your whole computer, and add a human approval step before writes for anything important.

#beginners #Gemini #AI agents #Tool calling #Python #Coding agent