Skip to content

feat(dashscope): add separate explicit and implicit cache pricing - #40111

Closed
limdeng wants to merge 13 commits into
BerriAI:mainfrom
limdeng:litellm_dashscope_qwen_cache_pricing
Closed

limdeng wants to merge 13 commits into
BerriAI:mainfrom
limdeng:litellm_dashscope_qwen_cache_pricing

Conversation

@limdeng

@limdeng limdeng commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Feature this adds:

  • Add separate, configurable read prices for Qwen explicit and implicit Context Cache
  • Extend existing DashScope cache support with optional mode-aware pricing
  • Keep existing cache-read pricing when no implicit rate is configured

How it works:

  • Preserve provider-reported cache_type in normalized usage
  • Reuse cache_read_input_token_cost for explicit reads and cache_creation_input_token_cost for cache creation
  • Add optional implicit_cache_read_input_token_cost for implicit reads
  • Apply the selected rate consistently to request cost, cost breakdown, tiered pricing, and caching savings

Explicit (cache_control-based) and implicit (automatic prefix) caching are documented DashScope capabilities. This PR adds pricing support for distinguishing their cache reads in LiteLLM.

Provider documentation: https://www.alibabacloud.com/help/en/model-studio/context-cache

User Flow

Before: Qwen cache reads share one configured rate

  1. The proxy admin configures cache_read_input_token_cost at $0.10/M tokens; separate implicit-cache read pricing is not supported
  2. A developer sends POST http://localhost:4000/v1/chat/completions twice with the same long Qwen prompt and no cache_control
  3. The repeated response is 200 OK with cached_tokens and no cache_type
  4. The cache-read cost header uses the shared $0.10/M rate

After: the admin can opt into separate implicit-cache read pricing

  1. The proxy admin keeps cache_read_input_token_cost at $0.10/M and sets the new implicit_cache_read_input_token_cost to $0.20/M
  2. The developer repeats the same requests
  3. An implicit hit uses $0.20/M; an explicit hit with cache_type: "ephemeral" continues to use $0.10/M
  4. Omitting the new field preserves the existing shared-rate behavior

Relevant issues

Closes #40090

Related transport and pricing work:

Affected release

Linear ticket

Pre-Submission checklist

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

  • I have added meaningful tests
  • The focused tests pass locally: the core cost, provider, and dispatcher suites report 608 passed; spend tracking reports 225 passed; savings reports 97 passed; types reports 39 passed
  • My PR passes all required CI/CD checks on current commit 2cafaa308f
  • 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 on the current commit (5/5 for 2cafaa308f)

Local verification:

  • Patch coverage is 100% across 88 changed executable Python lines
  • All make check gates passed on 2cafaa308f, including circular-import, type-discipline, test-quality, frontend, and schema.d.ts sync checks
  • GitHub reports every required check as passing. The separate non-required OSV scan reports mlflow 3.15.0 / PYSEC-2026-3865 from the unchanged uv.lock; OSV reports no fixed release
  • Local CodSpeed wall-time A/B improved OpenAI from 20.17µs to 14.47µs and Anthropic from 21.50µs to 18.14µs
  • A second npm run gen:api produced no generated diff

Delays in PR merge?

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

Screenshots / Feature Verification

This no-mock proof used real dashscope/qwen3.8-max calls. A local relay forwarded request bodies unchanged to the development gateway and removed only upstream cost headers, forcing each checkout to calculate its own cost from the unmodified provider usage.

Both checkouts used the same model configuration below. The new implicit_cache_read_input_token_cost field enables separate implicit-cache pricing in the PR checkout; the baseline uses the existing shared cache-read rate. These values are illustrative custom rates, not a statement of the provider's current model prices:

input_cost_per_token: 0.000001
output_cost_per_token: 0.000002
cache_creation_input_token_cost: 0.00000125
cache_read_input_token_cost: 0.0000001
implicit_cache_read_input_token_cost: 0.0000002

The implicit request contained a stable prompt longer than 1,024 tokens and no cache_control. The explicit request used the same text with cache_control: {"type": "ephemeral"}. Each curl loop sent the request twice and captured the second response.

Before (30f33a9)

Implicit automatic cache hit

  1. Send the implicit request twice to the baseline main checkout (30f33a949b):

    for _ in 1 2; do
      curl --fail-with-body --silent --show-error \
        --dump-header before-implicit.headers \
        --output before-implicit.json \
        --header "Authorization: Bearer $LOCAL_PROXY_KEY" \
        --header "Content-Type: application/json" \
        --data-binary @implicit.json \
        http://127.0.0.1:4011/v1/chat/completions
    done
  2. Observe 50,176 cached tokens with no cache_type, priced using the existing shared cache-read rate:

    HTTP/1.1 200 OK
    x-litellm-response-cost-cache-read: 0.0050176
    usage.prompt_tokens: 50664
    usage.prompt_tokens_details.cached_tokens: 50176
    usage.prompt_tokens_details.cache_type: null
    

    50176 * 0.0000001 = 0.0050176

