Skip to content

fix(caching): key the response cache on extra_body by default - #53898

Merged
joshua-berri merged 4 commits into
mainfrom
litellm_fix_extra_body_cache_key_53729
Nov 23, 2026
Merged

joshua-berri merged 4 commits into
mainfrom
litellm_fix_extra_body_cache_key_53729

Conversation

@joshua-berri

@joshua-berri joshua-berri commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Handwritten 1-3 sentence description

  • Includes extra_body options in cache keys by default, preventing requests with different options—such as thinking enabled versus disabled—from receiving each other’s cached responses.
  • Supports dictionaries, mapping objects, and key/value pair lists or tuples.
  • Preserves existing opt-in cache keys, explicit cache keys, and empty/token-only behavior.
Details

TLDR

Problem this solves:

  • Different provider options could receive the same cached response.

How it solves it:

  • Key dictionary, Mapping, and concrete pair-sequence extra_body values.
  • Preserve opt-in keys, token-only keys, and explicit overrides.

User Flow

Before, disabling thinking can return a cached thinking response.

  1. Enable the local response cache with default settings.
  2. Send a completion with thinking enabled in extra_body.
  3. Disable thinking and receive the earlier cached response.

After, each extra_body configuration gets its own response.

  1. Enable the local response cache with default settings.
  2. Send the same two requests with different thinking options.
  3. Receive separate responses, with repeat requests hitting their respective entries.

Relevant issues

Fixes #53729.

Pre-Submission checklist

  • I have added meaningful tests
  • The affected tests pass, with verification performed remotely through Devin
  • My PR passes all required CI/CD checks
  • My PR's scope is isolated to one problem
  • Every automated review on the latest commit has finished

Screenshots / Proof of Fix

Baseline 62ede30f997f664cd7190815b8c0fb104ef6878c, final tested tip 6409a88f3a6bfba3b0c1a3eb7a13ac85d1a1e3bd. Independent Devin Ultra verification found no in-scope regression.

The original issue snippet prints WITH-THINKING True before and NO-THINKING None after. The original local-vLLM request shape was tested with its mock response. Live proof uses hosted_vllm/qwen-plus on DashScope with enable_thinking, including accepted mapping and pair-sequence inputs.

Tests, coverage, gates at 6409a88f

Piece Result
Original snippet (mock) NO-THINKING None on default flag and flag true
Mapped tests, -n 4 1,216 passed, 0 failed. 91 new vs baseline, 0 removed
Changed-line coverage 30 of 30 executable lines, 12 of 12 branches (222 passed in test_caching.py)
Corpus, 176 cases flag true 0 changed vs baseline. Default 118 changed, 58 unchanged, 0 raises
All 7 gates vs base 62ede30f all exit 0, including type_check_gate.py
Function Lines Branches
_extra_body_mapping 2 of 2 none
_concrete_sequence 3 of 3 2 of 2
_extra_body_pair 5 of 5 2 of 2
_extra_body_from_pairs 5 of 5 2 of 2
_extra_body_beyond_always_keyed_params 6 of 6 2 of 2
_keyed_provider_params_in_extra_body 4 of 4 2 of 2
Cache._keyed_param_values 12 of 12 12 of 12

All 91 added parametrizations passed. The prior tip's isolated logging failure did not recur in the final mapped suite. No thresholds, suppressions, or budgets were raised. Repository-wide coverage is not claimed. Codecov has no report for this tip (API returns 404: No Commit matches the given query). The affected CI workflows do not upload to Codecov. The requested completed-Codecov-report readiness requirement remains unmet; the executed line/branch evidence above is independently available.

Three-turn live conversation, direct-provider controls, and token counts

Run FLAG=0 python live_conv3.py from each source checkout with DASHSCOPE_API_KEY set. This uses three turns with resent history, then replays each conversation. Continuation IDs are not applicable to this /chat/completions flow. The response-cache hit usage is stored usage, not a new provider charge.

