Skip to content

Classify Anthropic's "input length and max_tokens exceed context limit" as ContextLengthExceededError - #907

Merged
crmne merged 1 commit into
crmne:mainfrom
frostmark:fix/anthropic-context-limit-pattern
Sep 3, 2026
Merged

crmne merged 1 commit into
crmne:mainfrom
frostmark:fix/anthropic-context-limit-pattern

Conversation

@frostmark

@frostmark frostmark commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

What this does

Adds /context limit/i to ErrorMiddleware::CONTEXT_LENGTH_PATTERNS so Anthropic's second context-window error raises RubyLLM::ContextLengthExceededError instead of BadRequestError:

{"type":"error","error":{"type":"invalid_request_error","message":"input length and max_tokens exceed context limit: 900000 + 128000 > 1000000"}}

Closes #906.

Why

Anthropic checks input + max_tokens <= context_window before it checks the prompt alone, and the chat payload always sends max_tokens (model.max_tokens || 4096, 128k for claude-opus-4-8). So on a long-context model this is the first error a growing conversation hits, at roughly context_window - max_output_tokens input tokens. The "prompt is too long" pattern from #755 only fires later, once the prompt alone no longer fits. Applications rescuing ContextLengthExceededError for Anthropic therefore missed the case that actually occurs.

Type of change

  • Bug fix

Scope check

  • I read the Contributing Guide
  • This aligns with RubyLLM's focus on LLM communication
  • This isn't application-specific logic that belongs in user code
  • This benefits most users, not just my specific use case

Quality check

  • I ran bundle exec rspec spec/ruby_llm/error_middleware_spec.rb spec/ruby_llm/error_spec.rb (48 examples, 0 failures) and bundle exec rubocop on the touched files
  • I added a spec for the new phrasing next to the existing "prompt is too long" one
  • overcommit --run — not run locally (mysql2 does not build on this machine); RuboCop and the affected specs were run by hand

AI-generated code

  • I used AI tools to help write this code
  • I have reviewed and understand all generated code (required if above is checked)

API changes

  • Breaking change
  • New public methods/classes
  • Changed method signatures

Related issues

#906 (this), #755 (the earlier "prompt is too long" half). The streaming-status half of #906, where 1.16.0's Anthropic adapter labels every failure a 500, is already fixed on main by failed_http_status; this PR only adds the missing pattern.

…t" as ContextLengthExceededError

Anthropic checks input + max_tokens against the context window before it
checks the prompt alone, and the chat payload always carries max_tokens,
so on a long-context model this is the first error a growing conversation
hits. None of the context-length patterns matched it and it surfaced as
BadRequestError.

Closes crmne#906
@codecov

codecov Bot commented Sep 2, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.44%. Comparing base (959f42c) to head (891935b).

Additional details and impacted files
@@           Coverage Diff           @@
##             main     #907   +/-   ##
=======================================
  Coverage   94.44%   94.44%           
=======================================
  Files         238      238           
  Lines       11940    11940           
  Branches     2030     2030           
=======================================
  Hits        11277    11277           
  Misses        285      285           
  Partials      378      378           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@frostmark

Copy link
Copy Markdown
Contributor Author

The Migration adapters (PostgreSQL, MySQL) failure is pre-existing on main, not from this change: #905 and #903 fail on the same assertion (upgrade_migration_adapters_spec.rb:191, "structured content text was not preserved"), and this PR touches only ErrorMiddleware::CONTEXT_LENGTH_PATTERNS and its spec.

Likely cause, in case it helps: the MySQL branch of backfill_v2_data.rb.tt renders content with CAST(content_raw AS CHAR), and MySQL returns its normalized JSON text with a space after the colon ({"answer": 42}), while the spec expects {"answer":42}. PostgreSQL's ::text keeps the original spacing, which is why only the MySQL scenario fails. Happy to open a separate PR if you'd like the spec (or the cast) adjusted.

@crmne
crmne merged commit a1adc8e into crmne:main Sep 3, 2026
23 of 24 checks passed
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.

[BUG] Anthropic "input length and max_tokens exceed context limit" is not classified as ContextLengthExceededError

2 participants