Repository navigation
fix(router): resolve prompt cache minimum per model instead of a flat 1024 - #33637
Conversation
… 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 SummaryThis 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
Confidence Score: 5/5Safe 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. No files require special attention.
|
| 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 Report❌ Patch coverage is
📢 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
|
bugbot run |
There was a problem hiding this comment.
✅ 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.
…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
|
bugbot run |
There was a problem hiding this comment.
✅ 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.
Relevant issues
MINIMUM_PROMPT_CACHE_TOKEN_COUNTis 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 itprompt_cache_min_tokensto the cost map on 114 Anthropic keys, resolved per model instead of the flat 1024Only 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
@greptileaito 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-6deployments in one model group withoptional_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-idshows which deployment served each request, and Anthropic's ownusagereports whether it actually cached anythingBefore, prompt is 1403 tokens (
MINIMUM_PROMPT_CACHE_TOKEN_COUNT=1024reproduces the old flat threshold on the same binary)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
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
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
prompt_cache_min_tokensfield in the cost map, instead of a flat 1024MINIMUM_PROMPT_CACHE_TOKEN_COUNTstays as a global escape hatch when explicitly exported, and as the fallback for models with no entry, so anything unset behaves as it does todayAlso 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:
async_log_success_eventagainst 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 doingpattern_match_deploymentssubstitutes the real model name before the check sees it, and there is a test pinning thatQA runbook
claude-opus-4-6deployments in one model group withoptional_pre_call_checks: ["prompt_caching"], as above, and start the proxy withLITELLM_LOCAL_MODEL_COST_MAP=Trueso the new field is read from the local map rather than fetched frommainx-litellm-model-idvaries across both deployments, and thatcache_creation_input_tokensis 0 every timeMINIMUM_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 valuecache_creation_input_tokensis non-zero on the first request withcache_read_input_tokensnon-zero on the restpytest tests/test_litellm/router_utils/pre_call_checks/test_prompt_caching_deployment_check.py tests/test_litellm/test_utils.py -q --tb=lineFinal Attestation