Sub topic 3
Gather the context the assistant needs
This chapter assumes you can read a traceback (covered in the first chapter), reproduce a failure and shrink it (the second chapter), run code and tests from a terminal, and use basic git commands. The aim here is to decide what to send to an assistant along with your question, and what to leave out.
Why context decides the quality of the answer
An assistant cannot see your machine. It sees only the text you give it. When that text is thin, the assistant fills the gaps with guesses. The guesses are often plausible, which makes them harder to catch than obvious mistakes.
Compare two messages:
- "My average function crashes. How do I fix it?"
- A message with the function, the full traceback, the Python version, the input that triggers the crash, and what you expected to happen.
The first forces the assistant to guess the language, the cause and the goal. The second lets it reason from evidence. The extra work takes a few minutes, and it usually saves several rounds of back-and-forth.
The five pieces of context
Most debugging prompts need the same five things. You collect them before you write the prompt itself, which is the subject of a later chapter.
| Piece | What to include | What goes wrong without it |
|---|---|---|
| Code | The failing function and the code that calls it | The assistant invents code that looks like yours |
| Error output | The full traceback or log, unedited | The assistant guesses the error type and location |
| Environment | Language, runtime and library versions, operating system | Advice targets the wrong version or a removed API |
| Expected and actual behavior | What should happen and what happens instead | The assistant "fixes" behavior you wanted |
| What you tried | Changes made, commands run, results seen | You get the same suggestions you already rejected |
The code
Include the function that fails and the code that calls it. The failing line named in the traceback is the starting point, but the cause often sits in a caller that passed bad data.
For the running example from this tutorial, the failing code is:
def average(values):
return sum(values) / len(values)
print(average([]))The function is only two lines. In real projects, resist pasting the whole file by default. Instead include:
- The function in the failing frame.
- The caller that supplied the input, if the input looks suspicious.
- Any type definitions, constants or configuration the function reads.
- The import lines, so the assistant knows which libraries are in play.
The error output
Paste the whole traceback, not a paraphrase. A summary such as "it throws a division error" drops the line numbers and the frame order. The assistant can use both to work out which call led to the failure.
Traceback (most recent call last):
File "stats.py", line 5, in <module>
print(average([]))
File "stats.py", line 2, in average
return sum(values) / len(values)
ZeroDivisionError: division by zeroCopy the text instead of retyping it. Do not trim the top of a long traceback, because the frames at the top often show how the program got into the bad state. If the output is thousands of lines, keep the first error and the last frames, and say that you cut the middle.
Also include warnings printed before the error. A deprecation warning or a "falling back to default" log line sometimes explains the failure better than the exception does.
The environment
Many errors depend on versions. A method that exists in one release of a library can be missing or renamed in another. Assistants are trained on text from many years and versions, so without a version they may recommend an API that your installed release does not have.
Give at least:
- The language and runtime version, for example Python 3.12.
- The versions of the libraries involved in the error.
- The operating system, if paths, shells or file permissions might matter.
- How you run the code: a script, a test runner, a container, a notebook or a web server.
Expected and actual behavior
State the behavior you wanted, not only the one you got. For average([]), the actual result is a ZeroDivisionError. The expected result might be a clear error telling the caller that the input is empty, or it might be 0, or it might be None. Those are three different fixes, and only you know which one is correct. If you leave the expectation out, the assistant picks one for you.
What you already tried
List the changes you made and what happened. For example: "I wrapped the call in try/except and it hid the error but the report was still blank." This prevents repeated suggestions. It also tells the assistant which causes you have already ruled out.
Choosing how much code to send
More context is not always better. A very large paste buries the relevant lines, and it increases the chance that you include something sensitive. Use this order of preference:
- A minimal reproduction you built in the previous chapter. It is the best form of context because it contains only what is needed to trigger the bug.
- The failing function, its caller and the traceback.
- Several related files, when the bug depends on how they interact.
- The whole repository, only when the assistant can search it itself and you describe where to start.
Start small and add on request. If the assistant asks for another file, send it. That is cheaper than sending everything up front.
Collect environment details with a script
Typing versions by hand invites mistakes. A short script gives you a consistent block of text to paste. This one prints the Python version, the operating system, the current git commit, and the installed versions of any packages you name on the command line.
import platform
import subprocess
import sys
from importlib import metadata
def run(command):
try:
result = subprocess.run(
command, capture_output=True, text=True, check=False, timeout=10
)
except (FileNotFoundError, subprocess.TimeoutExpired):
return "unavailable"
return (result.stdout or result.stderr).strip() or "unavailable"
def package_version(name):
try:
return metadata.version(name)
except metadata.PackageNotFoundError:
return "not installed"
print(f"Python: {sys.version.split()[0]}")
print(f"OS: {platform.platform()}")
print(f"Git commit: {run(['git', 'rev-parse', '--short', 'HEAD'])}")
for package in sys.argv[1:]:
print(f"{package}: {package_version(package)}")Save it as envinfo.py and run it with the packages relevant to your bug:
python envinfo.py pytest requestsThe output is a few lines you can paste under your question. The script names packages explicitly instead of printing everything installed. A full pip freeze is long, mostly irrelevant, and can contain private index URLs or internal package names.
Capture the state of your changes
If the bug appeared after a change, the change is the most valuable piece of context you have. Git can show it:
git status --short
git diff
git log --oneline -5git diff shows uncommitted edits. If the code worked at an earlier commit, say which one. "This passed at commit a1b2c3d and fails now" narrows the search to the changes in between. Use git diff a1b2c3d HEAD -- path/to/file.py to share only the relevant difference.
How the pieces fit together
The order below is the order that wastes the least effort. You read the error first, reproduce it, then collect, and only then write the prompt.
Edge cases and common mistakes
The error you paste is not the error you have
If you changed code after the failure, the traceback may no longer match the file. Line numbers will point at the wrong lines, and the assistant will reason about code that is not there. Rerun the failing command and paste fresh output together with the current code.
Errors that only appear sometimes
For intermittent failures, one traceback is not enough. Record how often the failure occurs, what differs between passing and failing runs, and whether it depends on timing, ordering, input size or the machine. Say so explicitly, for example: "Fails about one run in ten when the full test suite runs, never when this test runs alone." That detail points toward shared state or test ordering, which the assistant cannot infer from a single traceback.
Errors that happen in a different place than they originate
Python reports where an exception was raised, not where the bad value was created. A None that reaches len() may have been returned by a function three calls earlier. When you suspect this, include the caller chain and the line where the value was produced, not just the failing frame.
Logs and framework noise
Web frameworks and test runners print many lines around an error. Keep the first exception, the frames from your own code and the last lines. Remove repeated lines, but write "[repeated 40 times]" so the assistant knows lines were removed. Do not edit the contents of the lines you keep.
Mixed-up environments
A common cause of "it works on my machine" is running a different interpreter than you think. Run python --version and which python in the same terminal where the failure happens, and check that the version in your message matches. Virtual environments, containers and IDE run configurations can each use a different interpreter.
Sensitive values in the material you gathered
Tracebacks, logs and git diff output can contain API keys, tokens, connection strings, user emails and file paths with usernames. Review everything you gathered before sending it. The next chapter covers how to remove these values safely. Treat this review as a required step, as the diagram shows.
Checklist before you write the prompt
- The failing function and its caller are included, or a minimal reproduction replaces them.
- The traceback is complete, fresh and matches the current code.
- Language, runtime and relevant library versions are listed.
- The expected behavior is written in one sentence.
- Previous attempts and their results are listed.
- The material has been checked for secrets and personal data.
Exercise
You ask an assistant why your script fails and send only the sentence "I get a KeyError when I load the config." The assistant suggests using dict.get(). List three pieces of context that were missing, and say what each would have told the assistant.
Show answer
Examples of valid answers: (1) The full traceback, which shows the exact missing key and the line that raised the error, so the assistant can tell whether the key is absent from the file or misspelled in the code. (2) The config file's structure with values removed or replaced, which shows what keys exist. (3) The expected behavior, which tells the assistant whether a missing key should use a default, raise a clear error, or never happen. The environment version or the code that loads the config would also be acceptable. The dict.get() suggestion may hide a real problem, such as loading the wrong file.
Exercise
A traceback you pasted shows File "report.py", line 42, but after you edited the file, line 42 is now a blank line. Why is this a problem for the assistant, and what should you do?
Show answer
The traceback no longer matches the file, so the assistant will reason about lines that do not correspond to the code you sent. Rerun the failing command and paste the new traceback together with the current version of the code, so the line numbers match.
Exercise
Run the envinfo.py script from this chapter in one of your own projects, naming two packages that the project uses. Which line of the output would you check first if an assistant suggested a method that your library does not have, and why?
Show answer
Check the line for that library's version. The assistant may have drawn on documentation for a different release, so comparing the version to the one the method was added or removed in shows whether the suggestion applies to your installation.