Repository navigation
feat: retry a completion that overflows the context window - #120
Conversation
gopaljigaur
left a comment
There was a problem hiding this comment.
Reviewed d378759 (stacked on #118's f37b258). No CI since the base isn't main; locally pytest passes on 3.14 and 3.10 (476 passed), mypy and pre-commit are clean. Of the seven new test cases, the five that retry fail on #118's code and pass here; the two without a remedy pass on both, as they should (they assert no retry). The confidentiality grep and the dash check find nothing.
Findings, each in its thread:
- The lowered
max_tokensisn't kept, so every later step sends a request that overflows first (reproduced: 6 requests for 4 steps). - The single retry can go to lowering
max_tokenswhen the count underestimates the input, and compaction is then never tried. - A lowered
max_tokensat or below the thinking budget turns the overflow into a differentBadRequestErroron Anthropic models. - After the rebase onto #110, the lazily built window counts the tools from the start of the run.
Checked and fine:
- No loop. The retry is outside the
try, so a second overflow raises; an overflow from the summary request inside_fitalso raises. At most one extra completion per step. - #95.
ContextWindowExceededErroris aBadRequestError(400), which_retry_delaynever retries, before or after the first delta; a streamed overflow comes before any chunk, so the streamed path retries the same way. - #98. An answer the lowered limit cuts ends with
stop_reason="max_tokens". - Arithmetic.
room = max_input_tokens - tokens(history), applied only when it is positive and belowmax_tokens(or the model'smax_output_tokenswhen unset). That matches how OpenAI and Anthropic count a request against the window. - LiteLLM 1.105.1 mapping (
exception_mapping_utils.py). Anthropic: "prompt is too long", "prompt: length" and "exceed context limit". Bedrock: "too many tokens", "Input is too long", "prompt is too long" and "Too many input tokens". Gemini and Vertex: "exceeds the maximum number of tokens allowed" and "400 Request payload size exceeds". OpenAI: matched only by the text "this model's maximum context length is"; thecontext_length_exceededcode isn't checked, so an OpenAI overflow worded otherwise surfaces as a plainBadRequestErrorand isn't retried. I did not check which wording each current OpenAI model returns.
f37b258 to
2e4284a
Compare
fed023d to
1e64293
Compare
90ded7b to
081b684
Compare
1e64293 to
c16eefa
Compare
gopaljigaur
left a comment
There was a problem hiding this comment.
Re-reviewed c16eefa (restacked on #118's 081b684). It has no CI, so I ran it locally: pytest passes on 3.14 and 3.10 (531 passed), and on a local merge with current main (542 passed). mypy and pre-commit are clean. The confidentiality grep and the dash check find nothing.
Earlier threads:
- Later steps keep the lowered limit: fixed. Once the transcript is counted,
max_tokensis lowered before each request. My earlier probe now sends(318, None), (318, 82), (342, 58): one overflow, then no more failed requests. - Each remedy at most once: fixed. The loop allows at most three requests in a step, because each
continuepath sets a flag that blocks re-entry: lowering onnot fit, compaction onnot compacted. An overflow from the summary request still raises. - Explicit thinking budget: fixed for an explicit
thinkingargument. Thereasoning_effortcase is still open (thread). - Tools loaded mid-run: fixed through
request().
New finding (thread): a thinking budget that LiteLLM derives from reasoning_effort isn't considered when max_tokens is lowered.
Also applies here: this branch carries #118's summary input budget bug unchanged (models whose output limit equals their input limit), and the base needs the same rebase onto main.
081b684 to
d51822c
Compare
c16eefa to
3e036dc
Compare
d51822c to
4aefaec
Compare
On LiteLLM's ContextWindowExceededError the run counts the request and tries each remedy at most once: a max_tokens that fits the room the input leaves, above any thinking budget, then compaction when it is set. Once the transcript is counted, later requests get that max_tokens up front.
LiteLLM turns reasoning_effort into a thinking budget of up to 16384 tokens for some providers, which max_tokens has to exceed. A request with an effort is lowered only above the largest of those budgets.
3e036dc to
e984439
Compare
Stacked on #118 (compaction); the base is
feat/compaction, so the diff shows only this change.What changed
When the provider rejects a request as too long for the context window (LiteLLM's
ContextWindowExceededError), the run counts the request withlitellm.token_counterand tries each remedy at most once:max_tokens: the room the input leaves (max_input_tokensless the request's tokens). It is used when it is belowmax_tokens, or below the model'smax_output_tokenswhenmax_tokensis unset, and above a thinking budget, whichmax_tokenshas to exceed. Withreasoning_effort, that is the largest budget LiteLLM makes of an effort (DEFAULT_REASONING_EFFORT_MAX_THINKING_BUDGET, 16384 by default), since mapping each effort exactly would mean copying a private, provider-specific LiteLLM function.AgentConfig.compactionis set: on another overflow after lowering, or when lowering doesn't fit. TheCompactedevent, theon_compactionhook, usage accounting and the autosave rewrite all work as in feat: summarize older messages near the model's input limit #118.No remedy is repeated, so there are at most two retries per completion and never a loop.
The lowered limit is kept. Once the run has counted its transcript (from the start with
compactionset, or after its first overflow otherwise), every later request gets the fittingmax_tokensup front from the cached counts, so later steps don't each overflow first._ContextWindownow works without compaction, which is passed per call, and knows the model's output limit. Without compaction it counts nothing until a request overflows. The step's completion moved into_RunLoop._complete, used for the first try and the retries, streamed or not.How it fits the existing handling
ContextWindowExceededErroris a 400, which_retry_delaynever retries, sonum_retriesand these retries don't stack. A router raises it after its own fallbacks.max_tokenscuts ends the run withstop_reason="max_tokens"andfinish_reason="length", as any cut answer does.Tests
Added to
tests/test_compaction.py, with LiteLLM'smock_response="litellm.ContextWindowExceededError"and real token counting:max_tokens, streamed and not;reasoning_effort, sending the overflow to compaction, or ending the run without it;uv run pytest,uv run pre-commit run --all-filesanduv run mypy cyclopspass. The agents guide indocs/and the website has a Context overflow section.Closes #60