"""LIVE three-turn conversation, history resent each turn, hosted_vllm/qwen-plus on DashScope intl.
Part 1: direct provider control (httpx, top-level enable_thinking). Part 2: LiteLLM SDK with extra_body, first pass then replay of the identical turns.
Prints billed tokens (prompt/completion/reasoning) and provider cached prompt tokens for every turn."""
import json, os, subprocess
import httpx, litellm
from litellm.caching.caching import Cache
FLAG = os.environ.get("FLAG") == "1"
litellm.enable_caching_on_provider_specific_optional_params = FLAG
API = "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
KEY = os.environ["DASHSCOPE_API_KEY"]
TAG = f"conv3-{os.getpid()}"
TURNS = [f"[{TAG}] What is 17*23? Answer with the number only.", "Add 9 to that. Number only.", "Double it. Number only."]
print(json.dumps(dict(sha=subprocess.check_output(["git", "-C", os.path.dirname(os.path.dirname(litellm.__file__)), "rev-parse", "HEAD"]).decode().strip(), flag=FLAG, live=True)))

def usage_fields(u):
    ptd = u.get("prompt_tokens_details") or {}
    ctd = u.get("completion_tokens_details") or {}
    return f"prompt_tokens={u.get('prompt_tokens')} | cached_tokens={ptd.get('cached_tokens', 0)} | completion_tokens={u.get('completion_tokens')} | reasoning_tokens={ctd.get('reasoning_tokens', 0)}"

for et in (True, False):
    history = []
    for i, q in enumerate(TURNS, 1):
        history.append({"role": "user", "content": q})
        r = httpx.post(f"{API}/chat/completions", headers={"Authorization": f"Bearer {KEY}"}, timeout=120, json={"model": "qwen-plus", "max_tokens": 400, "messages": history, "enable_thinking": et}).json()
        m = r["choices"][0]["message"]
        print(f"direct | turn={i} | enable_thinking={et} | id={r['id']} | content={m['content'][:20]} | reasoning_chars={len(m.get('reasoning_content') or '')} | {usage_fields(r['usage'])}")
        history.append({"role": "assistant", "content": m["content"]})

litellm.cache = Cache(type="local")
lookups = []
orig = litellm.cache.get_cache_key
def spy(**kw):
    k = orig(**kw)
    lookups.append(k)
    return k
litellm.cache.get_cache_key = spy

def conversation(label, et):
    history = []
    for i, q in enumerate(TURNS, 1):
        history.append({"role": "user", "content": q})
        n = len(lookups)
        r = litellm.completion(model="hosted_vllm/qwen-plus", api_base=API, api_key=KEY, max_tokens=400, messages=history, extra_body={"enable_thinking": et})
        m = r.choices[0].message
        u = r.usage.model_dump()
        print(f"sdk | {label} | turn={i} | messages={len(history)} | enable_thinking={et} | id={r.id} | content={(m.content or '')[:20]} | reasoning_chars={len(getattr(m, 'reasoning_content', None) or '')} | {usage_fields(u)} | cache_hit={r._hidden_params.get('cache_hit')} | key_lookups={len(lookups) - n} | key={(lookups[-1][:16] if len(lookups) > n else 'none')}")
        history.append({"role": "assistant", "content": m.content})

conversation("first", True)
conversation("first", False)
conversation("replay", True)
conversation("replay", False)

Baseline 62ede30f997f664cd7190815b8c0fb104ef6878c:

Turn Thinking Direct SDK first pass SDK replay
1 true 33 / 0 / 655 / 647 33 / 0 / 655 / 647, miss hit, same id
2 true 55 / 0 / 231 / 223 55 / 0 / 231 / 223, miss hit, same id
3 true 74 / 0 / 153 / 145 74 / 0 / 153 / 145, no lookup no lookup, new id, 74 / 0 / 153 / 145
1 false 33 / 0 / 3 / 0 hit on the thinking reply, 33 / 0 / 655 / 647 hit on the thinking reply
2 false 55 / 0 / 3 / 0 hit on the thinking reply, 55 / 0 / 231 / 223 hit on the thinking reply
3 false 74 / 0 / 3 / 0 74 / 0 / 3 / 0, no lookup no lookup, new id, 74 / 0 / 3 / 0

