Chapter 3. Context engineering

Learning objectives

  • Explain the meaning of the context window budget and context rot, and draw up a budget table for a single request.
  • Reason backward from the question to identify required information and include only the necessary materials.
  • Arrange long documents and questions in the order that maximizes quality, and attach sources and versions to documents.
  • Require evidence to be cited first from long documents, and verify that the citations sufficiently support the conclusion.
  • Explain the principles of conversation summarization, compaction, and retrieval augmentation, and diagnose retrieval failure and generation failure separately.
  • Place untrusted external content separately from instructions.

Introduction

An analyst at a consulting firm inserted five entire annual reports and asked for "three key industry changes this year." The context window was large enough, and the request was processed without error. However, one of the three points in the answer exaggerated a single footnote line in the appendix of the third report, while the changes emphasized in common across all five reports were missing. The analyst asked, "Why did it miss them when I included everything?" The answer lies within the question. It missed them precisely because everything was included. The model did not fabricate the footnote. Rather, it received hundreds of thousands of tokens without clues to distinguish what was important, and within the wide window, an irrelevant footnote merely competed for the same attention alongside key signals.

This chapter covers everything outside the instructions—namely, everything the model sees at once. Starting from why context is a finite resource, it covers how to draw up a budget table, select only the necessary information, handle document metadata and placement order, require citations first and use citation features, understand the principles of retrieval augmentation and diagnose failures, summarize and compact conversations, employ strategies for long-running agents, utilize prompt caching, and position untrusted content. Going deeper covers the choice between long windows and retrieval, tool design, and caveats when entrusting conversation state to the server.

Key concepts

Context is desk space

A wide desk allows you to spread out many documents, but as documents pile up, finding the single page you need right now becomes harder. Anthropic documentation explains the context window as "working memory," distinct from training data, which holds all text referenced when generating a response as well as the response itself, emphasizing that being large does not automatically make it better. Whether output is counted against the same window varies across vendors and models. This is due to context rot, where accuracy and recall degrade as tokens increase.

Anthropic's article on context engineering explains this in terms of an attention budget. In a Transformer, every token forms a relationship with every other token, meaning that for n tokens, the relationships grow to n², with each new token sharing the limited attention. Therefore, the goal is to find "the smallest possible set of high-signal tokens that maximizes the likelihood of the desired outcome"—that is, the minimum set of tokens densely packed with useful information. If prompt engineering is the work of polishing instructions, context engineering is the work of curating the entire set of tokens the model sees each time.

Note

The context window is merely the volume that can be read at one time; it has no bearing on the freshness of the model's knowledge. Even if the window grows larger, facts after training must still be provided through retrieval or attachments.

Context window budget table

To draw up a budget, you must first know what occupies the window. According to Anthropic documentation, the system prompt, all messages inside messages (including tool results, images, and documents), tool definitions, and the output (including thinking) generated by the model in that turn all enter the window. Thinking blocks from previous turns must not be left out either. Earlier models automatically stripped these, but models from Opus 4.5 and from Sonnet 4.6 onward, as well as Haiku 5.5, Fable, and Mythos, retain them by default, so they occupy the window just like any other input tokens. To clear them, use clear_thinking_20251015. Tokens read via prompt cache also occupy the window. Caching reduces charges, but it does not free up space in the window. Because token counts vary by language and script, do not estimate even Korean materials by character count; measure actual inputs with a token counting feature.

Component Budget question How to reduce
System instructions Is it a fixed cost repeated across every request? Pruning duplicate rules, caching
Tool definitions Are tools unneeded for this task loaded? Pruning tools, just-in-time loading
Examples Has the count been determined through experiments? Experiments on count in Chapter 2
Documents / retrieval results Are they the parts needed to answer the question? Curation, excerpts
Conversation history / tool results Does already digested content remain? Summarization, clearing old tool results
Output margin Is space left for the answer and thinking to fit? Setting max_tokens, split generation

The output margin is forgotten especially often. Even if the window is wide, there is a separate upper limit on the output of a single request; based on Anthropic documentation, even the latest models with a 1-million-token window have a maximum output of 128k (approximately 128,000) tokens per request. If you ask it to rewrite an entire long report, the input fits, but the output hits the upper limit and gets truncated, with stop_reason becoming max_tokens. Official documentation advises raising the limit or continuing generation. For tasks with long deliverables, divide them into sections from the beginning, and supply common criteria such as a glossary alongside each section.

