Papa Programmer
Lesson 02 of 11

Context is a budget

8 min read

Optional

Big windows do not save you from sloppy budgets

Model providers love advertising 200,000-token and 1,000,000-token windows. It tempts engineers into skipping budgeting altogether: "Just toss all the docs and the whole chat history in — it fits."

Three things break the moment you do that in production:

  1. Input and output share the same bucket. Stuffing 190,000 TokenA small piece of text that a model reads or writes as one unit, such as a short word, part of a longer word or a punctuation mark. In English, one token is about four characters. of prompt into a 200,000-token window starves the reply — or triggers an HTTP 400 error mid-session.
  2. You pay for every wasted token on every turn. Latency climbs and API bills multiply 5x–10x while 80% of the prompt is stale chatter.
  3. Quality drops long before the window is full. Models degrade when relevant facts are diluted by tens of thousands of irrelevant tokens.

A Context budgetA plan that gives each part of a request, such as instructions, history and documents, a size limit, so the whole fits in the context window with room left for the reply. is simply code that decides ahead of time how many tokens each section is allowed to spend — instead of letting whichever array grew longest push out the user's question.

Spend the window in strict priority order

When space runs tight, something has to get cut. Make that an explicit product decision in code, never an accidental string slice.

  1. Reserve the replySubtract the maximum reply token budget before touching anything else.
  2. Fund fixed essentialsSystem instructions, output schema, and the user's current request always go in.
  3. Add ranked evidencePolicy docs, code chunks, or records — best match first — while budget remains.
  4. Add recent historyNewest turns first, up to the history cap.
  5. Drop the rest cleanlyStop adding once the budget hits zero; never cut essential parts to fit noise.
The order to fund every request

Different products weight steps three and four differently. A compliance bot funds retrieved policy docs before old chat; a conversational tutor might fund the last three turns first. What matters is that you chose the priority order explicitly.

Enforce the budget in code

Notice what happens in this small allocator when two policies compete for limited space. Because the more specific sale policy sits above the general returns policy in the priority list, it wins the remaining tokens. Flip those two entries and the model gets the wrong rule!

python
def est_tokens(text):
    return round(len(text.split()) * 1.3)

window = 60
reply_reserve = 15
fixed = {
    "rules": "Answer strictly from the policy. Be brief.",
    "request": "Can I return a discounted item bought 20 days ago?",
}
optional = [
    ("discount policy", "Discounted items are final sale after 14 days from delivery."),
    ("general returns", "Full-price items can be returned within 30 days for a refund."),
    ("old chat", "Customer asked about express shipping last week and was told 2 to 4 days."),
]

left = window - reply_reserve - sum(est_tokens(v) for v in fixed.values())
print("budget left for optional parts:", left)
for name, text in optional:
    cost = est_tokens(text)
    if cost <= left:
        left -= cost
        print(f"KEEP {name:16} ({cost} tok) -> {left} left")
    else:
        print(f"DROP {name:16} ({cost} tok) -> only {left} left")

Running this prints:

text
budget left for optional parts: 23
KEEP discount policy  (13 tok) -> 10 left
DROP general returns  (14 tok) -> only 10 left
DROP old chat         (18 tok) -> only 10 left

In production, swap est_tokens for the model's real tokeniser (tiktoken or your provider's token-count endpoint). The allocation pattern stays identical: reserve reply, pay fixed costs, walk optional items from highest value to lowest.

What to do when even the essentials overflow

Sometimes a user pastes a 40-page stack trace and even the fixed parts blow past your limit. Whatever you do, never blindly slice from the end with prompt[:max_chars] — that cuts off whatever came last, which is usually the user's actual question.

Pick one of four honest strategies instead:

  1. Compress the culprit. Extract only error lines from logs, or summarise older turns into a short state block.
  2. Split the job. Map-reduce large inputs across separate focused calls and merge in code.
  3. Step up to a bigger window only after verifying the extra context actually helps your evals.
  4. Refuse cleanly. Tell the user the pasted file is too large and show the limit.

Log where your tokens actually go

An unmonitored budget always drifts toward whichever subsystem is noisiest. Emit per-bucket token percentages in your request logs and glance at them weekly. Almost every team gets a shock the first time they chart a real production request:

  • Instructions8%
  • History55%
  • Retrieved documents25%
  • Tool results10%
  • Question2%
Share of a real 6,000-token support request, in percent

When chat history eats 55% of your prompt while the actual question is 2%, trimming or summarising history is an instant win — before you spend a single afternoon rewriting instructions or upgrading models.

Put hard numeric caps in config (for example: 500 tokens for instructions, 1,500 for history, 3,000 for retrieved chunks, 800 reserved for reply) and assert them in tests. Catching a bloated prompt in CI is infinitely cheaper than discovering it from a hallucinated customer reply.

Reserve the reply firstInput and output share one window — subtract reply headroom before funding anything else.
Priority order decides accuracyOptional blocks are funded top-down, so rank the highest-signal evidence first.
Log token share by bucketWhen history eats 55% of the prompt, trim history first instead of guessing.

Your reading position is saved

0%

0 of 11 complete

Contents

Learning tools