Three-turn conversation, 6409a88f, default flag, history resent (FLAG=0 python live_conv3.py, script unchanged from the one I sent). Cells are prompt / cached / completion / reasoning tokens.

Turn (messages) Thinking Direct provider SDK first pass SDK replay
1 (1) true 33 / 0 / 247 / 239 33 / 0 / 247 / 239, miss hit, same id
2 (3) true 55 / 0 / 337 / 329 55 / 0 / 337 / 329, miss hit, same id
3 (5) true 74 / 0 / 160 / 152 74 / 0 / 160 / 152, no lookup no lookup, new id, 74 / 0 / 160 / 152
1 (1) false 33 / 0 / 3 / 0 33 / 0 / 3 / 0, miss, own key hit, same id
2 (3) false 55 / 0 / 3 / 0 55 / 0 / 3 / 0, miss, own key hit, same id
3 (5) false 74 / 0 / 3 / 0 74 / 0 / 3 / 0, no lookup no lookup, new id, 74 / 0 / 3 / 0
  • Baseline for comparison (already sent): turns 1 and 2 with false were cache hits on the thinking reply (647 and 223 reasoning tokens).
  • Usage vs direct: SDK counts equal the direct control on every first-pass turn. On a hit the usage is the stored reply's and no provider call is made.
  • Provider cached tokens: 0 on all 18 calls.
  • Turn 3: key_lookups=0 on all four turn-3 calls, same as baseline, so it is billed again on replay. Unrelated to the diff, not investigated.
  • Continuation IDs: N/A, /chat/completions with resent history has none. I did not check other DashScope endpoints.

The existing third-turn cache bypass appears on both revisions and is outside this fix. Provider cached-token counts were zero, so this proves response-cache isolation rather than provider prompt-cache behavior.

Supported body shapes, live and mock results

Mapping and pairs, 6409a88f (FLAG=0|1 LIVE=1 python shapes_eb.py, which is mapping_eb.py with five wrappers: dict, MappingProxyType, UserDict, list(d.items()), tuple(d.items()))

Check Result for all five shapes
Default keys, original shape true 1db29bdea8b3beb5, false 3d272581e4399997, omitted f12cd7aeba771634
Mock completion and acompletion, default WITH miss, NO miss, WITH hit, NO hit
Live qwen-plus completion, default 2 ids each, false has 0 reasoning chars and 3 completion tokens, repeats hit
Flag-true keys byte-identical to baseline per shape (list e3e8559f9df59232 / e0f551034492eed6, tuple 4168f4582cb43e59 / 275ef94d3319c07d, mappings same as dict)
Raises 0 of 40 live calls, 0 of 40 mock calls

Live reasoning chars at default, true then false: dict 1644 / 0, MappingProxyType 1796 / 0, UserDict 1518 / 0, list 631 / 0, tuple 541 / 0.

shapes_eb.py, complete (4,449 bytes), env DASHSCOPE_API_KEY only. Run from the repo root as FLAG=0 LIVE=1 python shapes_eb.py and FLAG=1 LIVE=1 python shapes_eb.py. Without LIVE=1 it runs the key and mock legs only and needs no key.

"""extra_body given as dict / MappingProxyType / UserDict / list of pairs / tuple of pairs: original issue shape, completion + acompletion.
MOCK legs use mock_response; LIVE leg (LIVE=1) sends enable_thinking to DashScope qwen-plus to show whether the provider call accepts the mapping class."""
import asyncio, json, os, subprocess, traceback
from collections import UserDict
from types import MappingProxyType
import litellm
from litellm.caching.caching import Cache
from litellm.caching.caching_handler import _PENDING_CACHE_WRITES
FLAG = os.environ.get("FLAG") == "1"
LIVE = os.environ.get("LIVE") == "1"
litellm.enable_caching_on_provider_specific_optional_params = FLAG
WRAP = {"dict": dict, "MappingProxyType": MappingProxyType, "UserDict": UserDict, "list_of_pairs": lambda d: list(d.items()), "tuple_of_pairs": lambda d: tuple(d.items())}
MSGS = [{"role": "user", "content": "extra-body"}]
print(json.dumps(dict(sha=subprocess.check_output(["git", "-C", os.path.dirname(os.path.dirname(litellm.__file__)), "rev-parse", "HEAD"]).decode().strip(), flag=FLAG, live=LIVE)))