Selecting and including only necessary information

Before inserting materials, reason backward from the question.

  1. Break the question down into sub-issues. "Risk factors for the second-half pricing strategy" splits into cost changes, competitor prices, and demand shifts.
  2. List the materials needed for each issue. Purchase unit price tables for cost changes, September price surveys for competitor prices.
  3. Distinguish essential from secondary materials. Materials without which the answer becomes incorrect versus materials that enrich the answer if present.
  4. Choose between full text and excerpts. Full text if phrasing is critical, such as clause comparisons; excerpts or summaries if background explanation.
  5. Remove secondary materials first if the budget is exceeded. Determine the removal order in advance.
  6. Flag issues lacking evidence. For issues without materials, inform the model as "no materials available" as well, preventing it from filling gaps with general knowledge.

The objective is not merely cost reduction. A context mixed with materials from other products, other years, or other departments becomes, in itself, the ingredient for incorrect answers.

Attaching sources, versions, and scopes of application to documents

If you insert only content, the model cannot know which document is up to date and which applies where. Attach metadata to each document.

<documents>
  <document index="1">
    <source>Travel Expense Regulations Article 4</source>
    <version>Amended 2026-07-01</version>
    <applies_to>Regular employees, domestic business trips</applies_to>
    <document_content>{{RULE_4}}</document_content>
  </document>
  <document index="2">
    <source>Travel Expense Regulations Article 4</source>
    <version>Amended 2025-01-01 (Repealed)</version>
    <applies_to>Applies only to travel expense settlements prior to 2026-06-30</applies_to>
    <document_content>{{RULE_4_OLD}}</document_content>
  </document>
</documents>

Anthropic guidelines recommend wrapping each document in <document> and separating content and metadata using child tags such as <document_content> and <source> when inserting multiple documents. Amendment dates, effective dates, and target audiences serve as grounds for the model to judge "which document it should follow." Without metadata, if old and new versions of the same clause are retrieved together, the model may blend both into its answer.

Metadata becomes even more critical when documents do not align. If simply told to "synthesize," the model will force conflicts into a single sentence or quietly discard one side. Instruct it to categorize and organize content confirmed in common, content with differing figures or definitions, and content present in only one side, while providing resolution rules. For example: "If they are old and new versions of the same clause, follow the version in effect on the reference date of the question." For conflicts that cannot be resolved by rules, instruct it not to resolve them, but to report: "Conflict: Document 1 and Document 3 differ."

Long documents at the front, questions at the end

Anthropic recommends placing long documents before questions, instructions, and examples in long inputs exceeding 20,000 tokens. In official testing, placing questions at the end improved response quality by up to 30%, especially in complex multi-document inputs. Gemini guides also recommend placing specific questions at the very end and using phrasing that links back to preceding materials, such as "Based on the above information," while OpenAI guides cite structures that place contexts that change with each request toward the end. The same applies to images. Anthropic documentation guides placing images before text and, if there are multiple images, labeling them such as "Image 1:" and "Image 2:" to refer to them by name.

Official recommendations are a starting point, not an immutable law for every task. Treat the structure of placing core behavioral constraints at the front, long materials behind them, and specific questions at the very end as the default, and verify critical tasks by comparing with versions where placement is altered.

Require citations first

When eliciting answers from long documents, the greatest risk is the mixing in of content not present in the documents. Official guides recommend having the model cite relevant portions first before undertaking the task. The model focuses on relevant content while selecting citations, and humans can directly cross-check citations against the source text. Anthropic's documentation on reducing hallucinations adds two things: having it state that there are no relevant citations if none exist, and having it find supporting citations for each claim after drafting an answer, retracting claims for which no citations could be found.

1. Transcribe original sentences relevant to the question verbatim inside <quotes>, numbered.
   If there are no relevant sentences, write only "No relevant citations."
2. Answer inside <answer> based only on the content in <quotes>, and attach citation numbers to each claim.
3. Exclude from the answer any claim that cannot be assigned a citation number.

The presence of citations does not mean evidence is sufficient. There are three additional checks to make.

