Skip to content

fix(router): resolve prompt cache minimum per model instead of a flat 1024 - #33637

Merged
tin-berri merged 3 commits into
litellm_internal_stagingfrom
litellm_lit4520_cache_min_tokens
Jul 17, 2026
Merged

tin-berri merged 3 commits into
litellm_internal_stagingfrom
litellm_lit4520_cache_min_tokens

Conversation

@tin-berri

@tin-berri tin-berri commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Relevant issues

MINIMUM_PROMPT_CACHE_TOKEN_COUNT is a hardcoded 1024 used to guess whether the provider will cache a prompt, and that guess decides whether routing pins to one deployment. The real minimum is per-model, from 512 to 4096, so on Opus 4.6 a 2000 token prompt looked cacheable and litellm pinned all traffic to one deployment while Anthropic never cached it

  • Added prompt_cache_min_tokens to the cost map on 114 Anthropic keys, resolved per model instead of the flat 1024
  • Changed the routing check to read its threshold from the deployments, not the model group alias, which never resolves
  • Left Gemini and third-party-hosted Claude keys unset, so nothing changes for them (LIT-4525)

Only routing changes. Whether caching happens is the provider's call and is unaffected

Linear ticket

Resolves LIT-4520

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • My PR passes all CI/CD checks (e.g., lint, format, unit tests)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • I have received a Greptile Confidence Score of at least 4/5 before requesting a maintainer review (Greptile reviews automatically once the PR is opened; only comment @greptileai to re-request a review after pushing changes)

Delays in PR merge?

If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).

Screenshots / Proof of Fix