def key_row(name, wrap):
    c = Cache(type="local")
    def k(et):
        try:
            return c.get_cache_key(model="hosted_vllm/qwen", messages=MSGS, extra_body=wrap({"chat_template_kwargs": {"enable_thinking": et}}))[:16]
        except Exception as e:
            return f"RAISED {type(e).__name__}"
    omitted = c.get_cache_key(model="hosted_vllm/qwen", messages=MSGS)[:16]
    t, f = k(True), k(False)
    print(f"key | {name} | true={t} | false={f} | omitted={omitted} | true==false:{t == f} | true==omitted:{t == omitted}")

def outcome(fn):
    try:
        r = fn()
        return f"{r.choices[0].message.content} cache_hit={r._hidden_params.get('cache_hit')}"
    except Exception as e:
        return f"RAISED {type(e).__name__}: {str(e)[:90]}"

async def aoutcome(coro_fn):
    try:
        r = await coro_fn()
        await asyncio.gather(*_PENDING_CACHE_WRITES)
        return f"{r.choices[0].message.content} cache_hit={r._hidden_params.get('cache_hit')}"
    except Exception as e:
        return f"RAISED {type(e).__name__}: {str(e)[:90]}"

def mock_sync(name, wrap):
    litellm.cache = Cache(type="local")
    def call(et, mock):
        return lambda: litellm.completion(model="hosted_vllm/qwen", api_base="http://localhost:8000", messages=MSGS, extra_body=wrap({"chat_template_kwargs": {"enable_thinking": et}}), mock_response=mock)
    seq = [outcome(call(True, "WITH-THINKING")), outcome(call(False, "NO-THINKING")), outcome(call(True, "UNSERVED")), outcome(call(False, "UNSERVED"))]
    print(f"mock completion | {name} | " + " | ".join(seq))

async def mock_async(name, wrap):
    litellm.cache = Cache(type="local")
    def call(et, mock):
        return lambda: litellm.acompletion(model="hosted_vllm/qwen", api_base="http://localhost:8000", messages=MSGS, extra_body=wrap({"chat_template_kwargs": {"enable_thinking": et}}), mock_response=mock)
    seq = [await aoutcome(call(True, "WITH-THINKING")), await aoutcome(call(False, "NO-THINKING")), await aoutcome(call(True, "UNSERVED")), await aoutcome(call(False, "UNSERVED"))]
    print(f"mock acompletion | {name} | " + " | ".join(seq))

def live_sync(name, wrap):
    litellm.cache = Cache(type="local")
    msgs = [{"role": "user", "content": f"[shape-{name}-{os.getpid()}] What is 17*23? Answer with the number only."}]
    for label, et in [("true", True), ("false", False), ("repeat true", True), ("repeat false", False)]:
        try:
            r = litellm.completion(model="hosted_vllm/qwen-plus", api_base="https://dashscope-intl.aliyuncs.com/compatible-mode/v1", api_key=os.environ["DASHSCOPE_API_KEY"], max_tokens=400, messages=msgs, extra_body=wrap({"enable_thinking": et}))
            m = r.choices[0].message
            print(f"live completion | {name} | enable_thinking={label} | id={r.id} | reasoning_chars={len(getattr(m, 'reasoning_content', None) or '')} | completion_tokens={r.usage.completion_tokens} | cache_hit={r._hidden_params.get('cache_hit')}")
        except Exception as e:
            print(f"live completion | {name} | enable_thinking={label} | RAISED {type(e).__name__}: {str(e)[:160]}")

