ChatGPT Prompt to Debug an Error From a Stack Trace
A debug stack trace prompt gives ChatGPT, Claude, or Gemini the exact error message, the stack trace, and the relevant code so it can find the root cause instead of guessing from a vague description like "my app is broken." This is for developers who are stuck staring at a traceback, a failed CI job, or a production error log and want a model to narrow down what actually went wrong before they start changing code.
The prompt works because it forces structure: the full error text, the stack trace in order from where the exception was raised, the code around each relevant frame, and what the developer already tried. Models are good at pattern-matching known exception types and common causes (null references, off-by-one errors, async timing issues, type mismatches) when given this context, but they will hallucinate a plausible-sounding fix if the trace is incomplete or truncated.
Used well, the output is a ranked list of likely causes tied to specific lines, not a single confident guess. If the stack trace is long or spans multiple files, pasting it alongside a vague prompt wastes tokens and often gets cut off mid-context, so running it through a Token Optimizer first keeps the trace and surrounding code lean enough that nothing relevant gets dropped before the model sees it.
Prompt template
ROLE: You are an experienced [PROGRAMMING LANGUAGE] developer helping debug a runtime error.
CONTEXT:
-
Language/runtime: [LANGUAGE AND VERSION, e.g. Python 3.11, Node 20]
-
Framework/libraries involved: [FRAMEWORK NAMES AND VERSIONS]
-
What the code is supposed to do: [BRIEF DESCRIPTION OF THE FEATURE OR FUNCTION]
-
Error message and full stack trace: [PASTE FULL ERROR MESSAGE AND STACK TRACE HERE, TOP TO BOTTOM, UNEDITED]
-
Relevant source code (include every function/file named in the trace): [PASTE CODE FOR EACH FRAME IN THE STACK TRACE]
-
What I've already tried: [LIST ANY FIXES OR CHECKS ALREADY ATTEMPTED, OR WRITE "NOTHING YET"]
CONSTRAINTS:
- Do not suggest a fix until you've identified the specific line and condition that triggers the exception
- If the trace doesn't contain enough information to be certain, say so and list what additional information (logs, input values, config) would confirm the cause
- Do not assume framework defaults that weren't stated — ask if a detail is missing rather than guessing
OUTPUT FORMAT:
- Root cause analysis: the most likely cause, tied to the exact line/frame in the trace
- Alternative hypotheses: 1-2 other possible causes, ranked by likelihood, each with what evidence would confirm or rule it out
- Suggested fix: the minimal code change to resolve the most likely cause
- Verification step: how to confirm the fix actually resolves the error (a test to run, a log line to check, an input to retry)
Example input
ROLE: You are an experienced Python developer helping debug a runtime error.
CONTEXT:
-
Language/runtime: Python 3.11
-
Framework/libraries involved: FastAPI 0.110, SQLAlchemy 2.0
-
What the code is supposed to do: fetch a user's order history by user_id and return it as JSON
-
Error message and full stack trace: Traceback (most recent call last): File "app/routers/orders.py", line 42, in get_order_history orders = db.query(Order).filter(Order.user_id == user_id).all() File "app/models/order.py", line 18, in repr return f"<Order {self.id} total={self.total.amount}>" AttributeError: 'NoneType' object has no attribute 'amount'
-
Relevant source code:
app/routers/orders.py
@router.get("/orders/{user_id}") def get_order_history(user_id: int, db: Session = Depends(get_db)): orders = db.query(Order).filter(Order.user_id == user_id).all() return orders
app/models/order.py
class Order(Base): id = Column(Integer, primary_key=True) user_id = Column(Integer) total = Column(Money, nullable=True)
def __repr__(self):
return f"<Order {self.id} total={self.total.amount}>"
- What I've already tried: confirmed user_id exists in the database and has orders
CONSTRAINTS:
- Do not suggest a fix until you've identified the specific line and condition that triggers the exception
- If the trace doesn't contain enough information to be certain, say so
OUTPUT FORMAT:
- Root cause analysis
- Alternative hypotheses
- Suggested fix
- Verification step
Example output
-
Root cause analysis: The exception is raised in Order.repr at app/models/order.py line 18, not in the query itself.
self.totalisNonefor at least one of the returned orders (thetotalcolumn is declarednullable=True), and the code calls.amounton it unconditionally. When FastAPI or logging tries to represent one of these Order objects as a string (for example when serializing the response or logging the result),__repr__runs and crashes on the None value. -
Alternative hypotheses:
- The
totalcolumn itself is correctly populated but theMoneytype's.amountattribute name is wrong for this version of the library (less likely, since the error is specificallyNoneType has no attribute, confirmingtotalis None, not misnamed). - A specific order row was inserted without a total value due to a bug elsewhere (e.g., a failed payment webhook that created the order before charging it). Confirm by querying
SELECT id FROM orders WHERE user_id = <id> AND total IS NULL;.
- Suggested fix:
def __repr__(self):total_str = f"{self.total.amount}" if self.total is not None else "none"return f"<Order {self.id} total={total_str}>"
Also consider whether orders should ever have a null total — if not, enforce it at the database level with nullable=False and backfill existing null rows.
- Verification step:
Re-run the
/orders/{user_id}endpoint for the same user_id that triggered the original error. Add a temporary log line before the query result is returned:logger.info([o.total for o in orders])to confirm which order had a None total, then confirm the endpoint now returns a 200 response instead of raising AttributeError.
When to use it
- A production error log or exception monitoring tool (Sentry, Datadog, CloudWatch) surfaced a stack trace and you need to triage it quickly
- A CI pipeline failed with a traceback and you want to understand the failure before re-running the build blindly
- You're debugging an intermittent or hard-to-reproduce error and need a second opinion on likely root causes from the trace alone
- You inherited code you didn't write and the stack trace references functions or modules you're unfamiliar with
Best practices
- Paste the full, unedited error message and stack trace in the original order the runtime produced it — don't paraphrase or summarize the exception text
- Include the actual source code for every function or file named in the trace, not just the one where the error surfaced, since the root cause is often several frames up the call stack
- State what you already tried or ruled out so the model doesn't waste the first response re-suggesting a fix you've already tested
- Ask for multiple ranked hypotheses with the specific line or condition that would confirm each one, rather than a single fix, especially for intermittent or environment-dependent errors
Common mistakes
- Pasting only the last line of the error message instead of the full stack trace, which hides exactly where the failure actually originated
- Omitting the code for upstream functions in the call chain, so the model can only guess at what data or state triggered the exception
- Not specifying the language version, framework version, or runtime environment, which matters for errors tied to deprecated APIs or breaking changes
- Accepting the first suggested fix without asking the model to explain why that specific line causes that specific exception type
FAQs
Why does ChatGPT sometimes suggest a fix that doesn't match my actual error?
This usually happens when the stack trace is incomplete or the model wasn't given the code for every frame in the trace. ChatGPT will pattern-match the exception type to a common cause for that type even without full context, which produces a plausible but wrong guess. Always include the full trace and the code at each referenced line.
Should I paste the whole file or just the function that crashed?
Paste at minimum the function where the exception was raised plus every function listed in the stack trace above it, since the root cause is frequently several calls upstream from where the error actually surfaces. If a file is large, trim unrelated functions rather than truncating the relevant ones.
Does it matter which model I use for debugging a stack trace?
All major models (ChatGPT, Claude, Gemini) can parse structured stack traces well since they're trained on large amounts of code and error logs, but results depend far more on how complete the pasted context is than on which model you pick. Claude and GPT-4-class models tend to handle longer traces with more surrounding code without losing track of earlier details.
How do I debug an error that only happens intermittently and doesn't always produce the same trace?
Collect traces from several occurrences if possible and note what varies between them (input values, timing, concurrent requests), then ask the model to compare the traces for a common frame or condition rather than analyzing a single instance in isolation.
What Cuelara tool can help me build a stronger version of this prompt?
Prompt Optimizer — its Coding mode is built specifically to turn a messy debugging request and pasted trace into a structured prompt with clear constraints, which reduces the chance of the model jumping to an unverified fix.