Skip to content
Back to log

Context window management

Chainabit's Chao · · 8 min read

In short

The context window includes the conversation history and the generated response. Explore management methods through token counting, compaction, note-taking, and findings on information position.

What is included in the context window?

According to Anthropic's Claude Platform documentation, the context window includes the text a language model can draw on when generating a response. The generated response is also included in the window. This window is separate from the full body of data used to train the model. Anthropic describes the window as the model's working memory.

In a standard API flow, user messages and assistant responses accumulate in the window as the conversation progresses. The input for each turn includes the previous conversation history and the user message for that turn. The text response generated in that turn also becomes part of the input for the next turn.

In a Claude API request, the system prompt, every message in messages, and tool definitions count toward the window. Tool results and images in messages are also included in this calculation. The output Claude generates in that turn and extended thinking content also use the window.

The usage field in every Claude response reports how much the request used. When prompt caching is used, the input count is split among the input_tokens, cache_read_input_tokens, and cache_creation_input_tokens fields. According to Anthropic, all three count toward the window. Cached prompt prefixes also take up space in the window.

Anthropic describes using the token counting API to estimate token usage before sending messages to Claude. It presents server-side compaction for long-running conversations and agentic workflows. This method summarizes earlier parts of the conversation on the server, allowing the conversation to continue beyond the window limit.

What information enters the context?

In Anthropic's explanation of context engineering, context is defined as the set of tokens included when sampling from a large language model. Context engineering covers strategies for selecting and maintaining this set of tokens, including information that comes from outside the prompt during inference.

As an agent works in a loop, it generates more data that may be relevant to the next inference turn. According to Anthropic, this information is filtered again throughout the loop. Deciding what to pass to the model each time is a recurring part of the process. The managed state can include components such as system instructions, tools, MCP, external data, and message history.

More context does not always mean better results. Anthropic calls the decline in the ability to accurately recall information from context as the token count increases context rot. In long contexts, the accuracy of information retrieval and reasoning across distant sections can decline compared with shorter contexts. This change is described as a gradual difference in performance rather than a sharp break.

Anthropic explains that in the transformer architecture, each token can attend to other tokens throughout the context. As the context grows, the model's capacity to capture these relationships is strained. Anthropic also notes that short sequences are generally more common than long sequences in the training distributions in which models learn attention patterns.

Organizing prompt and tool content

Anthropic recommends clear and direct language for the system prompt. The balance it describes lies between rigid, complex hardcoded logic at one extreme and vague guidance that gives no concrete indication of the expected output at the other. Complex logic can increase the maintenance burden; overly general guidance can assume shared context.

Anthropic recommends organizing the prompt into separate sections and using XML tags or Markdown headings to separate them. Example section names include <background_information>, <instructions>, Tool guidance, and Output description. According to Anthropic, keeping the set of information needed to describe the expected behavior small does not necessarily mean it must be brief.

The testing process Anthropic recommends starts by trying a minimal prompt on the task. Explicit instructions and examples are added based on the types of errors seen in the initial tests. For examples, it recommends varied, representative examples that show the expected agent behavior rather than listing every possible edge case.

Tools allow the agent to work with its environment and receive additional context during execution. Anthropic recommends that tool outputs provide token-efficient information and that the purposes of tools be clear. It also specifies that input parameters should be defined descriptively and without room for interpretation. A tool set that is too broad or has overlapping functions can create uncertainty about which tool to use.

Retrieving information during execution

In the just-in-time approach described by Anthropic, the agent keeps lightweight references such as file paths, saved queries, and web links instead of processing all relevant data upfront. It then uses tools to load the data into the context during execution.

In this approach, the metadata of references can also provide guidance. Anthropic gives folder hierarchies and naming conventions as examples. As the agent explores, each interaction can provide context that affects the next decision. File size can offer a clue about complexity, while naming can offer a clue about purpose.

Turn this insight into action.

Use the mobile app to continue with guided workflows.

Anthropic describes this process as the gradual discovery of relevant context through exploration. As the agent navigates the file system, it can collect information in layers. It can also use note-taking methods to keep additional information for later use.

Exploration during execution has a cost: according to Anthropic, it is slower than retrieving precomputed data. Without suitable guidance, the agent can misuse tools, follow dead ends, or fail to find important information. Anthropic also describes a hybrid approach in which some data is retrieved upfront and the remaining exploration is left to the agent.

Anthropic explains that Claude Code uses this hybrid approach. CLAUDE.md files are included in the context upfront. The agent navigates its environment with tools such as glob and grep and retrieves files just-in-time. This allows information included in the initial context and information discovered during execution to be used together.

Compaction and notes for long tasks

Anthropic describes compaction as summarizing a conversation approaching the window limit and starting a new context window with the summary. In the Claude Code example, the message history is summarized; architectural decisions, unresolved errors, and implementation details are preserved, while repeated tool outputs or messages are discarded.

Which information is retained during compaction matters. Anthropic notes that excessive compression can cause the loss of critical details whose importance may only become apparent later. For compaction systems, it recommends first focusing on capturing relevant information, then improving the summary by removing unnecessary content. Clearing old tool results is also among the lighter operations described.

The Claude Platform documentation describes two separate operations under context editing: tool result clearing, which clears old tool results in agentic workflows, and thinking block clearing, which manages thinking blocks from previous turns. When thinking is used, input and output tokens, including thinking tokens, count toward the window. Whether thinking blocks from previous assistant turns remain in the window depends on the model.

When tool use and thinking are combined, the entire thinking block accompanying the relevant tool request is sent back unchanged along with the tool results. Anthropic notes that this includes the block's signature information. The API uses a cryptographic signature to verify the authenticity of the thinking block.

In structured note-taking, the agent writes persistent notes outside the context window and later brings those notes back into the window. Anthropic gives the example of an agent keeping a to-do list or NOTES.md. This arrangement allows progress, important context, and dependencies to be tracked in complex tasks.

Anthropic notes that the method can vary by task type. In its explanation, compaction is associated with maintaining the flow of conversation in tasks involving many back-and-forth messages, while note-taking is associated with iterative development with distinct stages. In a sub-agent architecture, the main agent coordinates the high-level plan while sub-agents in separate context windows carry out focused tasks and return summaries of their results.

In a sub-agent arrangement, detailed search context stays within the sub-agents. The main agent focuses on bringing together and analyzing the returned results. Anthropic associates this arrangement with complex research and analysis tasks where parallel exploration is useful.

Limits and information position

According to the Claude Platform documentation, if the input alone exceeds the model's context window, the API returns the invalid_request_error and prompt is too long error. In a request containing many images or large files, the request size limit may be reached before the token limit.

The Lost in the Middle study shows that the position of relevant information can affect performance on the tasks examined. The researchers used question answering across multiple texts and key-value retrieval tasks. Among the models examined, performance was often found to be higher when relevant information was at the beginning or end of the input and lower when it was in the middle of a long context.

In the study's controlled question-answering task, the input contains a question and texts; one of the texts contains the answer, while the others do not. The researchers examined the effect of position by changing the position of the text containing the answer, and context length by changing the number of texts that did not contain the answer. The study also used a setup in which no texts were provided and one in which only the text containing the answer was provided.

The same study conducted a separate retrieval task using key-value pairs in JSON format. The model was asked to return the value associated with a specific key. The researchers examined the effects of position and length in the task by changing the position of the relevant key and the number of irrelevant pairs. Some models completed this task without errors, while others struggled to find matching tokens in the middle of the input.

Ready to start?

Download the app and continue from your phone.

End of Entry