for name, wrap in WRAP.items():
    key_row(name, wrap)
for name, wrap in WRAP.items():
    mock_sync(name, wrap)
for name, wrap in WRAP.items():
    asyncio.run(mock_async(name, wrap))
if LIVE:
    for name, wrap in WRAP.items():
        live_sync(name, wrap)
Test, coverage, lint, and mutation commands

Commands (from the repo root, existing .venv, Python 3.12.16, uv 0.13.9)

# mapped tests, baseline
LITELLM_LOCAL_MODEL_COST_MAP=True .venv/bin/python -m pytest tests/unit/caching tests/unit/proxy/test_route_llm_request.py -q -p no:cacheprovider -n 4
# mapped tests, final candidate
LITELLM_LOCAL_MODEL_COST_MAP=True .venv/bin/python -m pytest tests/unit/caching tests/unit/proxy/test_route_llm_request.py -q -p no:cacheprovider -n 4
# coverage of the changed file
LITELLM_LOCAL_MODEL_COST_MAP=True .venv/bin/python -m coverage run --branch --include='litellm/caching/caching.py' -m pytest tests/unit/caching/test_caching.py -q -p no:cacheprovider
.venv/bin/python -m coverage json -o head_cov.json
# gates, B=62ede30f997f664cd7190815b8c0fb104ef6878c
uv run --no-sync ruff format --check --exclude '/enterprise/' litellm/caching/caching.py
(cd litellm && uv run --no-sync ruff check .)
uv run --no-sync ruff check --config .github/linters/ruff-tests.toml tests
uv run --no-sync python litellm/scripts/ruff_strict_gate.py --base $B
uv run --no-sync python litellm/scripts/type_discipline_gate.py --base $B
uv run --no-sync python litellm/scripts/test_quality_gate.py --base $B
uv run --no-sync python litellm/scripts/type_check_gate.py --base $B
# mutation: 13 single-edit mutants of caching.py in an external copy, each run with
LITELLM_LOCAL_MODEL_COST_MAP=True python -m pytest tests/unit/caching/test_caching.py -q -p no:cacheprovider -n 4

All seven gates exit 0. Mutation killed 11 of 13.

The 13-mutation run tested the first implementation. It caught 11 mutations, including removing the fix, dropping falsy values, and bypassing opt-in precedence. The two survivors sorted newly keyed fields or produced identical bytes. Final mapped tests and coverage above were rerun at 6409a88.

Live async, streaming, and the two-worker shared-Redis proxy were also exercised at af1a80aec0877ebb620d4c539b7ac0b444f1cc10. They produced two response IDs and correct repeat hits. The only subsequent change types the same runtime guards. All 176 corpus keys and 31 edge-shape keys per flag are identical between af1a80a and 6409a88; the original scenario, all five body shapes, and the three-turn conversation were independently rerun at the final tip.

Two-worker Redis proxy setup and measured outputs

Two-worker proxy proof, head. Config proxy_config_2w.yaml, one local Redis for router state, coordination and response cache:

model_list:
  - model_name: qwen
    litellm_params:
      model: hosted_vllm/qwen-plus
      api_base: https://dashscope-intl.aliyuncs.com/compatible-mode/v1
      api_key: os.environ/DASHSCOPE_API_KEY
router_settings:
  redis_host: 127.0.0.1
  redis_port: 6379
litellm_settings:
  cache: true
  cache_params:
    type: redis
    host: 127.0.0.1
    port: 6379
    namespace: v53729-proxy
    ttl: 600
general_settings:
  master_key: os.environ/V53729_MASTER_KEY
  coordination_redis:
    host: 127.0.0.1
    port: 6379
