Reading a Stack Trace With AI: Root Cause Before the Fix

A programmer working at a desktop computer, representing the process of debugging code

To debug a stack trace with AI, paste the complete trace (every frame and every “Caused by” section), the source of the frame where your own code first appears, and the input or state that triggered it, then ask the model to explain the trace frame by frame and name the root-cause frame before it proposes any fix. That order matters: the line where an exception surfaces is often not the line that caused it, and a model asked to “fix this error” will usually patch the symptom. The prompts below are built around that sequence and work for Python, Java and JavaScript traces.

How to read a stack trace before you prompt

A stack trace is the list of function calls that were active when an exception was raised, one line (a “frame”) per call, usually with file name and line number. Each frame was called by the one next to it. Knowing which direction the list runs in your language is the first thing to get right, because it decides where you start reading.

LanguageWhere the error was raisedChained / wrapped errorsThings to know
PythonAt the bottom. The header says Traceback (most recent call last).Earlier exception printed first, then “The above exception was the direct cause of the following exception” (explicit raise ... from) or “During handling of the above exception, another exception occurred” (implicit).Since Python 3.11, notes added with add_note() appear after the message.
JavaAt the top of each block.Each wrapped cause appears below in a Caused by: block.... n more means the last n frames repeat the enclosing trace. Suppressed: entries often come from try-with-resources close failures.
JavaScriptAt the top.Depends on how the code attaches a cause; not part of the stack string format itself.Error.stack is not standardized; V8, SpiderMonkey and JavaScriptCore format lines differently.

The Python details come from the official Python errors and exceptions tutorial, the Java format from the Throwable API documentation, and the JavaScript notes from MDN’s Error.stack page.

Two practical consequences. First, in a chained trace the most useful information is often in the original exception, which in Python is printed first and in Java is the last Caused by:. Developers who read only the final line miss it. Second, the frame you care about is usually the first one that belongs to your code, not the topmost library frame. Library frames still matter: they show what your code passed in.

What to paste, and what not to

The model can only reason about what you give it, so the quality of the answer is mostly decided by the paste. Include:

  1. The full trace, unedited. Every frame, every “Caused by”, every “During handling” section. Trimming to “the important part” is how the root cause gets lost.
  2. The source of the first frame in your code, plus its caller if the bad value came from there. Include line numbers or mark the failing line with a comment, because pasted code loses its original numbering.
  3. The input or state. The request payload, the record ID, the config value, the environment. “This only fails for orders with a discount code” is often worth more than another 50 lines of code.
  4. Versions. Language runtime, framework and the library that appears in the trace. Behavior and messages differ between versions.
  5. What changed. A deploy, a dependency bump, a data migration. If nothing changed and it started failing, say so.

Leave out, or redact: API keys, tokens and connection strings (they often appear in traces from HTTP and database clients), customer personal data in payloads, and internal hostnames if your policy requires it. Replace them with placeholders such as <REDACTED_TOKEN> so the structure stays readable. Check your organization’s rules on which AI tools are approved for proprietary code.

The core prompt: explain first, fix second

This is the prompt to reach for first. It forces the model to commit to an explanation you can check before it writes any code.

You are helping me debug a production error. Do not propose a fix yet.

## Environment
Language/runtime: [e.g. Python 3.12]
Framework/libraries in the trace: [e.g. Django 5.1, psycopg 3.2]
What changed recently: [deploy / dependency bump / nothing known]

## Full stack trace (unedited)
```
[paste]
```

## Source of the first frame in my code (failing line marked with # <-- HERE)
```
[paste function, plus its caller if relevant]
```

## Input / state when it failed
[payload, record id, config, how often it happens]

## What I want
1. Walk the trace in execution order and explain each frame in one line.
   If there are chained exceptions, explain how they relate.
2. Identify the frame most likely to contain the ROOT CAUSE (which may be
   different from where the exception was raised) and explain why.
3. State the exact condition (value, type, state) that makes this line
   raise this exception.
4. List what you cannot see that would confirm or rule out your theory,
   and how I can check it (a log line, a query, a REPL command).
Mark anything you are guessing as a guess.

Why each part exists:

  • “Do not propose a fix yet” blocks the most common bad outcome: a try/except or a null check that makes the error disappear while the bad data keeps flowing.
  • “In execution order” removes the top-down versus bottom-up confusion between languages.
  • Step 3 turns a vague explanation into a testable statement. “order.customer is None when the order was created by the import job” can be checked in a minute.
  • Step 4 makes the model tell you what evidence is missing instead of filling the gap with a confident story. The general technique is covered in reducing AI hallucinations with better prompts.

