AI Agents & LLMsEasy
What is a context window?
Learning path, stage 1 of 5: How LLMs work · question 4 of 10The context window is the maximum number of tokens a model can consider in one request: the system prompt, conversation history, tool definitions, retrieved documents and the model's own output, all together. Anything outside it simply doesn't exist for the model.
Key points
- Current frontier models offer large windows (hundreds of thousands to a million tokens), but bigger isn't free. Cost and latency grow with input size.
- Long context ≠ perfect recall. Models use information at the start and end of a long prompt better than information buried in the middle.
- The output budget (
max_tokens) also comes out of the window.
Strategies when content doesn't fit, or shouldn't
- Retrieve only the relevant chunks (RAG) instead of pasting everything.
- Summarise or compact older conversation turns.
- Trim tool results: return IDs and short summaries, and let the agent fetch details on demand.
- Sub-agents: hand a sub-task to a fresh context and bring back only the result.
Sources
Code example
tsx
1// Keep a chat inside a token budget by dropping the oldest turns.2import Anthropic from "@anthropic-ai/sdk";34const client = new Anthropic();5const MODEL = "claude-opus-5-5";67async function fitToBudget(8 system: string,9 history: Anthropic.MessageParam[],10 budget: number,11): Promise<Anthropic.MessageParam[]> {12 let msgs = [...history];13 while (msgs.length > 1) {14 const { input_tokens } = await client.messages.countTokens({ model: MODEL, system, messages: msgs });15 if (input_tokens <= budget) break;16 msgs = msgs.slice(2); // drop the oldest user+assistant pair17 }18 return msgs;19}2021// Better in production: summarise what you drop instead of losing it.
To run it: follow the one-time setup guide, add npm i @anthropic-ai/sdk, save the code as a .ts file and run npx tsx file.ts. Anything marked declare is a part you supply.
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the AI Agents & LLMs set.