Sub topic 3
Add the context the assistant cannot see
This chapter assumes you can read and write code in at least one language, run tests, and have used a chat-based or editor-integrated assistant. It builds on the previous chapters: a prompt is the assistant's only view of your task, and a good prompt starts with a specific, testable goal.
Why context matters
A goal tells the assistant what you want. Context tells it where the work happens. The assistant cannot see your repository, your terminal, your installed packages, or the conversation you had with a teammate yesterday. Anything you do not write down, it fills in with a guess. The guess is usually the most common choice in its training data, which may not match your project.
Consider the request "Add a retry to the fetch function." Without context, the assistant must guess the language, the HTTP library, whether the function is async, and what "fetch" even refers to. It may produce code that is valid but useless to you: it might use requests when your project uses httpx, or add a synchronous time.sleep to an async function.
Context is the set of facts that lets the assistant make the same choices you would make. You supply it by writing it into the prompt.
The kinds of context that matter
Most useful context falls into five groups.
| Kind of context | Examples | What goes wrong without it |
|---|---|---|
| Language and runtime | Python 3.10, Node 20, Java 17 | Syntax or standard-library features that your version lacks |
| Frameworks and libraries | Django 4.2, `httpx`, pytest | A different library than the one you use |
| Existing code | The function to change, its callers, a type definition | Duplicate helpers, mismatched names and signatures |
| Errors and observed behavior | Full traceback, failing test output, actual vs. expected result | A fix for a problem you do not have |
| Environment and conventions | OS, deployment target, style guide, project layout | Code that runs on the assistant's imagined setup but not yours |
You rarely need all five. Pick the ones that could change the answer.
Language and versions
Always name the language. Name the version when it affects the answer, which is more often than people expect.
- Python 3.9 has no
matchstatement and noX | Ytype union syntax in annotations that are evaluated at runtime. Python 3.10 has both. - Java 8 has no
var. Java 17 has records and text blocks. - A library's major version can change its API. Code written for Pydantic v1 fails under v2, and the reverse is also true.
The topic's running example does this in one line: "Write a Python 3.10 function slugify(text: str) -> str". That single phrase rules out older syntax and tells the assistant that type hints are welcome.
If you are unsure of a version, check before you prompt:
python --version
pip show pydanticExisting code
When you ask for a change to code that already exists, paste that code. Describing it in words loses detail, and the assistant will invent whatever you leave out.
Include the smallest slice that lets the assistant do the job:
- The function or class you want changed.
- The signatures of anything it calls, if those are not obvious.
- Type definitions or data shapes it depends on.
- One example of the project's style, if you want new code to match it.
Leave out unrelated files. A long paste dilutes the relevant part and raises the chance the assistant edits something you did not intend. It also costs more of the limited amount of text the assistant can consider at once.
Label each piece so the assistant knows what it is looking at. Here is a prompt that supplies code and a request together:
Task: Add a timeout parameter to fetch_json and raise a clear error when it expires.
Context: Python 3.10, using httpx 0.27. Here is the current function:
def fetch_json(url: str) -> dict:
response = httpx.get(url)
response.raise_for_status()
return response.json()
Callers pass only the url, so the new parameter must be optional.
Constraints: do not change the return type; do not add new dependencies.
Output format: only the updated function.The prompt names the language, the library and its version, the current code, and one fact about callers that the assistant could not have known. The last point matters most. The code alone does not reveal that existing callers pass only url, so the assistant might otherwise make the new parameter required and break them.
Errors and observed behavior
For debugging, the most valuable context is evidence. A description such as "it doesn't work" gives the assistant nothing to reason from. Provide three things:
- What you did, such as the command you ran or the input you passed.
- What you expected to happen.
- What happened instead, including the complete error message and traceback.
Copy the traceback exactly. Do not paraphrase it. The file names, line numbers, and exception type are the clues the assistant uses.
Task: Find why this test fails and propose a fix.
Context: Python 3.10, pytest 8. Running `pytest tests/test_slug.py` gives:
FAILED tests/test_slug.py::test_slugify[C++ & Rust-c-rust]
AssertionError: assert 'c--rust' == 'c-rust'
Current function:
def slugify(text: str) -> str:
text = text.strip().lower()
text = re.sub(r"[^a-z0-9]", "-", text)
return text.strip("-")
Expected: "c-rust". Actual: "c--rust".
Output format: one sentence naming the cause, then the corrected function.Here the failing output points at the cause: the pattern replaces each non-alphanumeric character instead of each run of them. The assistant can confirm this quickly because you gave it the actual and expected values next to the code.
Also state what you have already tried. If you have ruled out a cause, say so, or the assistant will propose it again.
Environment and conventions
Some context is not about the code at all. Mention the following when it could affect the answer:
- The operating system, when the task involves paths, shells, or system tools.
- The deployment target, such as a serverless function with a time limit or a browser with no file access.
- Team conventions: naming style, docstring format, test framework, logging approach.
- Hard limits, such as "no network access at runtime".
Conventions are easy to forget because you stopped noticing them. If a reviewer has ever asked you to change something in your pull requests, that is a convention worth stating in the prompt.
How much context is enough
More context is not always better. The test is whether a fact could change the assistant's answer. If it could, include it. If it could not, leave it out.
Three practical rules follow from this:
- Prefer specific facts over general background. "Django 4.2 with PostgreSQL 15" helps. A paragraph on your company's history does not.
- Trim pasted code and logs to the relevant part. For a long traceback, keep the final exception and the frames that belong to your code. If you cut anything, say that you did.
- Do not include secrets. API keys, passwords, tokens, and customer data do not belong in a prompt. Replace them with placeholders such as
API_KEYor[email protected]. A later chapter covers this in detail.
Edge cases and common mistakes
Stale context. If you edit the code during a conversation, the assistant still holds the old version. Paste the current version when it matters, or say "ignore the earlier version of this function".
Contradictory context. A prompt that says "Python 3.8" in one place and uses match in the pasted code confuses the answer. Check that your facts agree with each other.
Missing context that you think is obvious. The assistant does not know that "the config" means settings/prod.yaml. Name the file.
Context that quietly overrides the goal. A large paste can pull the answer toward the pasted code's style, even when you wanted something different. Say which parts are reference and which are the target: "Use orders.py as a style reference only. Do not modify it."
Partial snippets that hide dependencies. If the pasted function uses a global or a helper you did not include, the assistant will guess what it does. List such dependencies or include their definitions.
Assuming the assistant ran your code. Most assistants do not execute anything unless they have a tool for it. When you report behavior, report what you observed. Do not expect the assistant to have observed it.
A worked comparison
Here is the same request with and without context.
Without context:
Make the report export faster.
With context:
Task: Reduce the time of export_report for 100,000 rows.
Context: Python 3.10, pandas 2.1. The function below takes about 40 seconds on 100,000 rows; profiling shows most time in the loop that builds `df`. Memory is not a concern.
def export_report(rows: list[dict]) -> pd.DataFrame:
df = pd.DataFrame()
for row in rows:
df = pd.concat([df, pd.DataFrame([row])], ignore_index=True)
return df
Constraints: keep the signature and the output columns; no new dependencies.
Output format: the revised function and one sentence explaining the change.The first version could produce advice about databases, caching, or parallelism. The second points at the loop and fixes the library and signature. The assistant can now suggest building the DataFrame once from the list, which is the likely cause of the slowdown, because it can see the code, the measurement, and the profiling result.
Exercise
You ask an assistant, "Fix the crash in my parser." It proposes a change that does not help. List four pieces of context you should add to the prompt, and explain why a pasted traceback should be copied rather than summarized.
Show answer
Add the language and version (and parser library, if any), the parser code or the relevant function, the input that triggers the crash, and the complete error message with traceback. You could also add what you expected to happen and what you have already tried. The traceback should be copied exactly because the exception type, file names, and line numbers are the evidence the assistant uses to locate the cause. A paraphrase drops those details and leaves the assistant guessing.
Exercise
A prompt says "Python 3.8" in its context line, but the pasted code uses a match statement. What problem does this cause, and how do you fix it?
Show answer
The facts contradict each other, because match requires Python 3.10 or later. The assistant may follow either fact, so the answer could be code that fails on 3.8 or code that depends on newer syntax. Check which version you actually run, correct the prompt (or the code), and state the version once, consistently.