# DATABASE_URL unset; env: DASHSCOPE_API_KEY, V53729_MASTER_KEY
python litellm/proxy/proxy_cli.py --config proxy_config_2w.yaml --port 4531 --num_workers 2 --detailed_debug --reload --use_v2_migration_resolver
# log: "Started parent process [40140]", "Started server process [40148]", "Started server process [40149]"; no "workers flag is ignored" warning
for et in true false true false; do
  curl -s -D - localhost:4531/v1/chat/completions -H "Authorization: Bearer $V53729_MASTER_KEY" -H 'content-type: application/json' \
    -d "{\"model\":\"qwen\",\"max_tokens\":400,\"messages\":[{\"role\":\"user\",\"content\":\"[nested-2w-tip-55505] What is 17*23? Answer with the number only.\"}],\"extra_body\":{\"enable_thinking\":$et}}"
done

Two-worker proxy, baseline (same config, command and curl loop as the head block, message tag nested-2w-base):

INFO:     Started parent process [46507]
INFO:     Started server process [46522]
INFO:     Started server process [46521]
extra_body.enable_thinking=true | id=chatcmpl-daeac6cc-9eee-9d77-a54a-c2763bb523c4 | content=391 | reasoning_chars=1462 | completion_tokens=630 | x-litellm-cache-key=absent
extra_body.enable_thinking=false | id=chatcmpl-daeac6cc-9eee-9d77-a54a-c2763bb523c4 | content=391 | reasoning_chars=1462 | completion_tokens=630 | x-litellm-cache-key=v53729-proxy:d2b5a46df2ff8667d6503c2e45cf18b9cf35021b1b5b0974dffb0a9175e52708
extra_body.enable_thinking=true | id=chatcmpl-daeac6cc-9eee-9d77-a54a-c2763bb523c4 | content=391 | reasoning_chars=1462 | completion_tokens=630 | x-litellm-cache-key=v53729-proxy:d2b5a46df2ff8667d6503c2e45cf18b9cf35021b1b5b0974dffb0a9175e52708
extra_body.enable_thinking=false | id=chatcmpl-daeac6cc-9eee-9d77-a54a-c2763bb523c4 | content=391 | reasoning_chars=1462 | completion_tokens=630 | x-litellm-cache-key=v53729-proxy:d2b5a46df2ff8667d6503c2e45cf18b9cf35021b1b5b0974dffb0a9175e52708

Neither commit printed the "workers flag is ignored" warning, so the two-worker check stands for both.

Two-worker proxy at af1a80aec0877ebb620d4c539b7ac0b444f1cc10, saved output, full ids and keys

INFO:     Started parent process [55287]
INFO:     Started server process [55375]
INFO:     Started server process [55376]
extra_body.enable_thinking=true | id=chatcmpl-629a987c-0325-9fed-b128-3a2de8dd466e | content=391 | reasoning_chars=656 | completion_tokens=295 | x-litellm-cache-key=absent
extra_body.enable_thinking=false | id=chatcmpl-d0ac7399-c5d4-9af1-a6ac-9c79938e2fa9 | content=391 | reasoning_chars=0 | completion_tokens=3 | x-litellm-cache-key=absent
extra_body.enable_thinking=true | id=chatcmpl-629a987c-0325-9fed-b128-3a2de8dd466e | content=391 | reasoning_chars=656 | completion_tokens=295 | x-litellm-cache-key=v53729-proxy:fdc10b2a90a857d725e072d36308ac91295197fa320820fe6697939700336438
extra_body.enable_thinking=false | id=chatcmpl-d0ac7399-c5d4-9af1-a6ac-9c79938e2fa9 | content=391 | reasoning_chars=0 | completion_tokens=3 | x-litellm-cache-key=v53729-proxy:df3aac86e04a3377dd18282585a42f59e7c3e86332569405915a2b9f7ea3dde0

Redis held exactly 2 keys under v53729-proxy* afterwards, and the log has no "workers flag is ignored" warning.

Differences from what I sent before:

  • proxy_config_2w.yaml: none. The file is unchanged since 19:29 UTC and matches the block I sent byte for byte.
  • Command: the same, python litellm/proxy/proxy_cli.py --config proxy_config_2w.yaml --port 4531 --num_workers 2 --detailed_debug --reload --use_v2_migration_resolver with DATABASE_URL unset and DASHSCOPE_API_KEY, V53729_MASTER_KEY set.
  • Curl loop: the same. Only the message tag differs, [nested-2w-tip-55505] in place of [nested-2w-head].

