Skip to content

feat: retry a completion that overflows the context window - #120

Merged
gopaljigaur merged 2 commits into
mainfrom
feat/context-overflow
Oct 15, 2026
Merged

gopaljigaur merged 2 commits into
mainfrom
feat/context-overflow

Conversation

@gopaljigaur

@gopaljigaur gopaljigaur commented Oct 15, 2026 •

Copy link
Copy Markdown
Owner

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 with litellm.token_counter and tries each remedy at most once:

  1. A lower max_tokens: the room the input leaves (max_input_tokens less the request's tokens). It is used when it is below max_tokens, or below the model's max_output_tokens when max_tokens is unset, and above a thinking budget, which max_tokens has to exceed. With reasoning_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.
  2. Compaction, when AgentConfig.compaction is set: on another overflow after lowering, or when lowering doesn't fit. The Compacted event, the on_compaction hook, usage accounting and the autosave rewrite all work as in feat: summarize older messages near the model's input limit #118.
  3. Else the run ends with the error, as before.

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 compaction set, or after its first overflow otherwise), every later request gets the fitting max_tokens up front from the cached counts, so later steps don't each overflow first.

_ContextWindow now 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

Tests

Added to tests/test_compaction.py, with LiteLLM's mock_response="litellm.ContextWindowExceededError" and real token counting:

  • the lowered max_tokens, streamed and not;
  • later steps keeping it, and lowering up front with compaction set;
  • compaction after a failed lowering, and when there is no room to lower;
  • each remedy tried at most once on every path;
  • a thinking budget, explicit or from reasoning_effort, sending the overflow to compaction, or ending the run without it;
  • no retry for an unknown model or when no remedy applies.

uv run pytest, uv run pre-commit run --all-files and uv run mypy cyclops pass. The agents guide in docs/ and the website has a Context overflow section.

Closes #60

@gopaljigaur gopaljigaur left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. The lowered max_tokens isn't kept, so every later step sends a request that overflows first (reproduced: 6 requests for 4 steps).
  2. The single retry can go to lowering max_tokens when the count underestimates the input, and compaction is then never tried.
  3. A lowered max_tokens at or below the thinking budget turns the overflow into a different BadRequestError on Anthropic models.
  4. 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 _fit also raises. At most one extra completion per step.
  • #95. ContextWindowExceededError is a BadRequestError (400), which _retry_delay never 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 below max_tokens (or the model's max_output_tokens when 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"; the context_length_exceeded code isn't checked, so an OpenAI overflow worded otherwise surfaces as a plain BadRequestError and isn't retried. I did not check which wording each current OpenAI model returns.

Comment thread cyclops/core/run.py Resolved
Comment thread cyclops/core/run.py Resolved
Comment thread cyclops/core/compaction.py Resolved
Comment thread cyclops/core/run.py Resolved
@gopaljigaur
gopaljigaur force-pushed the feat/context-overflow branch 2 times, most recently from fed023d to 1e64293 Compare October 15, 2026 05:00
@gopaljigaur
gopaljigaur force-pushed the feat/context-overflow branch from 1e64293 to c16eefa Compare October 15, 2026 05:00

@gopaljigaur gopaljigaur left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. Later steps keep the lowered limit: fixed. Once the transcript is counted, max_tokens is lowered before each request. My earlier probe now sends (318, None), (318, 82), (342, 58): one overflow, then no more failed requests.
  2. Each remedy at most once: fixed. The loop allows at most three requests in a step, because each continue path sets a flag that blocks re-entry: lowering on not fit, compaction on not compacted. An overflow from the summary request still raises.
  3. Explicit thinking budget: fixed for an explicit thinking argument. The reasoning_effort case is still open (thread).
  4. 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.

Comment thread cyclops/core/compaction.py Resolved

@gopaljigaur gopaljigaur left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No findings.

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.
@gopaljigaur
gopaljigaur force-pushed the feat/context-overflow branch from 3e036dc to e984439 Compare October 15, 2026 05:44

@gopaljigaur gopaljigaur left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No findings.

@gopaljigaur
gopaljigaur changed the base branch from feat/compaction to main October 15, 2026 05:54
@gopaljigaur gopaljigaur reopened this Oct 15, 2026
@gopaljigaur
gopaljigaur merged commit 8b9ba97 into main Oct 15, 2026
9 checks passed
@gopaljigaur
gopaljigaur deleted the feat/context-overflow branch October 15, 2026 05:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Recover from context overflow

1 participant