Check Question Method
Match Is the citation verbatim identical to the source text? Automated cross-check via source string search
Relevance Does the citation actually support that claim? Human verification of drawn samples
Sufficiency Are exception clauses or counter-evidence not omitted? Separately asking, "Are there clauses that would overturn this conclusion?"

Citation features and search result blocks

Instead of eliciting citations via prompts, you can also use vendor citation features. Anthropic's Citations feature, when citations are enabled on a document, returns text blocks of cited portions with source locations attached (character offsets for plain text, page numbers for PDFs, block numbers for custom blocks). Whether claims appear without citations is checked separately. The official documentation cites three advantages: cited text (cited_text) is not counted as output tokens; because the API parses citations, valid locations pointing to provided documents are guaranteed; and in internal evaluations, it cited more relevant sentences than prompt-based methods.

Plain text and PDFs are cited at the sentence level; to define units directly, such as transcripts or bullet points, pass them as custom blocks. This feature cannot be used alongside structured outputs, so including documents with citations enabled and output_config.format in a single request results in a 400 error. If both are required, split the calls.

For custom retrieval results, inserting them as Anthropic's search_result blocks (source, title, content) allows you to receive citations with attached sources just like web search. Gemini's Google Search grounding lets the model determine on its own whether search is needed, conduct searches, and attach source URLs to segments of the response. Use search grounding for frequently updated public information and internal retrieval results for internal materials; when using both together, ensure each sentence in the answer clearly distinguishes which source serves as its evidence.

Principles of retrieval augmentation

Retrieval-augmented generation (RAG) is a method of retrieving and inserting materials unknown to the model at the time of the question. It is like a librarian listening to a question, selecting just a few relevant books, and placing them on the desk.

Step Action Common mistake
1. Indexing Split documents into pieces (chunks) and store them for retrieval Chunks lose their original context
2. Query generation Extract keywords and conditions from the question Searching the original question verbatim
3. Retrieval Find candidate chunks in the repository Using only semantic search, missing exact strings
4. Reranking and selection Re-rank by relevance and retain only top candidates Inserting everything because the window has spare capacity
5. Placement Attach source tags toward the front, question at the end Concatenating without document boundaries
6. Generation Require citations first before answering Letting it answer without indicating evidence

Anthropic's article on Contextual Retrieval addresses the issue at Step 1. When documents are chunked, a piece like "Revenue grew by 3% from the previous quarter" loses which company and which period it refers to. The solution is to attach a short explanation (typically 50–100 tokens) referencing the entire document to each chunk before embedding, and build a BM25 index with the same text. Embedding retrieval is strong on semantically similar texts but weak on search queries requiring exact character matches such as error codes or model names, a weakness compensated for by word-matching-based BM25. In experiments from the article, retrieval failure rates dropped by 35% with contextual embeddings alone, by 49% when adding BM25, and by 67% when adding reranking.

Nor does every problem require retrieval. The same article states that if the knowledge base is under 200,000 tokens, one can forego building a retrieval step, insert all materials, and use prompt caching to reduce cost and latency. If materials are small, the simplest method may be the best method.

Diagnosing retrieval failure and generation failure separately

When RAG produces an incorrect answer, modifying the prompt first is a common mistake. First, distinguish at which stage the failure occurred.

  1. Was the evidence for the correct answer in the repository? If not, it is a data problem.
  2. Was the evidence for the correct answer ranked high in retrieval results? If not, it is a retrieval problem. Modify query generation, indexing, or retrieval methods.
  3. Did the evidence enter the context? If it was pruned during reranking or selection, adjust selection criteria.
  4. Did the answer turn out wrong despite the evidence being included? Only then do you adjust the generation stage—namely instructions, placement, and citation methods.

This determination requires an evaluation set where documents serving as evidence for correct answers are paired in advance with each question. One application of evaluation sets covered in Chapter 5 is precisely this.

Conversation summarization and compaction

When conversations grow long, the history must be reduced. The most common method is summarizing the earlier portions, but summarization loses detailed wording. In particular, passing through multiple rounds of summarization blurs figures, dates, and conditions into expressions such as "appropriate level" or "in the near future." Therefore, design the summary not as a "plot summary," but as a "work state record."

