Skip to main content

Module context

Module context 

Source
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_budget did.
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_n turns (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 (with note appended 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 of history as fit in budget_tokens (after fixed_tokens, e.g. the tool definitions). A budget_tokens of 0 disables trimming. When turns are dropped the system message gets a trim_note appended, so the model knows the conversation is incomplete.