Ravindra BagaleCourses & study guides Track your progress
AI CODING ASSISTANTS · CHAPTER 5 · WORKFLOWS

How to Debug Code with AI

Stuck on an error? Paste the failing test and the short stack trace — not the whole project. The AI suggests a fix; you prove it by re-running the test.

In short: reproduce → collect error lines → ask for one hypothesis → apply a small fix → re-run tests. Never paste secrets or .env files into the chat.

Why AI helps debugging

WHY

Reading a long stack trace is slow when you are tired. An AI is good at pattern-matching common mistakes (wrong type, off-by-one, float money math). You stay in charge: it guesses, you verify.

What to give the AI

WHAT
  • Failing test name: so it knows the expected behaviour.
  • Error / stack lines: the exception type and the 5–15 lines that point at your file.
  • The small function: not the entire repository.
  • What you already tried: one sentence, to avoid looping the same bad fix.

How debugging flows

1 · Reproduce failing test or minimal script 2 · Copy error lines not the whole log 3 · Ask for 1 fix hypothesis + patch 4 · Apply + re-run tests decide 5 · New chat if stuck fresh context

Example: GST total was wrong

BUG REPORT PROMPT (COPY)

Language: Python 3.12. Failing test: test_rounds_half_up. Error: AssertionError — expected Decimal('117.99'), got 117.9882…. Function below uses float. Fix money math with Decimal, keep the same API, return code only.

buggy idea (do not ship)
# Common AI mistake: float money math
def gst_total(price, rate_percent):
    return round(price + price * rate_percent / 100, 2)
# 99.99 * 0.18 in float can surprise you — use Decimal for money.
gst.py (fixed, tested here)
"""Indian GST on a price. Rate is percent, e.g. 18 for 18%."""
from decimal import Decimal, ROUND_HALF_UP


def gst_total(price: str | Decimal, rate_percent: str | Decimal) -> Decimal:
    p = Decimal(str(price))
    r = Decimal(str(rate_percent))
    if p < 0 or r < 0:
        raise ValueError("price and rate must be >= 0")
    tax = (p * r / Decimal("100")).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
    return (p + tax).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
test_gst.py
from decimal import Decimal
import pytest
from gst import gst_total

def test_18_percent():
    assert gst_total("100", "18") == Decimal("118.00")

def test_rounds_half_up():
    assert gst_total("99.99", "18") == Decimal("117.99")

def test_zero_rate():
    assert gst_total("50", "0") == Decimal("50.00")

def test_negative_raises():
    with pytest.raises(ValueError):
        gst_total("-1", "18")
cd code/debug
python3 -m pytest -q
# -> 4 passed

How to debug step by step

HOW
  1. Make it fail the same way twice with a test or a 5-line script.
  2. Copy only the useful error lines (file, line, exception). Drop huge HTML dumps.
  3. Ask for one hypothesis, not five random rewrites.
  4. Apply the smallest patch. Reject drive-by refactors.
  5. Re-run the same test. If it still fails, paste the new error only.
  6. Start a new chat when the thread is full of wrong guesses.

Where to debug in real tools

  1. VS Code + Copilot / Claude Code / Cursor: select the function, open chat or inline chat, paste the error.
  2. Agent mode: allow it to run the test command; keep approval on for shell.
  3. Terminal CLI (Claude Code): run from the project root so it can see the failing test file.
  4. Settings: put the test command in project rules so you do not retype it.
DoDon't
Paste failing test + short stackPaste .env, tokens, or full production logs
One fix round at a time“Rewrite the module from scratch” on first try
Re-run the exact same testAssume the chat “looks correct”
Rule: AI can invent a confident wrong cause. If the stack points at line 40, do not accept a rewrite of an unrelated file.

Try this yourself: debug a study-time parser with AI

Hello friends. In this practice we will run a small buggy function, read the real error, give the AI a short and clear prompt, and then prove the fix with tests. The study log here is fictional practice data. Never paste passwords, API keys or private customer data into an AI chat.

Ravindra Bagale's Tip

Paste the last line of the error and the small function, not the whole project. The AI gives a better answer when it sees exactly what failed.