<conversation_state>
  Confirmed terms: Delivery quantity 1,200 units, delivery date November 14, packaging individual polybag
  Unresolved questions: Logo print color (client to reply after reviewing proof)
  Decision history: Unit price negotiation completed on October 20 (Quote Q-2026-118)
  Next action: Finalize printing specifications upon receipt of proof feedback
</conversation_state>

Confirmed values are kept in their original expressions, decisions are distinguished from proposals, and each item can be traced back to its origin. The flow of conversation is maintained by preserving the most recent few turns in full text.

You can also use vendor features. Anthropic provides server-side compaction in beta, replacing older turns with a summary written by Claude on the server and allowing the conversation to continue. Initially, there was only the threshold method, which compacted when input tokens exceeded a baseline value. On September 14, 2026, on-demand compaction, where the application determines the timing, was added, and official documentation recommends using on-demand compaction wherever possible. If default summarization misses necessary information, write custom summarization instructions directly, or, for finer control, use context editing features to clear older tool results or thinking blocks according to rules. The business owner determines what must be preserved.

Context strategies for long-running agents

Agents calling tools for hours quickly fill up their context. The techniques introduced in Anthropic's article and their matching scenarios are as follows:

Technique Action Matching task
Compaction Start afresh with a summary when the window is nearly full Tasks with heavy back-and-forth where flow is critical
Clearing tool results Remove raw text of older tool results already incorporated The safest and lightest compaction
Structured notes Record progress in notes outside the window and load to read later Long-term tasks with distinct stages
Subagents Delegate focused tasks to subagents with clean windows and receive only compressed summaries (usually 1,000–2,000 tokens) Research and analysis where parallel exploration is beneficial
Just-in-time loading Hold only lightweight identifiers such as file paths, saved queries, and links, loading them via tools when needed Tasks where data is large and changes frequently

Just-in-time loading is slower, but it avoids stale index issues and keeps the context lightweight. There are also hybrid methods where some materials are inserted in advance and the rest are retrieved when needed.

Prompt caching and placement

Prompt caching is a feature that stores prefixes repeated across requests and reuses them in subsequent requests. The core point is that the prefix must be identical down to every single character. Anthropic constructs the prefix in the order of tools, system, and messages, requiring 100% identity up to the cache breakpoint for a hit. OpenAI also enables caching by default on supported models, reusing it only when the entire rendered prefix matches.

Principle Reason
Static content (tool definitions, system instructions, reference materials, examples) at the front Creates an identical prefix across requests
Dynamic content (request timestamp, user-specific information, questions) at the back If dynamic values are placed at the front, everything following is recalculated
Avoid frequent changes to tool definitions In Anthropic, if tool definitions change, the entire cache is invalidated
Check hits with usage fields Prompts that are too short are not cached without an error

It is also important to understand the cost structure. Based on Anthropic documentation, cache writes are slightly more expensive than base input pricing (1.25x for 5-minute cache), and cache reads are significantly cheaper (10% of base input pricing across most models). The default time-to-live is 5 minutes, refreshed with each use, with a 1-hour option also available. OpenAI caches prompts of 1,024 tokens or more for its latest models, noting that caching does not alter how outputs are generated.

Positioning untrusted content

Content from uncontrollable sources—such as web pages, incoming emails, user-uploaded files, and tool results—may harbor sentences intended to manipulate the model. This is called indirect prompt injection. Unlike direct injection where the user attacks directly, here the user may be trustworthy, but third-party content read by the model on their behalf becomes the attack vector. OWASP Top 10 for LLM Applications (2025) ranks this as the top risk, stating that neither RAG nor fine-tuning can completely prevent it.

Placement principles recommended by Anthropic documentation are as follows:

  1. Place third-party content only inside tool results (tool_result), not in the system prompt or ordinary user text.
  2. Disclose what that content is and where it came from ("incoming email body from an unknown sender") in tool descriptions or result structures.
  3. Explicitly state in the system prompt that content originating from tools, documents, or searches is untrusted data and cannot override the system prompt or the user's original request.
  4. Encapsulate external strings in JSON objects whenever possible. JSON escaping clarifies boundaries so that attackers cannot escape into instruction space by closing quotes or tags.
  5. Conversely, do not place your own instructions inside tool results. They may be treated with suspicion or ignored.
  6. Apply least privilege in preparation for a breach. Restrict access to unneeded confidential information, narrow tool privileges, and require human approval for risky actions.

