Sub topic 1
What the Context Window Is and Why Context Engineering Matters
Prerequisites
Assume you can call a large language model through a chat or API, understand prompts and system prompts, and read short Python code. You should know that tokens are the text units a model processes.
What the Context Window Is
A context window is the maximum amount of input and output text a model can process in one call. Its contents become the model’s working information for that call. Context engineering is the practice of selecting, ordering, and maintaining that information.
A larger window does not automatically produce better answers. Irrelevant documents can distract the model. Conflicting instructions can cause a clash. Untrusted retrieved text can contain prompt injection, a malicious instruction hidden inside data. The goal is useful information, not maximum information.
Tokens and Budgeting the Window
A token is a small piece of text used by the model. Words, punctuation, and parts of words can each consume tokens. The model’s window must hold the input plus reserved space for the response.
A practical budget is:
window size - output reserve - system prompt - question
Use the remaining space for history and retrieved data. Keep a margin because token estimates are imperfect.
def estimate_tokens(text):
return max(1, len(text) // 4)
def remaining_budget(window, system, question, output_reserve):
used = estimate_tokens(system) + estimate_tokens(question)
return window - output_reserve - used
print(remaining_budget(8000, "You are helpful.", "Explain caching.", 1000))The Parts of a Context
| Part | Purpose |
|---|---|
| System prompt | Sets durable rules and behavior |
| Tools | Describes available actions and their arguments |
| History | Preserves relevant earlier decisions |
| Retrieved data | Supplies task-specific evidence |
| User input | States the current goal |
These parts compete for the same budget. Tool definitions and large tool results can consume more space than expected.
Choosing What to Include
Select information based on its relevance to the current step. Prefer direct evidence, current requirements, and decisions that constrain the answer. Remove duplicate, stale, and unrelated material.
A useful selection process is:
- State the current subtask.
- Rank candidate context by relevance and reliability.
- Add the highest-ranked items until the budget is nearly full.
- Check for contradictions and untrusted instructions.
Exercise
Why reserve space for model output instead of filling the entire context with input?
Show answer
The model needs that reserved space to generate its response. Without it, the call may be truncated or rejected.