Environment (tested): this exercise was run on 6 November 2026 with Python 3.13.5 and pytest 9.2.0. Use Python 3.10 or newer. Older Python versions print the traceback with fewer ^^^ marker lines, but the last line with the error type and message is the same.

Your task: a fictional study-log app stores study time as text such as 1h 30m, 2h or 45m. An AI wrote parse_duration(text) to turn that text into total minutes, but it crashes on 45m and 2h. Reproduce the crash, ask an AI assistant for a fix with the prompt below, and prove the fix with the tests. The finished function must return 90 for "1h 30m", 45 for "45m", 120 for "2h", ignore extra spaces, and raise ValueError for text such as "ninety".

Buggy starter — save this exact text as duration.py

duration.py
"""Buggy starter for the debug exercise (fictional practice study log)."""


def parse_duration(text: str) -> int:
    """Convert a duration like '1h 30m' into total minutes."""
    hours, minutes = text.split(" ")
    return int(hours[:-1]) * 60 + int(minutes[:-1])

Tests — save this as test_duration.py in the same folder

test_duration.py
"""Tests for the fictional parse_duration practice."""
import pytest

from duration import parse_duration


def test_hours_and_minutes():
    assert parse_duration("1h 30m") == 90


def test_minutes_only():
    assert parse_duration("45m") == 45


def test_hours_only():
    assert parse_duration("2h") == 120


def test_extra_spaces():
    assert parse_duration("  1h   5m ") == 65


def test_bad_input_raises():
    with pytest.raises(ValueError):
        parse_duration("ninety")

Prompt to give your AI assistant (Copilot Chat, ChatGPT, Claude, Gemini or any similar tool):

prompt
I am practising debugging in Python 3. This function should turn a study time
such as "1h 30m", "2h" or "45m" into total minutes.

Here is my function from duration.py:
(paste the whole duration.py file here)

When I run parse_duration("45m") I get this error:
ValueError: not enough values to unpack (expected 2, got 1)

Please explain the most likely cause in two or three sentences.
Then give the smallest fix. Keep the name parse_duration and its one text argument.
It must accept "1h 30m", "2h", "45m" and extra spaces.
It must raise ValueError for text that is not like "2h" or "45m".
Do not add any new library.
HOW
  1. Create a project folder and open a terminal inside it.
  2. Create a virtual environment: on macOS or Linux run python3 -m venv .venv. On Windows run py -3 -m venv .venv.
  3. Activate it: on macOS or Linux run source .venv/bin/activate. In Windows Command Prompt run .venv\Scripts\activate.bat, and in Windows PowerShell run .venv\Scripts\Activate.ps1.
  4. Install pytest inside the virtual environment: python -m pip install pytest.
  5. Save the two files above as duration.py and test_duration.py in the same folder.
  6. Reproduce the bug by running python -c "from duration import parse_duration; print(parse_duration('45m'))". You should see the ValueError shown below.
  7. Run the tests before the fix with python -m pytest -q test_duration.py. You should see 3 failed and 2 passed.
  8. Send the prompt to your AI assistant and paste your real duration.py where the prompt says so.
  9. Read the explanation first. Check that the cause matches the error line: split(" ") returns only one part for 45m, so the two names on the left cannot both be filled.
  10. Apply the smallest fix to duration.py and save the file. Do not edit the tests to make them pass.
  11. Run the same test command again and confirm that all 5 tests pass.

Real output before the fix (from Python 3.13.5; the folder path on your computer will be different):

terminal
Traceback (most recent call last):
  ...
  File ".../duration.py", line 6, in parse_duration
    hours, minutes = text.split(" ")
    ^^^^^^^^^^^^^^
ValueError: not enough values to unpack (expected 2, got 1)
terminal
python -m pytest -q test_duration.py
...
FAILED test_duration.py::test_minutes_only - ValueError: not enough values to...
FAILED test_duration.py::test_hours_only - ValueError: not enough values to u...
FAILED test_duration.py::test_extra_spaces - ValueError: too many values to u...
3 failed, 2 passed in 0.01s

Real output after the fix (the time in seconds can be slightly different on your computer):

terminal
python -m pytest -q test_duration.py
.....                                                                    [100%]
5 passed in 0.00s
Optional solution for duration.py (try it yourself first)

