Sub topic 2
Context limits and spending your budget
This chapter assumes you have programmed in at least one language, used an editor or terminal, and chatted with an AI assistant before. It covers the second concept in the plan: the context window is finite, and every piece of context you add uses part of it.
What the context window is
An AI assistant does not remember your project. On each request, it reads a block of text and produces a reply. That block of text is the context. The maximum amount of text the model can handle at once is the context window.
The window is measured in tokens, not characters or lines. A token is a chunk of text, often a short word or part of a longer one. English prose averages roughly four characters per token. Code usually costs more per character than prose, because symbols, indentation, and unusual identifiers split into many small tokens. Treat these figures as rough guides. Each model has its own tokenizer, so the same file can have different token counts in different tools.
The window holds more than what you typed. A typical request fills it with several parts:
- Instructions the tool adds on your behalf, such as a system prompt and the descriptions of tools it can call.
- Standing instructions, such as a project conventions file.
- The earlier turns of the conversation, including the assistant's own replies.
- Files, selections, and error output you attached.
- Anything the assistant read or ran while working, such as file contents and command output.
- Your new message.
- Room for the reply itself.
The last item is easy to forget. Most models count the reply against the same limit or a closely related one. If the input fills nearly the whole window, little space remains for the answer, and long replies can be cut short.
Why a limit matters even when the window is large
Modern windows can hold hundreds of thousands of tokens, which may sound like more than you will ever need. Three effects still make budgeting worthwhile.
- Hard limits still get hit. A large repository, a long log, or a conversation that has run for hours can exceed any window. When that happens, the tool either refuses the request, drops older content, or summarizes it. You do not always control which.
- Quality drops before the limit. A model has to find the relevant lines among everything it was given. When the relevant part is a few lines inside tens of thousands of lines of unrelated text, the model is more likely to miss it, mix up similar names, or answer from the wrong place. Models tend to attend less reliably to material buried in the middle of a very long input.
- Cost and speed. Many tools bill by tokens, and larger inputs take longer to process. A request that carries ten files when one would do is slower and more expensive for no benefit.
So the goal is not to fill the window. The goal is to put the most useful text in it.
A budget model
Think of the window as a budget with fixed and variable spending.
| Category | Who controls it | Typical behavior |
|---|---|---|
| Tool and system instructions | The tool | Fixed. You cannot remove it. |
| Standing instructions | You | Paid on every request, so keep them short. |
| Conversation history | Grows over time | Grows with each turn and is the usual source of bloat. |
| Attached context | You | The part you decide on for each request. |
| Reply space | The tool and the model | Must be left free. |
You have the most control over attached context and conversation history. Standing instructions matter because they are charged on every request, so a long conventions file costs you again on each turn.
Estimating what something costs
You rarely need an exact count, but you should be able to judge orders of magnitude. A rough rule is one token per four characters of prose, and somewhat fewer characters per token for code.
You can measure a file's size before you attach it. The following Python script prints an approximate token count for each file you pass on the command line. It uses only the standard library and the four-characters-per-token heuristic, so treat its output as an estimate.
import sys
from pathlib import Path
CHARS_PER_TOKEN = 3.5 # code tends to be a little denser than prose
def estimate_tokens(text: str) -> int:
return round(len(text) / CHARS_PER_TOKEN)
def main(paths: list[str]) -> None:
total = 0
for name in paths:
path = Path(name)
try:
text = path.read_text(encoding="utf-8")
except (OSError, UnicodeDecodeError) as error:
print(f"{name}: skipped ({error})")
continue
tokens = estimate_tokens(text)
total += tokens
print(f"{name}: about {tokens} tokens")
print(f"total: about {total} tokens")
if __name__ == "__main__":
main(sys.argv[1:])Run it as python count_tokens.py stats.py README.md. For the small stats.py file used in this tutorial, the count is tiny. For a generated file, a lock file, or a minified bundle, the count can be enormous. Those are exactly the files you want to discover before attaching them.
Spending the budget well
Prefer the smallest context that answers the question
Start with the narrowest context that could work, then widen it if the answer needs more. Consider the bug in stats.py:
def average(values):
return sum(values) / len(values)
print(average([]))To fix it, the assistant needs the function, the failing call, and the error. It does not need the rest of the repository. Sending only those three items is cheap, and the answer can focus on the actual problem. If the assistant then asks where average is used, you can add the call sites.
Starting small and expanding is almost always better than starting large and hoping the assistant finds the right part. Later chapters cover how to choose between a file, a selection, and a description.
Rank content by how much it helps
Not all text is equally useful. When you have to cut, keep the content that carries the most information per token.
- The exact error message and the lines it points to.
- The code that failed, and the code it directly calls or is called by.
- The statement of what you want changed.
- Surrounding definitions, such as types or function signatures the code depends on.
- General background, such as the whole module or related files.
Items near the top are cheap and decisive. Items near the bottom are expensive and often unnecessary.
Trim repetitive and low-value text
Some content takes many tokens and says little:
- Long stack traces where the same frames repeat many times. Keep the first and last frames and the exception line.
- Log files with thousands of identical lines. Share the lines around the failure.
- Generated files, dependency lock files, and build output.
- Whole files when only one function matters.
Trimming should keep the information that identifies the failure. For the error in this tutorial, the whole traceback is short, so you keep all of it:
Traceback (most recent call last):
File "stats.py", line 4, in <module>
print(average([]))
File "stats.py", line 2, in average
return sum(values) / len(values)
ZeroDivisionError: division by zeroA trace with two hundred frames from a framework would be a different case. There you would keep the exception line, the frames from your own code, and a few frames on either side.
Control conversation growth
Every turn adds to the history, and the history is resent each time. A conversation that began with a small bug can end up carrying a long record of abandoned ideas, pasted output, and earlier file versions. That record costs tokens and can mislead the model, because old, wrong code sits next to the current code.
Two habits help. First, start a new conversation when you change tasks. Second, when a thread has become long, write a short summary of the current state and begin fresh with that summary and only the files you still need. A later chapter returns to this under keeping context current and uncluttered.
Failure modes when the budget runs out
Knowing how tools behave at the limit helps you recognize the symptoms.
| Symptom | Likely cause | What to do |
|---|---|---|
| The tool reports the input is too long | Attached content exceeds the window | Remove files or trim logs, then resend |
| The assistant forgets an earlier instruction | Older turns were dropped or summarized | Restate the instruction, or start fresh |
| The reply stops mid-sentence | Not enough room left for output | Shorten the input and ask again |
| The answer ignores a detail you attached | Detail was lost among a lot of text | Cut the unrelated text and point to the detail |
| The assistant invents a function that exists elsewhere | The real definition was not included | Attach the definition |
The fourth and fifth rows have no error message. The assistant produces a confident answer anyway. This is why a smaller, targeted context gives you more than reliability against limits. It also gives you answers that are easier to check.
Context spending in practice
Here is the same request in two forms. Both ask for the same fix.
The expensive form attaches stats.py along with five unrelated modules, the full test suite output, and a long conversation history about an earlier refactor. The assistant must sort out which parts matter.
The budget-aware form is brief:
Context: stats.py (attached), selection: the average function (lines 1-2).
Error: ZeroDivisionError: division by zero when average([]) is called.
Task: Change average so an empty list returns None instead of raising. Keep the function signature and do not change other code.It names the file, the selection, and the error, then states the task and its limits. It costs a small fraction of the other form, and the assistant has little room to wander. The remaining chapters explain how to build each part of a request like this.
Checklist before you send
- Does the request include the error text or the lines it points to?
- Can any attached file be replaced with a selection from it?
- Are there repeated or generated lines you can cut?
- Is the conversation still about this task, or should you start fresh?
- Have you left room for a full reply?
Exercise
You are asking an assistant to fix a bug in one 30-line function. Your project has a 4,000-line module containing that function, a 15,000-line log, and a conversation that is 40 turns long and mostly about a different feature. Which of these would you send, and why? Name one symptom that would suggest you sent too much.
Show answer
Send the 30-line function (a selection), the exact error message with the trace lines from your own code, and a short task statement. Leave out the full module, the log (extract only the lines around the failure if needed), and the old conversation (start a new one). Sending too much spends tokens on irrelevant text and makes it more likely that the assistant overlooks the key lines. A symptom of this is an answer that ignores a detail you attached, refers to code from the other feature, or invents a function that exists elsewhere in the module.
Exercise
Using the token-counting script from this chapter, a 21,000-character file is estimated at how many tokens? Is that estimate exact, and why or why not?
Show answer
21,000 divided by 3.5 is 6,000 tokens. The estimate is not exact, because the script uses a fixed characters-per-token ratio, while real tokenizers split text differently depending on the model and on the content. Use it only to compare file sizes and spot very large files.