Nothing was rerun for this. Coverage JSON and all logs are preserved in ~/verif-53729/logs.

Private verification session. Commands and measured outcomes are included here so reviewers do not need access to it.

Type

Bug Fix

Caveats

Low

  • Newly keyed bodies miss existing entries once and repopulate.
  • Dictionary ordering follows the existing formatter.
  • Flattened top-level provider kwargs retain the existing opt-in behavior.
  • Semantic scope was checked without a live vector store.
  • Live coverage used one provider, not a local vLLM server.
  • An 8 MiB body used about 17 MB peak hashing memory.
  • Equivalent reasoning aliases can now populate separate entries.
  • Proxy opt-in mode was not separately tested live.
  • Worker startup was verified, per-call worker attribution was not recorded.
  • A third-turn cache bypass was observed on both revisions.
  • One-shot iterators and non-string-key pairs retain their previous handling.

Final Attestation

  • Tests and verification cover the affected behavior and compatibility boundaries

Note

Medium Risk
Changes default cache key material for many requests; existing entries may miss until repopulated, but this fixes incorrect cache hits across differing provider options.

Overview
By default, extra_body now participates in response cache keys, so requests that differ only by provider options (for example chat_template_kwargs.enable_thinking) no longer share one cached completion.

The cache layer parses extra_body from plain dicts, other mappings, and list/tuple key–value pairs, ignores empty or meaningless values, and still routes return_token_ids and continuation_token through the existing dedicated key fragments. When enable_caching_on_provider_specific_optional_params is on, behavior for full extra_body serialization is unchanged.

Coverage adds parametrized key preimage, semantic-scope, and end-to-end acompletion tests for these shapes and edge cases.

Reviewed by Cursor Bugbot for commit 6409a88. Bugbot is set up for automated code reviews on this repo. Configure here.

Two requests whose extra_body differed (for example chat_template_kwargs.enable_thinking)
shared one cache entry unless enable_caching_on_provider_specific_optional_params was set.
The default key now includes extra_body minus continuation_token and return_token_ids,
which keep their existing keys. Omitted, empty and non-dict extra_body, and every key
under the flag, are unchanged.

Fixes #53729
@joshua-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@greptileai review

@veria-ai

veria-ai Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

No security issues were found in this pull request.

Reviews

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@veria-ai

@greptile-apps

greptile-apps Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge, with no outstanding findings.

Summary

The PR adds extra_body to response cache keys by default, keeping different provider options from sharing cached replies.

  • Requests with different extra_body options use separate cached replies.

Reviews (4) · Last reviewed commit: "fix(caching): type the extra_body pair s..." · Reviewed by Greptile

Comment thread litellm/caching/caching.py Resolved
Comment thread litellm/caching/caching.py Resolved

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

… pairs

MappingProxyType, UserDict and list or tuple of (key, value) pairs reach the provider
like a dict on OpenAI-SDK routes, but the default cache key still ignored them, so
requests with different bodies shared one entry. They now key like the equivalent
dict, with the last duplicate pair winning. Truthy token fields stay in the body for
these shapes because the dict-only token fragment never sees them, and falsy ones
still count as absent. Malformed sequences, strings and one-shot iterators are still
ignored, and every key under the opt-in flag is unchanged.
…) does

dict(["ab"]) forwards {"a": "b"}, so a list or tuple of two-character strings now
keys like the equivalent dict instead of sharing the plain key. Shorter or longer
string items are still ignored.
@joshua-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@greptileai review

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@veria-ai

… items

Move the existing cast from the dict guard, which now reuses as_str_mapping, to the list/tuple guard so basedpyright sees Sequence[object]. Runtime behavior is unchanged.
@joshua-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@greptileai review

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@veria-ai

@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 6409a88. Configure here.

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@greptileai review

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

lgtm

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]: extra_body is left out of the response cache key by default

2 participants