Explicit ephemeral cache hit

  1. Send the explicit request twice to the same main checkout:

    for _ in 1 2; do
      curl --fail-with-body --silent --show-error \
        --dump-header before-explicit.headers \
        --output before-explicit.json \
        --header "Authorization: Bearer $LOCAL_PROXY_KEY" \
        --header "Content-Type: application/json" \
        --data-binary @explicit.json \
        http://127.0.0.1:4011/v1/chat/completions
    done
  2. Observe 50,654 cached tokens with cache_type: "ephemeral", priced using the existing explicit cache-read rate:

    HTTP/1.1 200 OK
    x-litellm-response-cost-cache-read: 0.005065399999999999
    usage.prompt_tokens: 50668
    usage.prompt_tokens_details.cached_tokens: 50654
    usage.prompt_tokens_details.cache_creation_input_tokens: 0
    usage.prompt_tokens_details.cache_type: ephemeral
    

    50654 * 0.0000001 = 0.0050654

After (2cafaa3)

Implicit automatic cache hit

  1. Send the identical implicit request twice to the current PR checkout:

    for _ in 1 2; do
      curl --fail-with-body --silent --show-error \
        --dump-header after-implicit.headers \
        --output after-implicit.json \
        --header "Authorization: Bearer $LOCAL_PROXY_KEY" \
        --header "Content-Type: application/json" \
        --data-binary @implicit.json \
        http://127.0.0.1:4012/v1/chat/completions
    done
  2. Observe the same 50,176 cached tokens, now priced using the separately configured implicit-cache read rate:

    HTTP/1.1 200 OK
    x-litellm-response-cost-cache-read: 0.0100352
    usage.prompt_tokens: 50664
    usage.prompt_tokens_details.cached_tokens: 50176
    usage.prompt_tokens_details.cache_type: null
    

    50176 * 0.0000002 = 0.0100352

Explicit ephemeral cache hit

  1. Send the identical explicit request twice to the same PR checkout:

    for _ in 1 2; do
      curl --fail-with-body --silent --show-error \
        --dump-header after-explicit.headers \
        --output after-explicit.json \
        --header "Authorization: Bearer $LOCAL_PROXY_KEY" \
        --header "Content-Type: application/json" \
        --data-binary @explicit.json \
        http://127.0.0.1:4012/v1/chat/completions
    done
  2. Observe the same 50,654 explicit cached tokens still using the existing explicit rate:

    HTTP/1.1 200 OK
    x-litellm-response-cost-cache-read: 0.005065399999999999
    usage.prompt_tokens: 50668
    usage.prompt_tokens_details.cached_tokens: 50654
    usage.prompt_tokens_details.cache_creation_input_tokens: 0
    usage.prompt_tokens_details.cache_type: ephemeral
    

    50654 * 0.0000001 = 0.0050654

Type

🆕 New Feature

Caveats (if any)

Low

  • Separate implicit pricing is opt-in per model
  • Missing implicit rates preserve existing cache-read pricing

Final Attestation

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

@greptile-apps

greptile-apps Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR distinguishes explicit and implicit Qwen cache-read pricing while preserving existing fallback behavior

  • Preserves provider-reported cache mode in normalized usage
  • Applies mode-specific flat, tiered, service-tier, and off-peak cache rates consistently across total cost, breakdowns, savings, and spend tracking
  • Keeps provider dispatch imports safe and adds focused regression coverage

Confidence Score: 5/5

The PR appears safe to merge because no new actionable issue or outstanding previous finding remains

The immutable refactor preserves cache-rate selection, including service-tier and zero-valued rates, while all previous findings are resolved in the current code

Important Files Changed

Filename Overview
litellm/litellm_core_utils/llm_cost_calc/utils.py Resolves implicit cache-read rates through immutable values and applies them consistently to totals, breakdowns, and savings
litellm/llms/dashscope/cost_calculator.py Classifies Qwen cache mode and selects matching flat, tiered, and off-peak pricing
litellm/types/utils.py Preserves cache-type metadata and exposes implicit cache pricing through shared typed models
litellm/utils.py Propagates implicit cache-read pricing through model registration and model information lookup
litellm/cost_calculator.py Defers Fireworks and Perplexity calculator imports to their matching dispatch branches
tests/test_litellm/llms/dashscope/test_dashscope_cost_calculator.py Covers explicit and implicit pricing across generic, DashScope, tiered, service-tier, off-peak, breakdown, and savings paths

Reviews (10): Last reviewed commit: "refactor(cost): keep cache rate immutabl..." | Re-trigger Greptile

Comment thread litellm/cost_calculator.py Resolved
@codspeed

codspeed Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing limdeng:litellm_dashscope_qwen_cache_pricing (2cafaa3) with main (30f33a9)

Open in CodSpeed

@codecov

codecov Bot commented Sep 7, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@limdeng

limdeng commented Sep 7, 2026

Copy link
Copy Markdown
Contributor Author

@greptileai Please review the latest commit. Cache-mode classification now stays in the DashScope adapter and uses provider response metadata only

