The context window is a token limit covering the system prompt, the conversation, retrieved documents and the response, and every request must fit prompt plus system plus retrieved context plus answer inside it. A common mistake when calling LLM APIs is forgetting that the context window is a shared pool between the input prompt and the generated response: if the model has a 32,000-token limit and the prompt is 30,000 tokens long, the model can generate at most 2,000 tokens before hitting the wall.
What you need
- The context window size of your model, in tokens
- A token count for your system prompt, history and retrieved documents
- How many output tokens the answer needs
Step 1: Add up everything the request will carry
Count the system prompt, the conversation history, the retrieved documents and the output you need to reserve. The window is shared, so every part counts against the same total.
Step 2: Reserve room for the answer first
Subtract the output tokens you need before adding retrieved context. An answer cut off mid-sentence looks like an error, and a prompt that fills the window leaves no room to reply.
Step 3: Trim the biggest part until it fits
If the total is over the window, trim the largest part: shorten the history, retrieve fewer chunks, or compress the documents. Re-count after each trim.
Worked example: synthetic context budget for a 32,000-token window
The table below is a synthetic example. It shows the expected result of budgeting a context window; no API call was made.
| Part | Tokens | Share of window |
|---|---|---|
| System prompt | 1,200 | 4 percent |
| Chat history | 14,000 | 44 percent |
| Retrieved documents | 10,000 | 31 percent |
| Reserved output | 4,000 | 13 percent |
| Total | 29,200 of 32,000 | 91 percent – fits |
Expected result (UNTESTED). the request totals 29,200 of 32,000 tokens, or 91 percent of the window, so it fits with room to spare. This check was not run live; the table shows the expected result for the synthetic example.
Limits
- The context window is a shared pool; exceeding it truncates the input or errors, depending on the API.
- Cost is per input and output token, usually priced differently, so a large prompt costs money as well as window.
- Long prompts and long outputs eventually push earlier context out of the model view, which is why conversations can forget earlier instructions.
- Always set max_tokens; it caps the output length and the cost.
