WRITE · TRACE · UNDERSTAND

Reserve output space before adding retrieval context

Implement pack_context(chunks,window,fixed,output).

Read lesson: Reserve output space before adding retrieval context →

Your experiment

Implement pack_context(chunks,window,fixed,output). chunks are (id,token_count), already ranked. Return admitted ids and total used context tokens. Skip oversized chunks, deduplicate admitted ids, require nonnegative integer counts/budgets and fixed+output<=window.

Python runs in your browser. Your draft stays on this device.

What to look for

The allocator enforces the supplied accounting contract. Incorrect tokenizer counts or omitted tool/message formatting overhead can still overflow a model context window, so the final serialized request needs a separate budget check.

Watch your code work

Ready to experiment

Write a solution or load the worked answer, then choose Trace & check.

Step through arrays, variables and training curves produced by your own Python.

About this algorithm

How Reserve output space before adding retrieval context works

The idea

A model's context window is shared by everything in one request: the system prompt and question, the retrieved chunks, and the answer the model still has to write. pack_context subtracts the fixed part and the reserved output space first, and only what is left may be spent on retrieved context.

Reserving the output before packing is the point. If context fills the window, the answer is cut short or the request is rejected. The chunks arrive already ranked, so the function walks them in order and admits each one that still fits. A chunk that is too large is skipped without ending the loop, so smaller chunks further down can still use the space. An id is admitted at most once.

How it works

  1. Check that window, fixed and output are non-negative integers and that fixed + output <= window.
  2. Compute remaining = window - fixed - output, the only space that context may use.
  3. Walk the ranked (id, token_count) pairs in order, rejecting any count that is not a non-negative integer.
  4. Admit a chunk when its id is not in seen and used + count <= remaining, then add its count to used.
  5. Skip a chunk that does not fit and keep going, so a later, smaller chunk can still be admitted.
  6. Return the admitted ids in rank order together with used.

What it costs

Time
O(n)
Space
O(n)

One pass over the n ranked chunks with a set lookup for each; counting the tokens of each chunk happens before this function is called.

Where it is used

  • Anthropic's Messages API requires a max_tokens value, and the input tokens plus that output allowance must fit inside the model's context window.
  • OpenAI's tiktoken library counts tokens so that an application can measure a prompt before sending it.
  • LangChain's trim_messages utility cuts a chat history down to a max_tokens budget using a token counter you supply.

Watch out for

  • Filling the whole window with context and leaving no room for the answer, which truncates the output or fails the request.
  • Using break at the first chunk that does not fit, which wastes space that a smaller, lower-ranked chunk could fill.
  • Charging a duplicate id twice: each id is admitted once, so a second copy must add nothing to used.