Follow-up prompts for specific situations

Once the explanation holds up, use the follow-up that matches your situation.

The minimal root-cause fix

Your explanation is confirmed: [one line of what you verified].
Propose the smallest change that fixes the root cause.
Constraints:
- Do not catch and silence the exception.
- If invalid data should be rejected earlier, show where.
- Show a unit test that fails before the fix and passes after.
- List any other callers that could hit the same condition.

The failing test is the proof that the fix addresses the cause you identified. For more on getting good tests out of a model, see AI prompts for writing unit tests.

Intermittent errors

This trace appears in roughly [N] of [M] requests and I cannot reproduce
it locally. [Paste trace + code + what differs between failing and
passing requests if known.]
List the likely causes of a NON-deterministic failure at this line,
ranked, considering: concurrency/shared state, ordering assumptions,
timeouts and retries, caching, external services, and data that only
exists in production. For each, give one log line or metric that would
confirm it.

Asking for a confirming signal per hypothesis turns a list of guesses into a plan. If the logs you have are not enough to confirm anything, prompts for better error messages and log output help you add the right ones.

A trace that is all framework frames

None of these frames are in my code; they are all in [framework].
Based on the frames and the exception, tell me which framework feature
was executing (e.g. template rendering, ORM query, middleware,
serializer), which of MY files or settings that feature reads, and
what value in them would cause this exception.

Framework-only traces usually mean your code configured something rather than called something: a template, a route, a model field, a serializer. The model can map framework internals back to the user-facing feature faster than you can read the library source.

Worked example: a Python traceback with chained exceptions

Here is an illustrative trace from a fictional invoicing service. File names and values are invented for the example.

Traceback (most recent call last):
  File "/app/billing/rates.py", line 18, in get_rate
    return RATES[currency]
           ~~~~~^^^^^^^^^^
KeyError: 'usd'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/app/api/views.py", line 42, in create_invoice
    total = invoice_total(payload["items"], payload["currency"])
  File "/app/billing/totals.py", line 11, in invoice_total
    rate = get_rate(currency)
  File "/app/billing/rates.py", line 20, in get_rate
    raise ValueError(f"Unsupported currency: {currency}") from e
ValueError: Unsupported currency: usd

A developer reading only the last line sees “Unsupported currency: usd” and may add 'usd' to the rates table. A model given just that line and asked for a fix will often suggest the same, or wrap the call in a try/except that returns a default rate.

With the core prompt, the analysis should look more like this (written here as an example of a good answer, not a captured output):

  1. Execution order: create_invoice passes payload["currency"] to invoice_total, which calls get_rate; the dictionary lookup raises KeyError: 'usd', which get_rate converts into a ValueError with raise ... from e.
  2. The KeyError shows the key was lowercase 'usd'. If RATES uses ISO codes like 'USD', the root cause is not in rates.py but in views.py line 42, which passes client input through without normalizing it.
  3. Condition: any request whose currency is not exactly an uppercase key in RATES.
  4. To confirm: print RATES.keys(), and check whether a client or API version recently started sending lowercase codes.

The fix then goes where the data enters the system: validate and normalize currency at the API boundary, return a 400 for unknown codes, and add a test that posts "usd". Adding 'usd' to the table would have hidden the problem until someone sent "Usd".

Mistakes that make AI debugging slower

  • Pasting only the error message. “TypeError: cannot read properties of undefined” without frames or code gives the model nothing to locate.
  • Cutting chained sections. The original exception is often the useful one.
  • Accepting a fix you cannot explain. If you cannot say why the change works, you have not confirmed the cause.
  • Letting the model guess versions. It may describe behavior from a different release of your framework.
  • Iterating in one very long chat. After several failed theories, start a fresh conversation with a summary of what you have ruled out. Long threads accumulate wrong assumptions.
  • Debugging minified JavaScript. Frames like main.4f3a.js:1:20931 point at bundled code. Get a source-mapped trace from your error tracker or dev build before prompting; AI prompts for debugging JavaScript and TypeScript errors covers that case.

When the trace is not the whole story

Some failures do not produce a useful trace at all: a process killed for memory, a timeout at a load balancer, a deadlock that hangs rather than throws. In those cases give the model what you have instead (the last log lines before the failure, resource metrics, the timeout error from the caller) and ask the same structured questions: what was executing, what condition explains it, and what evidence would confirm it. If you are handing the problem to someone else instead, a clear write-up with the trace, steps and environment saves everyone a round trip; AI prompts for writing bug reports shows how.

Sources

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top