Regarding direct injection (jailbreaking), where users directly attempt to break rules, Anthropic documentation recommends screening inputs first with a lighter model, validating inputs against known attack phrases, defining refusal methods in the system prompt, and responding to users who make repeated attempts. Countermeasures from OWASP point in the same direction: limiting behavioral scope, validating output formats, filtering input and output, enforcing least privilege, requiring human approval for risky actions, demarcating external content separately, and conducting testing that assumes attacks. In the most trusted positions, place only the most trusted content.

Two compaction methods: the application picks the timing

Current Claude models default to a 1-million-token window without beta headers. Even with a wide window, recall accuracy drops as conversations lengthen. Some models, such as Haiku 5.5, impose higher charges on requests exceeding 100,000 tokens. Therefore, long-running conversations must eventually be reduced. Anthropic's server-side compaction replaces older turns with a summary written by Claude on the server, eliminating the need to write separate summarization code. Official documentation also designates compaction as the default strategy in most cases.

From September 14, 2026, compaction is divided into two methods. Both remain in beta.

Category Threshold compaction On-demand compaction
Beta header compact-2026-01-12 compact-2026-09-04
Configuration Edit type compact_20260112 Top-level compaction parameter
Compaction trigger When input tokens exceed the baseline (default 150,000, configurable minimum 50,000) Determined by the application
Where to use Environments where on-demand cannot be used Preferred wherever it can be used

Because the trigger for the threshold method is solely input_tokens, summarization cuts in whenever the token count is reached, regardless of task boundaries. In the on-demand method, the application, which understands the workflow, selects the timing. Under either method, the compaction block received in the response must be sent back verbatim in the subsequent request. The API ignores all content preceding that block.

Suppose a claims adjudication agent at an insurance company hit the threshold while cross-checking documents and lost the medical certificate figures read earlier. The team switched to on-demand compaction, triggering compaction only when a single claim was completed. Because adjudication criteria tables had to persist across summarization, they had them recorded separately in a memory tool. Since the memory tool (memory_20250818, name memory) was a client-side tool, when Claude requested file operations under /memories, the application handled execution. Compaction kept the active window small, while memory preserved what could not be omitted from the summary.

Context editing considers both what to clear and what cache breaks

While compaction summarizes older turns in their entirety, context editing selectively clears only specified kinds of content from the history. Attach the beta header context-management-2025-06-27 and specify strategies in the edits array.

Strategy What it clears Key points to remember
clear_tool_uses_20250919 Older tool results By default, it clears results only. To clear invocation parameters as well, set clear_tool_inputs to true
clear_thinking_20251015 Thinking blocks from previous turns When used alongside other strategies, place at the front of the edits array

There is a reason a separate thinking block strategy exists. Earlier models automatically stripped thinking blocks from previous turns. That is no longer the case. Models from Opus 4.5, from Sonnet 4.6 onward, Haiku 5.5, Fable, and Mythos retain thinking blocks by default, counting them in the window like other input tokens. For an agent that engages in extensive thinking, a substantial portion of the history consists of thinking blocks.

Clearing comes at a price. If the front portion of the history changes, prompt caching will no longer match from that point onward. clear_at_least is the minimum amount to clear at one time. Setting this value prevents breaking the cache just to clear a trivial amount.

A log analysis agent for an operations team called retrieval tools dozens of times, receiving thousands of log lines with each result. The engineer used clear_tool_uses_20250919 with default settings, clearing only results while preserving invocation inputs. Because the conditions and query targets remained in the history, the agent did not repeat identical searches. Only the heavy raw log text was removed from the window. When paired with a memory tool, Claude received an automated warning as it approached the clearing threshold, allowing it to move critical information to memory before being cleared.

Keeping outside the window and calling when needed: tool search and progress files

Just-in-time loading is not a principle applied only to materials. The same holds true for tools and sessions. Keep only what is necessary for current judgment inside the window, leave the rest outside, and load them as needed.

An agent with dozens of tools spends non-trivial token counts on tool definitions alone on every request. Claude's tool search tool avoids loading all definitions in advance, locating and loading only the 3–5 needed for that specific request. Based on official documentation, the context occupied by tool definitions is typically reduced by more than 85%. The cache benefit is also substantial. In Anthropic, modifying tool definitions invalidates the entire prompt cache. Tool search keeps tools to be loaded later outside the prefix, leaving the prefix intact and preserving the cache.

