Skip to content
echogeco
The model as a component · Tokens and sampling

Token budget planner

Implement the planner that packs prioritised sections into a request budget with an output reserve and refuses when the mandatory ones do not fit.

codemediumExercise · 3 min · 11 of 77
On this page

The request that fit in testing did not fit in production. The planner that decides what to send runs before every call, and it is fifteen lines.

The situation

A summariser concatenated whatever the user attached after a 4k system prompt and 3k of tool definitions, until a user attached forty documents and the request was rejected at the API. The team now describes every request as a list of sections — a name, a size in tokens, a priority — and wants one function to decide which sections go in.

Priority 0 is mandatory: the system prompt, the tool definitions, the user's question. Priority 1 and up are optional, 1 the most wanted. The request has a budget — the token count the engineer allows this feature, below the window, as tokens and the context window sets it — and a reserve held back for the reply, which counts against the same budget. Sections keep their prompt order when sent; the planner chooses, it never reorders and never sends part of a section. Sizes are counted with the tokenizer, not estimated, so the function can trust them.

The question

Implement the planner.

def solve(sections, budget, reserve):
    """sections: [(name, tokens, priority), ...] in prompt order; priority 0
    is mandatory, 1 is the most wanted optional section. budget is the tokens
    this request may use in total; reserve is held back for the output.
    Returns the names to send, in prompt order, or None when the mandatory
    sections alone do not fit in budget - reserve."""
SECTIONS = [("system", 4000, 0), ("tools", 3000, 0), ("history", 12000, 2),
            ("retrieved", 30000, 1), ("examples", 10000, 3)]

solve(SECTIONS, 64000, 6000)                      -> ["system", "tools", "history", "retrieved"]
solve([("sys", 5000, 0), ("doc", 100, 1)], 5500, 1000)  -> None

In the first example 64,000 − 6,000 = 58,000 is available; the mandatory 7,000 leaves 51,000; retrieved at priority 1 fits and leaves 21,000; history fits and leaves 9,000; examples at 10,000 does not. In the second, 5,500 − 1,000 = 4,500 is less than the 5,000 the mandatory section needs, so the planner refuses.

A strong answer · Rubric · Where answers go wrong · Solution

Write your answer first, then open