Back to cookbook

ChatGPT Prompt to Debug an Error From a Stack Trace

12 views Published

Make this prompt yours

Share

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

Make this prompt yours

prompt-template
337 tokens
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: 1. Root cause analysis: the most likely cause, tied to the exact line/frame in the trace 2. Alternative hypotheses: 1-2 other possible causes, ranked by likelihood, each with what evidence would confirm or rule it out 3. Suggested fix: the minimal code change to resolve the most likely cause 4. Verification step: how to confirm the fix actually resolves the error (a test to run, a log line to check, an input to retry)

Want it sharper? Optimize this prompt with Prompt Optimizer, check it with the Prompt Debugger or shorten it with the Token Optimizer.

Example input

example-input
364 tokens
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: 1. Root cause analysis 2. Alternative hypotheses 3. Suggested fix 4. Verification step

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.

Found this prompt useful? Share it.

Share

More in Code Generation & Software Engineering

Code Generation & Software Engineering

AI Prompt to Write a GitHub Actions CI/CD Workflow from Plain English

This is a prompt for turning a plain English description of your build, test, and deploy process into a working GitHub Actions workflow YAML…

Role: You are a DevOps engineer writing a GitHub Actions workflow file.

Context:
Project type: [LANGUAGE/FRAMEWORK, e.g. Node.js with npm, Python with Poetry]
Repository structure notes: [e.g. monorepo with /api and /web folders, single app at root]
Runner: [e.g. ubuntu-latest]

Task:
Write a GitHub Actions workflow (.github/workflows/[FILENAME].yml) that does the following, in this order:
1. Trigger on: [TRIGGER EVENTS, e.g. pull_request to main, push of tags matching v*]
2. Job 1 - [JOB NAME, e.g. lint]: [WHAT IT DOES]
3. Job 2 - [JOB NAME, e.g. test]: [WHAT IT DOES], must run only after Job 1 succeeds
4. Job 3 - [JOB NAME, e.g. deploy]: [WHAT IT DOES], must run only after Job 2 succeeds and only on [CONDITION, e.g. tag pushes to main]

Secrets/environment variables needed (reference by name only, do not invent values): [SECRET NAMES, e.g. DEPLOY_TOKEN, AWS_ACCESS_KEY_ID]

Constraints:
- Pin third-party actions to a specific major version (e.g. actions/checkout@v4)
- Use caching for dependencies where the ecosystem supports it
- Keep job names and step names descriptive enough to read clearly in the Actions UI

Output format:
Return the complete YAML file in a fenced code block, followed by a short bullet list explaining what each job does and when it runs.

Make this prompt yours

Code Generation & Software Engineering

AI Prompt to Debug a Failed Vercel Deployment Using Vercel's MCP Server

This Vercel MCP prompt helps developers and DevOps engineers figure out why a deployment failed without manually scrolling through build log…

ROLE: You are a deployment troubleshooting assistant with access to Vercel's MCP server.

CONTEXT:
- Project: [PROJECT_NAME]
- Framework: [FRAMEWORK, e.g. Next.js 14]
- Deployment ID or URL: [DEPLOYMENT_ID_OR_URL]
- Last known good deployment: [PREVIOUS_DEPLOYMENT_ID_OR_URL, or 'none']
- What changed since the last successful deploy: [RECENT_CHANGES_SUMMARY]

TASK:
1. Retrieve the build and runtime logs for the failing deployment.
2. Identify the failure category: build error, runtime error, environment/configuration issue, or dependency issue.
3. Quote the specific log lines that show the root cause.
4. If a last known good deployment is provided, compare configuration and environment variables between the two.
5. Propose a ranked list of likely fixes, most probable first.

CONSTRAINTS:
- Do not guess at a cause without quoting supporting log evidence.
- Flag if critical information (e.g. an environment variable value) is missing rather than assuming it.

OUTPUT FORMAT:
- Failure category
- Root cause (with quoted log evidence)
- Ranked fix recommendations
- Any missing information needed to confirm the diagnosis

Make this prompt yours

Code Generation & Software Engineering

ChatGPT Prompt to Generate a Production-Ready Dockerfile for Your App

This Dockerfile generator prompt gives ChatGPT, Claude, or Gemini everything needed to write a secure, production ready Dockerfile for your…

You are an expert DevOps engineer who writes secure, production-ready Dockerfiles.

Context:
- Application language and version: [LANGUAGE AND VERSION, e.g., Node.js 20]
- Framework: [FRAMEWORK, e.g., Express, Django, Spring Boot]
- Package manager: [PACKAGE MANAGER, e.g., npm, pip, Maven]
- Target deployment platform: [PLATFORM, e.g., AWS ECS, Kubernetes, linux/amd64]
- Special requirements: [e.g., private package registry, native dependencies, health checks]

Task:
Write a production-ready Dockerfile for this application. Use a multi-stage build that separates the build/dependency-install stage from the final runtime stage. The final image should:
1. Use the smallest reasonable base image for the runtime.
2. Run as a non-root user.
3. Only copy the files needed to run the application, not build tools or source maps.
4. Include a HEALTHCHECK instruction appropriate for this type of service.
5. Set any necessary environment variables and expose the correct port.

Constraints:
- Do not use the "latest" tag for any base image; pin a specific version.
- Keep the final image size as small as possible.
- Explain, in a short comment above each non-obvious instruction, why it's there.

Output format:
1. The complete Dockerfile in a single code block.
2. A short bullet list explaining the base image choice and any trade-offs.
3. One suggested .dockerignore entry list for this stack.

Make this prompt yours