The same principle applies across session boundaries. Long-running tasks eventually split across multiple sessions, and new sessions start without memory of previous sessions. Anthropic's article on long-running agents (2025-11-26) recommends using the first session as an initialization session. Once this session creates progress files and feature lists, subsequent sessions read from those files and continue the work. Claude Code likewise starts with a new context window for each session. Two mechanisms bridge knowledge across sessions: CLAUDE.md and auto memory.

Suppose a coding agent was tasked with migrating 40 screens of an internal approval app to a new framework. In the first session, it did not modify a single line of code. It listed screens to migrate in a feature list, created a progress file, and ended. From the next session onward, it checked the last completed screen in the progress file and tackled the next screen immediately. Even if the session was interrupted, all that vanished was the in-window conversation; the task state remained in the file.

Going deeper

Put everything in a long window, or search?

As windows have grown larger, questions like “Can’t we just put everything in without searching?” have increased. The answer depends on the task. Google’s long-context documentation explains that while tests that retrieve a single piece of information show high accuracy, the same accuracy is not achieved when multiple pieces of information must be found simultaneously. In addition, input token costs are incurred again every time a question is sent, and longer inputs also increase latency to the first token.

Situation Preferred choice
Data is small (e.g., less than 200,000 tokens) and rarely changes, with repeated questions on the same data Include entirely and cache
Data is large or changes frequently Retrieval augmentation
Information from multiple locations must be gathered for a single question Search + citation, or split the question and ask multiple times
The flow or structure of the entire document must be examined (overall summary, consistency review) Include entirely, processing by section if necessary
Must be found by exact string (number, code) Include word-matching methods such as BM25 in search

Tool design is also context design

To an agent, tools are hands and eyes. Because tool definitions and tool results also occupy context, how tools are designed determines the quality of the context. An Anthropic article states that tools should return token-efficient information and have minimal overlap in functionality, pointing out that “if a human engineer cannot definitively say which tool to use, an agent cannot do any better.”

Anthropic’s tool definition documentation states that writing very detailed tool descriptions of at least three or four sentences for each tool is the most important factor in tool performance. You specify what it does, when to use it and when not to use it, the meaning of parameters, and the information it does not return. Similar operations are grouped into a single tool with an action parameter, and prefixed with the service name if spanning multiple services. In tool results, include only the fields and meaningful identifiers needed for the next decision. Bloated results waste context.

When entrusting conversation state to the server

You can also entrust conversation history to vendor servers. The OpenAI Responses API chains responses with previous_response_id or stores conversations as long-lived objects with the Conversations API. According to official documentation, even when chained with previous_response_id, input tokens from previous responses are billed again as input costs; stored responses are retained by default for 30 days, and setting store to false prevents the response object from being stored. However, since separate retention policies exist, such as abuse monitoring logs (default maximum of 30 days), check the data policy documentation as well. Conversation objects do not follow this 30-day limit. Choose the method according to your cost budget and retention regulations.

When using reasoning models together with tools, pass along traces of previous reasoning as well. OpenAI strongly recommends returning reasoning items together after a function call, and instructs passing encrypted reasoning content (encrypted_content) in non-storage mode. Anthropic recommends appending the assistant turn, including thought blocks, exactly as returned by the API. In models after Claude 5.1, this is a rule. History must only be appended, and thought blocks remain valid only if the content sent before them remains unchanged in the next request. Modifying previous messages or recreating system or tools causes an error or discards the block. Opus 5.5 rejects the configuration that turns off thinking with a 400 error. In this model, modifying the top-level system invalidates not only the cache but also all previous thought blocks. If you need to change rules, do not rewrite the history; instead, append it like the in-conversation system messages in Chapter 1.

At work

Blue Logistics: A Q&A bot searching through 400 regulations

Logistics company 'Blue Logistics' operated a Q&A bot that searched 400 internal regulation documents to provide answers. Employees had three complaints. While answers sounded plausible, it was impossible to tell which regulation they came from; vacation regulations were mixed into answers for business trip expense questions; and when asking about the lodging expense limit revised in July, the old amount was sometimes returned.