Your AI assistant may give a different answer that is also correct. Any version is fine if all 5 tests pass and the code is easy to read.

duration.py
"""Fixed version for the debug exercise (fictional practice study log)."""


def parse_duration(text: str) -> int:
    """Convert '1h 30m', '2h' or '45m' into total minutes.

    Raise ValueError for empty text or a part that is not like '2h' or '45m'.
    """
    parts = text.split()
    if not parts:
        raise ValueError("empty duration")
    total = 0
    for part in parts:
        number, unit = part[:-1], part[-1:]
        if not number.isdigit() or unit not in ("h", "m"):
            raise ValueError(f"bad duration part: {part!r}")
        total += int(number) * 60 if unit == "h" else int(number)
    return total

Troubleshooting this exercise

HOW
  1. Error: ModuleNotFoundError: No module named 'duration'. Fix: run the command from the same folder as the file, and check that the file is named exactly duration.py.
  2. Error: No module named pytest. Fix: activate the virtual environment first, then run python -m pip install pytest again.
  3. Error: test_extra_spaces fails with too many values to unpack. Fix: use text.split() with no argument, because it splits on any run of spaces and ignores spaces at the start and end.
  4. Problem: the AI fix returns a number for "ninety" instead of raising an error. Fix: tell the AI that every part must be digits followed by h or m, and that anything else must raise ValueError.
  5. Problem: the AI keeps guessing and rewriting unrelated code. Fix: start a new chat and send only the latest error line, the function and the failing test name.

Practice cards: English and spoken Marathi

Each card below explains one idea on its own, so you can save or revise a single card without reading the whole chapter.

PRACTICE CARDAI Coding

Reproduce before you ask

Run the failing code yourself first, so you can paste the exact error message into the AI chat.
A real error line helps the AI find the cause much faster than a vague description such as "it does not work".
Ravindra Bagale · ravindrabagale.com/ai-coding
PRACTICE CARDAI Coding

Prove the fix with the same test

After you apply the AI fix, run the same test command again without changing the tests.
If the tests still fail, paste only the new error and ask for one more small change.
Ravindra Bagale · ravindrabagale.com/ai-coding
सराव कार्डमराठी

आधी error स्वतः बघा

AI ला विचारण्याआधी code स्वतः चालवा, म्हणजे खरा error message तुम्हाला copy करता येईल.
"चालत नाही" असं लिहिण्यापेक्षा error ची खरी line दिली की AI ला कारण लवकर सापडतं.
Ravindra Bagale · ravindrabagale.com/ai-coding
सराव कार्डमराठी

fix झाला का, tests सांगतात

AI ने दिलेला fix लावल्यावर तीच test command पुन्हा चालवा, आणि tests बदलू नका.
Tests अजून fail होत असतील, तर फक्त नवीन error paste करा आणि एक छोटा बदल मागा.
Ravindra Bagale · ravindrabagale.com/ai-coding
Practice label: every name, number and time in this exercise is fictional teaching data. It is not about a real person, account or company. Passing these tests proves only the cases listed in the tests, not every possible input.

Quick quiz

1. What is the minimum to paste?

Failing test (or expected behaviour) plus the short error/stack lines.

2. Why not paste the whole repo?

Noise, cost, and risk of leaking secrets.

3. How do you know the fix worked?

The same failing test now passes.

4. What if the chat keeps guessing wrong?

Start a new chat with only the latest error and the small function.

Save tokens and money

SMART AI USE

Send the error and the function, not megabytes of logs. One hypothesis per turn. Prefer inline chat for a single function; save agents for multi-file bugs.

Save these cards

INTERVIEW CARDAI Coding

How do you debug with AI?

Reproduce, paste short error + function, ask one fix.
Prove with the same test; never paste secrets.
Ravindra Bagale · ravindrabagale.com/ai-coding
COMPARISON CARDAI Coding

Guessing vs verifying

Guess: chat explains a possible cause.
Verify: re-run the failing test after a small patch.
Ravindra Bagale · ravindrabagale.com/ai-coding
REVISION CARDAI Coding

Debug in 3

Reproduce.
Paste error + small code.
Re-run tests.
Ravindra Bagale · ravindrabagale.com/ai-coding