Expand description
Context-window management: bound what is sent to the model per request.
Sizes are estimates (characters / 4, rounded up, plus a few tokens of per-message framing). Real tokenizers differ by model and language (CJK text and code are usually far more tokens per character), so treat the budget as a coarse safety rail, not a guarantee that the endpoint will accept the request.
Trimming drops whole turns (a user message and everything the agent did in answer, tool calls and their results included) from the oldest end, so a tool call is never separated from its result. The system prompt and the tool definitions are always sent, and the latest turn is always kept, even if it alone exceeds the budget. The stored session is not modified; only the request is shortened.
What replaces the dropped turns in the system prompt is the compiled handoff
(crate::compact) and, under it, compiled_tail’s note about what was left out. The
budget itself uses a character heuristic, so it is a rail rather than a promise: the
handoff’s own size is bounded separately by [context] handoff_chars.
Structs§
- Trimmed
- What
trim_to_budgetdid. - Windows
- Which parts of the history a request keeps once it no longer fits: the first turn
(the ask, verbatim — it is the goal, and a summary of it is a guess), the last
protect_last_nturns (the live state), and nothing in between.
Constants§
- DEFAULT_
PROTECT_ LAST_ N - How many turns stay verbatim at the tail when a request has to be shortened. A turn is a user message and everything the agent did in answer, so twenty is a lot of live state.
Functions§
- assemble
- The request messages:
system(withnoteappended when given), the head of the history and then the tail, with the dropped middle left out. - compiled_
tail - The line under a compiled handoff: how much it stands in for, and that the handoff itself is what replaced it — “earlier conversation is not shown” would be a lie once it is.
- estimate_
message_ tokens - estimate_
text_ tokens - plan_
forced - Plan the three windows for one request. Pure arithmetic, no messages are built.
- plan_
windows - trim_
note - The note placed in the system prompt in place of dropped turns.
- trim_
to_ budget - Build the request messages:
system, then as many of the most recent turns ofhistoryas fit inbudget_tokens(afterfixed_tokens, e.g. the tool definitions). Abudget_tokensof 0 disables trimming. When turns are dropped the system message gets atrim_noteappended, so the model knows the conversation is incomplete.