Manager Moon, the person in charge, first gathered 50 failed questions and classified them by stage. There were 3 questions where the evidence for the correct answer was not in the repository. There were 14 questions where the evidence for the correct answer was not within the top 30 search results, most of which were questions asking by article number, such as “Article 4-2.” For the remaining 33 questions, the answers were incorrect even though the evidence was included in the context. Manager Moon also examined the existing structure. The question was at the very top, followed by 30 search results attached one after another without boundary markers, ending with “Answer.”

Based on the diagnosis, different remedies were prescribed for each stage:

  1. Data. The three questions without evidence involved content that existed only on the announcement board, not in the regulations. The relevant announcements were transferred to the department in charge of regulations to be incorporated into the regulations.
  2. Search. For questions searching with exact strings such as article numbers and regulation titles, exact word-matching search was added to semantic search. In the query generation stage, the business category of the question (business trip, vacation, procurement) was determined first to be used as a search filter.
  3. Filtering. Candidates were reranked by relevance, leaving only the top 5.
  4. Placement and metadata. For each retained regulation, a <document> tag, regulation number, revision date, and target scope were attached and placed at the front, while the question was moved to the very end. Repealed versions were excluded from the default search, but if a past date was present in the question, the version effective at that time was included.
  5. Generation. Before answering, the model was instructed to copy relevant provisions into <quotes>, and to write the regulation number and revision date at the end of the answer. When both new and old versions of the same article were included, it was instructed to follow the version matching the base date of the question, and to show both versions if it could not be determined.

The suggestion that “since the window is spacious, let’s increase search results to 50” was not accepted. A significant portion of the failures occurred because irrelevant regulations were mixed in, and increasing them would only amplify that problem. After the improvements, when the same 50 questions were run again, most were answered correctly along with the evidence for the correct answer, and input tokens were reduced to about a quarter of the previous level. Employees became able to find the original text immediately using the regulation numbers attached to the answers.

New Light Daily: Three years of campaign pledges in one article

Reporter Jang from the data team at the local newspaper 'New Light Daily' prepared an article ahead of the mayoral election comparing how the pledges of four candidates had changed over the past three years. The materials consisted of press releases, debate transcripts, pledge book PDFs, and city council minutes, totaling millions of tokens. Initially, all materials were inserted candidate by candidate with the instruction to “summarize pledge changes,” but the results were inconsistent. For some candidates, withdrawn pledges were summarized as if they were current pledges, and remarks from other candidates were mixed in.

Reporter Jang worked backward from the questions the article needed to answer. What the article had to answer was: “What is each candidate’s current pledge by sector, and when did what change?” The sectors were four: transportation, housing, care, and finance. Therefore, the unit of work was divided into “one candidate × one sector.” A budget table was drawn up for each of the sixteen tasks.

Component Content Principle
Fixed instructions Article criteria, citation rules, output format Kept identical across all tasks for caching
Materials Only statements and documents of the relevant candidate and sector Metadata for date, source, and speaker required
Question Current pledge, time of change, details of change Placed at the very end
Output headroom One summary table per sector Table format, citation numbers required

Selecting materials was done through search. After searching by candidate name and sector keywords, only materials where the speaker was that candidate were retained. Transcripts were cut into statement units, with speaker, date, and event name attached. The issue of other candidates' remarks being mixed in disappeared thanks to this metadata.

In the generation stage, citations were received first. The model transcribed pledge sentences verbatim from the original text, arranged them in chronological order, and marked points of departure from previous statements. Parts requiring interpretation, such as whether a pledge had been withdrawn, were left as “verification needed.” Reporter Jang asked a colleague for a script to mechanically cross-check citations against the original text, filtering out all citations with differing wording.

In the final consolidation stage, only the sixteen summary tables were included instead of the source materials to create a comparison table by sector. In the progress notes written for each task, verified citations and remaining items to verify were recorded, ensuring that progress was not lost even when working across several days.

Discarded alternatives were also recorded. The approach of inserting all materials at once and generating a comparison table directly carried a high risk of missing pledges because the task required finding multiple pieces of information simultaneously. The approach of summarizing the materials and then comparing those summaries carried a risk of blurring dates and numbers, so the approach of accumulating original-text citations was chosen instead of summaries. The article was published with sources and dates attached to each pledge sentence, and the supporting evidence needed to answer reader inquiries remained intact.