@limdeng

limdeng commented Sep 7, 2026

Copy link
Copy Markdown
Contributor Author

@greptileai Please review the latest commit. Shared cost utilities now use a provider-neutral registry, while DashScope owns its cache-rate resolver

@limdeng
limdeng changed the base branch from litellm_internal_staging to main September 14, 2026 03:31
@limdeng

limdeng commented Sep 14, 2026

Copy link
Copy Markdown
Contributor Author

@greptileai Please review current commit. DashScope now owns cache-mode pricing behind the provider-neutral configuration boundary, with current main and E2E proof.

@limdeng

limdeng commented Sep 14, 2026

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.

Stale Bugbot comment from a previous run.

@limdeng

limdeng commented Sep 14, 2026

Copy link
Copy Markdown
Contributor Author

@greptileai Please review current commit. The test now exercises a real provider without chat configuration and no longer monkeypatches class methods.

@limdeng

limdeng commented Sep 14, 2026

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.

Stale Bugbot comment from a previous run.

@limdeng

limdeng commented Sep 14, 2026

Copy link
Copy Markdown
Contributor Author

@greptileai Please review current commit. Tiered implicit rates now honor model-level configuration, savings use the same provider-resolved rate, and all checks pass.

@limdeng

limdeng commented Sep 14, 2026

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.

Stale Bugbot comment from a previous run.

@limdeng

limdeng commented Sep 14, 2026

Copy link
Copy Markdown
Contributor Author

@greptileai Please review current commit e68b357. The CodeQL import cycle is removed: DashScope now returns only a provider-specific pricing key, while shared code resolves that key without importing provider cost modules. Focused tests, 100% patch coverage, make check, and current-tip real E2E pass.

@limdeng

limdeng commented Sep 14, 2026

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.

Stale Bugbot comment from a previous run.

@limdeng

limdeng commented Sep 14, 2026

Copy link
Copy Markdown
Contributor Author

@greptileai Please review current commit b9db42a. Provider configuration hooks and dynamic provider imports have been removed. Shared pricing now activates the optional implicit rate only from normalized cache metadata plus model pricing, while DashScope total-cost logic remains provider-local. Focused tests, 100% patch coverage, make check, and current-tip real E2E pass.

@limdeng

limdeng commented Sep 14, 2026

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.

Stale Bugbot comment from a previous run.

@limdeng

limdeng commented Sep 14, 2026

Copy link
Copy Markdown
Contributor Author

@greptileai Please review commit bfca7aa. It aligns generic cache totals with breakdown rates and removes the CodeQL import cycles.

@limdeng

limdeng commented Sep 14, 2026

Copy link
Copy Markdown
Contributor Author

bugbot run Please review commit bfca7aa, especially generic cache total consistency and the lazy Fireworks and Perplexity imports.

@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.

Stale Bugbot comment from a previous run.

Comment thread litellm/cost_calculator.py Resolved
Comment thread litellm/cost_calculator.py Resolved
Comment thread litellm/cost_calculator.py Resolved
Comment thread litellm/cost_calculator.py Resolved
@limdeng

limdeng commented Sep 14, 2026

Copy link
Copy Markdown
Contributor Author

@greptileai Please re-review commit 2cafaa3 after the immutable cache-rate refactor; focused tests, patch coverage, and make check pass locally.

@limdeng

limdeng commented Sep 14, 2026

Copy link
Copy Markdown
Contributor Author

@cursor review Please review commit 2cafaa3 after the immutable cache-rate refactor; focused tests, patch coverage, and make check pass locally.

@greptile-apps

greptile-apps Bot commented Sep 14, 2026

Copy link
Copy Markdown
Contributor

Want your agent to iterate on Greptile's feedback? Try greploops.

@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 2cafaa3. Configure here.

@limdeng

limdeng commented Sep 15, 2026

Copy link
Copy Markdown
Contributor Author

@krrishd @ishaan-jaff Could you please prioritize reviewing this PR?

Explicit and implicit Context Cache are official, documented features of Alibaba Cloud's DashScope API, with different billing rates. Correctly distinguishing and pricing them is essential for accurate DashScope cost tracking in LiteLLM.

Official documentation: https://www.alibabacloud.com/help/en/model-studio/context-cache

This PR addresses that gap while preserving existing pricing when no implicit-cache rate is configured. The latest commit, 2cafaa308f, has all required checks passing, a Greptile score of 5/5, and no unresolved review conversations.

I also emailed Krrish about this PR roughly a day ago and haven't received a reply yet. I'd appreciate a review soon, or help routing it to the appropriate maintainer. Please let me know if anything else is needed before merging. Thanks!

@limdeng limdeng changed the title fix(dashscope): distinguish qwen cache pricing modes feat(dashscope): add separate explicit and implicit cache pricing Sep 17, 2026
@limdeng limdeng closed this Oct 9, 2026
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.

[DashScope/Qwen] Explicit (cache_control-based) and implicit (automatic) context-cache hits are merged, causing incorrect cost calculation

3 participants