Sub topic 1
Giving an AI Assistant the Right Context: Files, Selections, and Errors
Prerequisites
This chapter assumes basic programming experience, terminal or editor use, and some experience with an AI coding assistant.
What Context Is and Why It Matters
Context is the information an assistant can use for a response. It includes your request, earlier messages, selected code, attached files, and sometimes project information available through tools.
An assistant does not automatically know your whole project. If you omit an important dependency, requirement, or error, it may produce a plausible but incorrect answer. Good context reduces guessing.
For example, this function has a problem:
def average(values):
return sum(values) / len(values)
print(average([]))If you ask for a fix, the assistant needs to know whether an empty list should return None, return zero, or raise a different error. The code shows the failure, but the task statement supplies the intended behavior.
Context Limits and Spending Your Budget
A context window is the maximum amount of text an assistant can process in one interaction. Large files, long conversations, and repeated logs consume this limited budget.
Spend the budget on information that changes the answer:
- Include the relevant code and its surrounding interfaces.
- Remove repeated explanations and unrelated files.
- Summarize large generated files instead of pasting them.
- Keep the task, constraints, and expected result near the request.
Deciding What Is Relevant
Use the smallest useful context that still explains the task.
Share a whole file when imports, shared state, class structure, or nearby functions affect the behavior. Share a selection when the problem is local and the surrounding code adds little value. Share only a description when you need a general design suggestion rather than a code change.
Ask yourself: “Could removing this information change the assistant’s answer?” If not, leave it out. Before sending context, remove stale code, unrelated logs, credentials, tokens, and personal data.
Sharing Files
When sharing a file, identify its path and explain why it matters. State the relevant function, class, or line range. Include constraints such as preserving the public function signature or avoiding changes to other files.
A focused request might say:
> stats.py, lines 1–2: Change average so an empty list returns None. Keep the function signature and do not change other code.
This combines file identity, selection, desired behavior, and constraints. The assistant can then reason about the actual code instead of inventing missing details.
Exercise
When should you share a whole file instead of a selection?
Show answer
Share the whole file when imports, shared state, class structure, or nearby code could affect the requested change.