Common mistakes

  • A large window makes it advantageous to include everything. Due to context rot, irrelevant information instead degrades quality and increases cost and latency.
  • A wide window allows for long output as well. Outputs have a separate upper limit. Long deliverables are received by dividing them into sections.
  • Writing the question first lets the model know the objective. For long inputs, placing documents at the front and the question at the end is the officially recommended arrangement. Place key behavioral constraints at the front.
  • If RAG is wrong, fix the prompt. First distinguish which stage failed among data, retrieval, selection, and generation.
  • Summarization causes no loss of information. Summaries flatten numbers and conditions. Retain finalized values verbatim as a state record.
  • External materials are better reflected when placed in the system prompt. Placing untrusted content in the most trusted position increases the risk of injection.
  • Enabling caching automatically saves costs. If changing values are at the front, everything behind them is recalculated every time, resulting in almost no cache hits. Move static content to the front and variables to the back.

Summary at a glance

Topic What to remember
Context rot As tokens increase, recall and accuracy degrade. The goal is a small set of high-signal tokens
Budget table Instructions, tools, examples, materials, history, and output buffer. Cached tokens also occupy the window
Selection Break questions down into key issues to determine required materials in reverse, and determine the removal order in advance
Placement Core constraints at the front, long materials behind them, questions at the end. Images before text
Citations Cite first, state if absent, withdraw claims lacking citations. Verify exact match, relevance, and sufficiency
RAG Contextual chunk enrichment, semantic search + keyword match, reranking. Small materials in full + caching
Summarization State records rather than narratives. Finalized values verbatim
Caching Hits require the prefix to match by every single character. Static content at the front, variables at the back
External content Inside tool results, source attribution, JSON encoding, least privilege, human approval for risky actions

Check the official docs

Self-check

3-1. Define context rot in one sentence, and provide two reasons to oppose the proposal: "Since the window is large, let's include all related materials."

3-2. Write five components that must be included in the context budget table for a single request, and state which one is most frequently forgotten and the symptom that occurs when it is forgotten.

3-3. Write the skeleton of a prompt using tags that includes two 60-page audit reports and one question. Attach the source and creation date to each document, and ensure citations are requested first.

3-4. Write four questions in order of verification that isolate the failure stage when a retrieval-augmented answer is incorrect, and explain in one sentence why instructions are modified only at the final question.

3-5. Due to a change in personnel, an event planning conversation held with a model over several weeks must be transferred to a new conversation for a new person in charge. List three types of information that must be preserved verbatim in the record to be transferred, and provide an example of the format for that record.

3-6. An agent uses the same long instructions, but for each request, adds or removes part of the tool list depending on the user's permission level. Explain what penalty occurs from the perspective of prompt caching, and suggest one method to reduce this penalty while maintaining permission differences.

3-7. You are building a research agent that reads competitor websites to compile pricing tables. State where and in what format to place the retrieved web page body in the prompt, and write two safeguards each to mitigate damage if compromised by hidden instructions inside the page.

Hands-on tasks

Exercise

Long document placement A/B experiment (60 minutes)

  1. Prepare two public reports of 30 pages or more.
  2. Create five questions that can be answered only by comparing both documents.
  3. For Version A, write the question at the very top and attach the two documents below it. For Version B, place the documents at the front with document-specific tags, sources, and creation dates, request citations first, and place the question at the end.
  4. Cross-check every single claim in each answer against the original text to count the proportion of claims with evidence. For Version B, also verify whether citations match the original text verbatim.

Done when: The proportion of claims with evidence across both versions, the number of citations differing from the original text, and the time spent on review are compared in a table.

Exercise

Creating a context budget table and state record (45 minutes)

  1. Choose a recent long work-related conversation with a model (20 turns or more is recommended).
  2. Write a state record by dividing the essential information needed to continue that conversation into "finalized conditions, unresolved questions, decision history, and next actions." Transfer finalized values verbatim in their original phrasing.
  3. Place side by side the result of having the model freely summarize the same conversation and your own state record.
  4. Start two new conversations. Continue one with the free-form summary and the other with the state record, asking the same three follow-up questions in each.

Done when: The count of finalized conditions accurately maintained in both methods is recorded in a table, and if any information was blurred in the free-form summary, one example of it is documented.