Two claude-opus-4-6 deployments in one model group with optional_pre_call_checks: ["prompt_caching"], hitting the real Anthropic API. The same ~1400 token prompt (above the old flat 1024, below Opus 4.6's real 4096) sent 8 times. x-litellm-model-id shows which deployment served each request, and Anthropic's own usage reports whether it actually cached anything

model_list:
  - model_name: opus-group
    litellm_params:
      model: anthropic/claude-opus-4-6
      api_key: os.environ/ANTHROPIC_API_KEY
    model_info:
      id: deployment-A
  - model_name: opus-group
    litellm_params:
      model: anthropic/claude-opus-4-6
      api_key: os.environ/ANTHROPIC_API_KEY
    model_info:
      id: deployment-B

router_settings:
  optional_pre_call_checks: ["prompt_caching"]
  routing_strategy: simple-shuffle
PREFIX=$(python3 -c "print('The quick brown fox jumps over the lazy dog. ' * 155)")
BODY=$(python3 - "$PREFIX" <<'PY'
import json, sys
print(json.dumps({
    "model": "opus-group",
    "max_tokens": 16,
    "messages": [
        {"role": "system", "content": [
            {"type": "text", "text": sys.argv[1], "cache_control": {"type": "ephemeral"}}
        ]},
        {"role": "user", "content": "Reply with exactly one word: ok"},
    ],
}))
PY
)

for i in $(seq 1 8); do
  curl -sS -D /tmp/h -o /tmp/b -X POST http://localhost:4000/v1/chat/completions \
    -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" -d "$BODY" > /dev/null
  echo "req $i  served-by=$(grep -i '^x-litellm-model-id:' /tmp/h | tr -d '\r' | awk '{print $2}')  $(python3 -c "
import json; u=json.load(open('/tmp/b'))['usage']
print('cache_creation=%s cache_read=%s' % (u.get('cache_creation_input_tokens'), u.get('cache_read_input_tokens')))")"
done

Before, prompt is 1403 tokens (MINIMUM_PROMPT_CACHE_TOKEN_COUNT=1024 reproduces the old flat threshold on the same binary)

req 1  served-by=deployment-B  cache_creation=0 cache_read=0
req 2  served-by=deployment-B  cache_creation=0 cache_read=0
req 3  served-by=deployment-B  cache_creation=0 cache_read=0
req 4  served-by=deployment-B  cache_creation=0 cache_read=0
req 5  served-by=deployment-B  cache_creation=0 cache_read=0
req 6  served-by=deployment-B  cache_creation=0 cache_read=0
req 7  served-by=deployment-B  cache_creation=0 cache_read=0
req 8  served-by=deployment-B  cache_creation=0 cache_read=0

Every request is pinned to one deployment, and Anthropic reports it never cached the prefix on any of them. The pin bought nothing and cost the group its load balancing

After, same 1403 token prompt, per-model minimum of 4096 now applies

req 1  served-by=deployment-A  cache_creation=0 cache_read=0
req 2  served-by=deployment-B  cache_creation=0 cache_read=0
req 3  served-by=deployment-B  cache_creation=0 cache_read=0
req 4  served-by=deployment-A  cache_creation=0 cache_read=0
req 5  served-by=deployment-A  cache_creation=0 cache_read=0
req 6  served-by=deployment-A  cache_creation=0 cache_read=0
req 7  served-by=deployment-B  cache_creation=0 cache_read=0
req 8  served-by=deployment-A  cache_creation=0 cache_read=0

Load balancing is restored, and Anthropic still reports no caching, which is the point: there was never a cache to route to

Positive control, same group and same fixed binary, prompt raised to 6823 tokens so it clears Opus 4.6's real minimum

req 1  served-by=deployment-A  cache_creation=6823 cache_read=0
req 2  served-by=deployment-A  cache_creation=0 cache_read=6823
req 3  served-by=deployment-A  cache_creation=0 cache_read=6823
req 4  served-by=deployment-A  cache_creation=0 cache_read=6823
req 5  served-by=deployment-A  cache_creation=0 cache_read=6823
req 6  served-by=deployment-A  cache_creation=0 cache_read=6823
req 7  served-by=deployment-A  cache_creation=0 cache_read=6823
req 8  served-by=deployment-A  cache_creation=0 cache_read=6823

The feature still works where it should. Request 1 creates the cache, the rest pin to that deployment and genuinely read 6823 tokens back from it. The fix discriminates by model, it does not disable the check

Type

🐛 Bug Fix

Changes

  • Resolves the minimum cacheable prefix per model from a new prompt_cache_min_tokens field in the cost map, instead of a flat 1024
  • The routing check now reads its threshold from the deployments, not the model group alias it is handed, which never resolves
  • MINIMUM_PROMPT_CACHE_TOKEN_COUNT stays as a global escape hatch when explicitly exported, and as the fallback for models with no entry, so anything unset behaves as it does today
  • Anthropic keys only, 114 of them, in the cost map and its backup. Gemini and third-party-hosted Claude keys are left unset and unchanged (LIT-4525)
Minimum Models
512 Fable 5, Mythos 5
1024 Opus 4.8, Sonnet 5, Sonnet 4.6, Sonnet 4.5, Opus 4.1, Opus 4, Sonnet 4
2048 Opus 4.7, Mythos Preview, Haiku 3.5
4096 Opus 4.6, Opus 4.5, Haiku 4.5

Also platform-dependent, so Fable 5 is 1024 on Bedrock and 512 elsewhere. That falls out of the existing per-entry keys with no special casing

Two things a reviewer will likely ask about:

  • The read gate cannot cause a wrong pin, so it takes the group's lowest minimum rather than the highest. Entries are only written by async_log_success_event against the deployment's real model, so a model that will not cache a prefix never records one and there is nothing to pin it to. The read gate only decides whether the cache lookup is worth doing
  • Wildcard routes work because pattern_match_deployments substitutes the real model name before the check sees it, and there is a test pinning that

QA runbook

  1. Point a config at two claude-opus-4-6 deployments in one model group with optional_pre_call_checks: ["prompt_caching"], as above, and start the proxy with LITELLM_LOCAL_MODEL_COST_MAP=True so the new field is read from the local map rather than fetched from main
  2. Send the same ~1400 token prompt 8 times using the loop above and confirm x-litellm-model-id varies across both deployments, and that cache_creation_input_tokens is 0 every time
  3. Export MINIMUM_PROMPT_CACHE_TOKEN_COUNT=1024, restart, repeat, and confirm every request pins to a single deployment. This is the old behavior and confirms the escape hatch still overrides the per-model value
  4. Unset it, raise the prompt above 4096 tokens, restart, repeat, and confirm requests pin to one deployment and that cache_creation_input_tokens is non-zero on the first request with cache_read_input_tokens non-zero on the rest
  5. pytest tests/test_litellm/router_utils/pre_call_checks/test_prompt_caching_deployment_check.py tests/test_litellm/test_utils.py -q --tb=line

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR

… 1024

MINIMUM_PROMPT_CACHE_TOKEN_COUNT was a flat 1024 described as "minimum number of
tokens to cache a prompt by Anthropic". Anthropic's minimum cacheable prefix is
per-model and ranges from 512 to 4096, and it can differ per platform for the same
model, so one constant is wrong in both directions

is_prompt_caching_valid_prompt gates PromptCachingDeploymentCheck, which is what
optional_pre_call_checks: ["prompt_caching"] turns on. When it believes a prompt is
cacheable, async_filter_deployments pins routing to whichever deployment previously
served that prefix. For a prompt between 1024 and 4096 tokens on Opus 4.6, Opus 4.5
or Haiku 4.5, litellm judged it cacheable and constrained routing while the provider
never cached it, so the pin cost load balancing for nothing. In the other direction
Fable 5 caches from 512 tokens, so a 512 to 1024 token prefix was refused a pin it
had earned

The minimum now resolves from prompt_cache_min_tokens in the model cost map, which
keeps it current with new models and lets the Bedrock override for Fable 5 fall out
of the existing per-entry keys with no special casing. MINIMUM_PROMPT_CACHE_TOKEN_COUNT
stays as a global escape hatch when explicitly set, and as the fallback for models the
cost map has no entry for

async_filter_deployments only ever receives the model group alias, never a model name,
so it resolves the threshold from healthy_deployments instead. A group may mix models
with different minimums, so it takes the max: a prompt is only treated as cacheable when
it clears every member's minimum, because an unnecessary pin is the defect being fixed
while a missed pin only forfeits an optimization

Gemini context caching shares this gate and has the same defect; its entries are left
unset so they keep today's behavior, tracked separately in LIT-4525
@greptile-apps

greptile-apps Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes the prompt-caching routing gate in LiteLLM's router, replacing a flat 1024-token minimum with per-model values read from a new prompt_cache_min_tokens field in the model cost map, and fixes the routing gate so it resolves thresholds from actual deployment models rather than the group alias (which never matched any cost-map key).

  • Adds prompt_cache_min_tokens to 114 Anthropic model entries in both cost maps, with values ranging from 512 to 4096, and a DEFAULT_MINIMUM_PROMPT_CACHE_TOKEN_COUNT / MINIMUM_PROMPT_CACHE_TOKEN_COUNT_OVERRIDE split in constants.py so the env var escape hatch still works.
  • Introduces get_prompt_cache_min_tokens in utils.py (swallowing lookup misses rather than propagating them) and _get_min_token_count_for_deployments in the deployment check (taking the group minimum to avoid losing cache hits from lower-minimum members), with comprehensive unit tests covering per-model resolution, platform differences, wildcard routes, and the escape hatch.

Confidence Score: 5/5

Safe to merge — the change tightens the routing gate's token threshold to per-model values from the cost map, preserves the existing env-var escape hatch, and is covered by tests that clear the LRU cache correctly.

The core logic is sound: the read gate uses the group minimum (preventing lost cache hits from lower-minimum members), the write gate uses the real model name (ensuring only genuinely cacheable prefixes are recorded), and the resolver never propagates lookup misses. MINIMUM_PROMPT_CACHE_TOKEN_COUNT is preserved for backward compatibility. Tests cover the regression, positive control, mixed-group minimum, empty group, per-platform variation, unknown-model fallback, and wildcard routes.

No files require special attention.

Important Files Changed

Filename Overview
litellm/router_utils/pre_call_checks/prompt_caching_deployment_check.py Adds _get_min_token_count_for_deployments (takes group minimum, documented rationale) and threads it into async_filter_deployments via min_token_count; write gate at async_log_success_event correctly uses the real model name without change
litellm/utils.py Adds get_prompt_cache_min_tokens (never raises, falls back to default on lookup miss) and updates is_prompt_caching_valid_prompt to accept an explicit min_token_count and delegate to it when not provided
litellm/constants.py Splits MINIMUM_PROMPT_CACHE_TOKEN_COUNT into MINIMUM_PROMPT_CACHE_TOKEN_COUNT_OVERRIDE (set only when env var is present) and DEFAULT_MINIMUM_PROMPT_CACHE_TOKEN_COUNT, preserving backward compat while enabling callers to distinguish "explicitly configured" from "default"
litellm/types/utils.py Adds optional prompt_cache_min_tokens: Optional[int] field to ModelInfoBase TypedDict with an explanatory comment
model_prices_and_context_window.json Adds prompt_cache_min_tokens to 114 Anthropic model entries with values matching provider documentation (512/1024/2048/4096 per model); platform variants (Bedrock, Vertex AI) correctly differ from base entries
tests/test_litellm/router_utils/pre_call_checks/test_prompt_caching_deployment_check.py New test file with autouse fixture that clears get_model_info's LRU cache on setup and teardown; covers regression, positive control, mixed-group minimum, empty group, per-model minimum, and wildcard route resolution
tests/test_litellm/test_utils.py Adds tests for get_prompt_cache_min_tokens (per-model, per-platform, unknown-model fallback) and is_prompt_caching_valid_prompt (per-model minimum, explicit override); schema validator updated to accept the new prompt_cache_min_tokens field

Reviews (3): Last reviewed commit: "fix(router): take the lowest minimum acr..." | Re-trigger Greptile

@codecov

codecov Bot commented Jul 17, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 83.33333% with 5 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/litellm_core_utils/env_utils.py 50.00% 4 Missing ⚠️
litellm/utils.py 92.30% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

get_model_info is lru_cached, so swapping litellm.model_cost is not enough on its
own. An earlier test that resolved these models against the remote map, which does
not carry prompt_cache_min_tokens yet, leaves cached entries without it, and the
stale hit resolves to the default. The assertions would then pass for the wrong
reason or fail depending on execution order

Clear on teardown as well, so entries these tests warm against the local map do not
leak into later tests, matching the fixture already used in test_utils.py

Also pin that a wildcard route resolves the underlying model's minimum. That works
only because pattern_match_deployments substitutes the real model name into
litellm_params before the deployment reaches the check; without the assertion that
claim is unpinned and the threshold would silently fall back to the default
@tin-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@tin-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ Bugbot reviewed your changes and found no new issues!

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit 25b2f83. Configure here.

@codspeed

codspeed Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing litellm_lit4520_cache_min_tokens (fc58481) with litellm_internal_staging (4cfc987)

Open in CodSpeed

…ghest

The read gate cannot cause a wrong pin. A deployment is only pinned when the cache
already holds an entry for the prefix, and async_log_success_event writes entries
against the deployment's real model rather than the group alias, so a model that
will not cache a prefix never records one and there is nothing to pin it to

That makes this gate purely a cheap short-circuit deciding whether the cache lookup
is worth doing, so the threshold must be the lowest minimum in the group. Taking the
highest skipped the lookup for a prefix a lower-minimum member had genuinely cached,
losing a hit it earned, and protected against nothing. It also broke the Fable 5
direction this ticket is meant to fix: its real minimum is 512, so a group gate stuck
at a higher value would skip the lookup for a prefix Fable 5 had actually cached
@tin-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@tin-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ Bugbot reviewed your changes and found no new issues!

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit fc58481. Configure here.

@tin-berri
tin-berri enabled auto-merge July 17, 2026 03:16
@tin-berri
tin-berri merged commit b880ad3 into litellm_internal_staging Jul 17, 2026
85 of 86 checks passed
@tin-berri
tin-berri deleted the litellm_lit4520_cache_min_tokens branch July 17, 2026 03:34
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.

2 participants