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
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
- 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
Example: GST total was wrong
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.
# 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.pyfrom 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 passedHow to debug step by step
- Make it fail the same way twice with a test or a 5-line script.
- Copy only the useful error lines (file, line, exception). Drop huge HTML dumps.
- Ask for one hypothesis, not five random rewrites.
- Apply the smallest patch. Reject drive-by refactors.
- Re-run the same test. If it still fails, paste the new error only.
- Start a new chat when the thread is full of wrong guesses.
Where to debug in real tools
- VS Code + Copilot / Claude Code / Cursor: select the function, open chat or inline chat, paste the error.
- Agent mode: allow it to run the test command; keep approval on for shell.
- Terminal CLI (Claude Code): run from the project root so it can see the failing test file.
- Settings: put the test command in project rules so you do not retype it.
| Do | Don't |
|---|---|
| Paste failing test + short stack | Paste .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 test | Assume the chat “looks correct” |
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.
नमस्कार मित्रांनो. या practice मध्ये आपण एक छोटं buggy function चालवू, खरा error वाचू, AI ला छोटा आणि स्पष्ट prompt देऊ, आणि मग tests चालवून fix बरोबर आहे हे बघू. इथला study log फक्त practice साठी बनवलेला आहे. AI chat मध्ये password, API key किंवा customer ची खाजगी माहिती कधीच टाकू नका.
नमस्कार दोस्तों. इस practice में हम एक छोटा buggy function चलाएंगे, असली error पढ़ेंगे, AI को छोटा और साफ prompt देंगे, और फिर tests चलाकर देखेंगे कि fix सही है. यहाँ का study log सिर्फ practice के लिए बनाया गया है. AI chat में password, API key या customer की निजी जानकारी कभी मत डालना.
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.
Ravindra Bagale's Tip – मराठी
पूर्ण project नको, फक्त error ची शेवटची line आणि ते छोटं function paste करा. नक्की काय fail झालं ते दिसलं की AI चं उत्तर जास्त चांगलं येतं.
Ravindra Bagale's Tip – हिंदी
पूरा project नहीं, सिर्फ error की आखिरी line और वह छोटा function paste करो. ठीक क्या fail हुआ यह दिखे तो AI का जवाब ज़्यादा अच्छा आता है.
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
"""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
"""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):
promptI 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.
- Create a project folder and open a terminal inside it.
- Create a virtual environment: on macOS or Linux run
python3 -m venv .venv. On Windows runpy -3 -m venv .venv. - 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. - Install pytest inside the virtual environment:
python -m pip install pytest. - Save the two files above as
duration.pyandtest_duration.pyin the same folder. - Reproduce the bug by running
python -c "from duration import parse_duration; print(parse_duration('45m'))". You should see theValueErrorshown below. - Run the tests before the fix with
python -m pytest -q test_duration.py. You should see 3 failed and 2 passed. - Send the prompt to your AI assistant and paste your real
duration.pywhere the prompt says so. - Read the explanation first. Check that the cause matches the error line:
split(" ")returns only one part for45m, so the two names on the left cannot both be filled. - Apply the smallest fix to
duration.pyand save the file. Do not edit the tests to make them pass. - 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):
terminalTraceback (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)
terminalpython -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):
terminalpython -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
- Error:
ModuleNotFoundError: No module named 'duration'. Fix: run the command from the same folder as the file, and check that the file is named exactlyduration.py. - Error:
No module named pytest. Fix: activate the virtual environment first, then runpython -m pip install pytestagain. - Error:
test_extra_spacesfails withtoo many values to unpack. Fix: usetext.split()with no argument, because it splits on any run of spaces and ignores spaces at the start and end. - 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 byhorm, and that anything else must raiseValueError. - 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.
Reproduce before you ask
Prove the fix with the same test
आधी error स्वतः बघा
fix झाला का, tests सांगतात
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
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.