Skip to content

feat(litellm): pass-through cache_control_injection_points for Anthropic prompt caching - #2610

Merged
naorpeled merged 2 commits into
mainfrom
claude/pr-2405-finalize-ac42b0
Aug 8, 2026
Merged

naorpeled merged 2 commits into
mainfrom
claude/pr-2405-finalize-ac42b0

Conversation

@naorpeled

Copy link
Copy Markdown
Member

Supersedes #2405 (the original PR's branch is on an archived, read-only fork and can no longer be rebased/pushed to). Rebased onto current main, with all Qodo findings addressed. Original author credited via Co-authored-by.

Summary

Exposes LiteLLM's cache_control_injection_points kwarg via the [litellm] section of configuration.toml / .pr_agent.toml, enabling Anthropic prompt caching for self-hosted setups. Backwards compatible — the default is an empty list, so an absent/empty setting keeps current behavior (no caching).

Usage

[litellm]
cache_control_injection_points = [{location = "message", role = "system"}]

Qodo findings addressed

  • TypeError on the natural config spelling — a TOML array is parsed by Dynaconf into a native Python list, and json.loads(list) used to crash. The value is now accepted as a native list directly, with a JSON-string fallback for environment-variable overrides.
  • Config errors were retried — parsing/validation moved into a helper invoked before chat_completion's retry-wrapped body, so a malformed value raises a ValueError config error immediately instead of being wrapped as openai.APIError and retried.
  • kwargs overwrite — assignment uses kwargs.setdefault(...) to guard against clobbering an existing value.
  • Commented-out/dead config — documented as an active default (cache_control_injection_points = []) rather than commented example lines.

Tests

New tests/unittest/test_litellm_cache_control_injection_points.py (8 cases: native list, JSON string, absent/empty backwards-compat, invalid JSON not retried, non-list rejected). Full unit suite passes (1720 passed).

Co-authored-by: Mongol Agent mongol@chifat.ru

…pic prompt caching

Expose LiteLLM's cache_control_injection_points kwarg via the [litellm] section
of configuration.toml / .pr_agent.toml, enabling Anthropic prompt caching for
self-hosted PR-Agent setups. LiteLLM supports the kwarg natively
(https://docs.litellm.ai/docs/tutorials/prompt_caching); PR-Agent did not
surface it. Backwards compatible: the default is an empty list, so an
absent/empty setting keeps current behavior (no caching).

The value is accepted as a native TOML array (Dynaconf yields a Python list) or,
for env-var overrides, a JSON string. It is validated in a helper invoked before
chat_completion's retry-wrapped body, so a malformed value raises a ValueError
config error immediately instead of being wrapped as openai.APIError and
retried. Assignment uses setdefault to avoid overwriting a value already in
kwargs.

Co-authored-by: Mongol Agent <mongol@chifat.ru>
@github-actions github-actions Bot added the feature 💡 label Aug 8, 2026
@qodo-free-for-open-source-projects

Copy link
Copy Markdown
Contributor

PR Summary by Qodo

Expose LiteLLM cache_control_injection_points for Anthropic prompt caching

✨ Enhancement ⚙️ Configuration changes 🧪 Tests 🕐 20-40 Minutes

Grey Divider

AI Description

• Surface LiteLLM cache_control_injection_points via [litellm] config for Anthropic prompt
 caching.
• Validate/parse config pre-retry to avoid retrying deterministic config errors.
• Add unit tests covering TOML list, JSON env override, and invalid/empty behaviors.
Diagram

graph TD
  A["configuration.toml"] --> B(["Dynaconf get_settings"]) --> C[["LiteLLMAIHandler.chat_completion"]] --> D["_resolve_cache_control_injection_points"] --> E{"Valid list?"} --> F["kwargs.setdefault(...)"] --> G(["LiteLLM acompletion()"]) --> H(["Anthropic model"])
  E -- "no" --> I["ValueError (config error)"]
  subgraph Legend
    direction LR
    _cfg["Config file"] ~~~ _svc(["Runtime settings/external"]) ~~~ _mod[["Handler/module"]] ~~~ _dec{"Decision"} ~~~ _err["Error"]
  end
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Schema-validate injection points (Pydantic/dataclass model)
  • ➕ Stronger guarantees (e.g., require dicts with expected keys like location/role)
  • ➕ Clearer error messages with per-field context
  • ➕ Easier to extend if additional LiteLLM prompt-caching options are surfaced
  • ➖ Introduces extra dependency/complexity at the config boundary
  • ➖ May be overly strict vs LiteLLM’s own accepted shapes
  • ➖ Requires keeping schema aligned with upstream LiteLLM docs/behavior
2. Treat the setting as JSON-only (string) across all sources
  • ➕ Single parsing path; simpler validation logic
  • ➕ Avoids subtle type differences between TOML/env sources
  • ➖ Worse UX for TOML users (less natural syntax)
  • ➖ More brittle (quoting/escaping) in config files
  • ➖ Contradicts Dynaconf’s native TOML parsing behavior

Recommendation: Current approach is a good balance: accept Dynaconf’s native TOML list output, keep a JSON-string fallback for env overrides, and validate before the retry-wrapped call to prevent noisy retries. If future requirements need stricter guarantees, consider adding optional schema validation, but the lightweight list-only guard is appropriate for now.

Files changed (3) +161 / -0

Enhancement (1) +33 / -0
litellm_ai_handler.pyParse/validate cache_control_injection_points and pass through to LiteLLM +33/-0

Parse/validate cache_control_injection_points and pass through to LiteLLM

• Adds a helper to resolve 'LITELLM.CACHE_CONTROL_INJECTION_POINTS' from settings, accepting either a native list (TOML) or a JSON string (env override) and rejecting malformed values with ValueError. Moves parsing/validation ahead of the retry-wrapped body so deterministic config errors are not retried. Injects the kwarg via 'kwargs.setdefault(...)' to avoid overwriting an existing caller-provided value.

pr_agent/algo/ai_handlers/litellm_ai_handler.py

Tests (1) +127 / -0
test_litellm_cache_control_injection_points.pyAdd unit tests for cache_control_injection_points config boundary behavior +127/-0

Add unit tests for cache_control_injection_points config boundary behavior

• Introduces tests covering native TOML list pass-through, JSON-string parsing for env overrides, backwards-compatible empty/absent behavior, and fail-fast ValueError for invalid JSON or non-list values (ensuring no retries and no model calls).

tests/unittest/test_litellm_cache_control_injection_points.py

Other (1) +1 / -0
configuration.tomlDocument default cache_control_injection_points setting in [litellm] +1/-0

Document default cache_control_injection_points setting in [litellm]

• Adds an active default 'cache_control_injection_points = []' with inline documentation and an example, enabling self-hosted users to configure Anthropic prompt caching through LiteLLM.

pr_agent/settings/configuration.toml

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

Code Review by Qodo

🐞 Bugs (1) 📘 Rule violations (0) 📜 Skill insights (0)

Grey Divider


Remediation recommended

1. Entries not validated 🐞 Bug ≡ Correctness ⭐ New
Description
_resolve_cache_control_injection_points() only validates the top-level value is a list, even
though the repo’s own examples document a list of objects containing fields like location and
role. This allows malformed list contents to pass “validation” and be forwarded into kwargs,
undermining the intent to surface deterministic configuration errors early.
Code

pr_agent/algo/ai_handlers/litellm_ai_handler.py[R527-529]

+        if not isinstance(cache_control_injection_points, list):
+            raise ValueError("LITELLM.CACHE_CONTROL_INJECTION_POINTS must be a JSON/TOML array")
+        return cache_control_injection_points
Evidence
The helper’s doc/config examples describe a list of objects with specific fields, but the
implementation only checks isinstance(..., list) and then returns the list unchanged; tests also
only cover a list-of-dicts “happy path,” leaving malformed list contents unhandled at the config
boundary.

pr_agent/algo/ai_handlers/litellm_ai_handler.py[506-529]
pr_agent/settings/configuration.toml[356-366]
tests/unittest/test_litellm_cache_control_injection_points.py[56-81]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`_resolve_cache_control_injection_points()` currently checks only that `LITELLM.CACHE_CONTROL_INJECTION_POINTS` is a list, but does not validate the list entries despite the documented format being a list of inline tables/objects (e.g., `{location="message", role="system"}`). This means invalid entry shapes (e.g., strings, numbers, or dicts missing required keys) will pass through the “validated” boundary and be forwarded.

## Issue Context
The new option is intended to fail fast with a clear `ValueError` for malformed config before entering the retry-wrapped model call; validating only the outer container leaves a class of malformed configs undetected at this boundary.

## Fix Focus Areas
- pr_agent/algo/ai_handlers/litellm_ai_handler.py[506-529]
- tests/unittest/test_litellm_cache_control_injection_points.py[56-143]

## Implementation notes
- After confirming the value is a list, iterate each element and require it to be a `dict`/mapping.
- Enforce required keys (at minimum `location` and `role`) are present and are strings (and optionally validate allowed values if the project wants strictness).
- Add unit tests covering malformed list contents (e.g., `["message"]`, `[{}]`, `[{"location":"message"}]`) asserting a `ValueError` and that `acompletion` is not called.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Falsy config bypasses validation ✓ Resolved 🐞 Bug ≡ Correctness
Description
_resolve_cache_control_injection_points() returns None for any falsy value before validating
type, so malformed configs like 0, false, or {} are silently treated as “unset” instead of
raising ValueError as documented. This can hide operator misconfiguration and make caching
unexpectedly not apply.
Code

pr_agent/algo/ai_handlers/litellm_ai_handler.py[R517-519]

+        cache_control_injection_points = get_settings().get("LITELLM.CACHE_CONTROL_INJECTION_POINTS", None)
+        if not cache_control_injection_points:
+            return None
Evidence
The helper returns early on any falsy value, so type validation is skipped; this contradicts the
docstring that says malformed values raise ValueError.

pr_agent/algo/ai_handlers/litellm_ai_handler.py[506-527]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`_resolve_cache_control_injection_points()` currently uses `if not cache_control_injection_points: return None`, which treats *any* falsy value as “unset”. This bypasses the method’s own contract (“Raises ValueError on a malformed value”) for invalid-but-falsy types (e.g., `0`, `False`, `{}`).
### Issue Context
We still want backwards-compatible behavior for truly-unset/disabled values (e.g., `None`, `""`, `[]`). But other falsy non-list values should be rejected deterministically.
### Fix Focus Areas
- pr_agent/algo/ai_handlers/litellm_ai_handler.py[517-526]
### Suggested change
- Replace `if not cache_control_injection_points:` with an explicit disabled-value check, e.g.:
- `if cache_control_injection_points in (None, "", []): return None`
- Keep the existing JSON-string parsing and `list` type enforcement so invalid types always raise `ValueError`.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. Caching kwarg applied broadly ✓ Resolved 🐞 Bug ☼ Reliability
Description
When configured, chat_completion() injects cache_control_injection_points into kwargs for
every model/provider, even though the feature is Anthropic-specific. In multi-provider deployments
this broad injection can lead to provider-compatibility issues (the same function already avoids
injecting other unsupported params to prevent provider-side rejection when litellm.drop_params is
off).
Code

pr_agent/algo/ai_handlers/litellm_ai_handler.py[R742-743]

+                if cache_control_injection_points:
+                    kwargs.setdefault("cache_control_injection_points", cache_control_injection_points)
Evidence
The new injection block has no model/provider gating. Nearby logic explicitly avoids adding
unsupported params (the user field) to prevent provider-side request rejection when
litellm.drop_params is off, showing this is a real concern in this handler.

pr_agent/algo/ai_handlers/litellm_ai_handler.py[708-744]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`cache_control_injection_points` is intended for Anthropic prompt caching, but it is currently added for any request as long as the config is set. This differs from other params in the same function that are guarded to avoid passing unsupported parameters to providers.
### Issue Context
The codebase already contains logic acknowledging that some providers reject unsupported params when `litellm.drop_params` is off (see the `user` field handling). This setting should be scoped similarly to reduce unintended cross-provider impact.
### Fix Focus Areas
- pr_agent/algo/ai_handlers/litellm_ai_handler.py[708-744]
### Suggested change
- Only inject `cache_control_injection_points` when the target model/provider is Anthropic-compatible.
- Minimal heuristic: `if isinstance(model, str) and "claude" in model: ...`
- More robust: use `litellm.get_supported_openai_params(model=model)` (already used nearby) and inject only if it reports support for `cache_control_injection_points`.
- Optionally log a debug message when configured but skipped due to model/provider incompatibility.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


  • Author self-review: I have reviewed the code review findings, and addressed the relevant ones.

To customize comments, go to the Qodo configuration screen, or learn more in the docs.

Previous review results

Review updated until commit fcc8fec ⚖️ Balanced

Results up to commit 9eaa3d8


🐞 Bugs (2) 📘 Rule violations (0) 📜 Skill insights (0)


Remediation recommended
1. Falsy config bypasses validation 🐞 Bug ≡ Correctness
Description
_resolve_cache_control_injection_points() returns None for any falsy value before validating
type, so malformed configs like 0, false, or {} are silently treated as “unset” instead of
raising ValueError as documented. This can hide operator misconfiguration and make caching
unexpectedly not apply.
Code

pr_agent/algo/ai_handlers/litellm_ai_handler.py[R517-519]

+        cache_control_injection_points = get_settings().get("LITELLM.CACHE_CONTROL_INJECTION_POINTS", None)
+        if not cache_control_injection_points:
+            return None
Evidence
The helper returns early on any falsy value, so type validation is skipped; this contradicts the
docstring that says malformed values raise ValueError.

pr_agent/algo/ai_handlers/litellm_ai_handler.py[506-527]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`_resolve_cache_control_injection_points()` currently uses `if not cache_control_injection_points: return None`, which treats *any* falsy value as “unset”. This bypasses the method’s own contract (“Raises ValueError on a malformed value”) for invalid-but-falsy types (e.g., `0`, `False`, `{}`).

### Issue Context
We still want backwards-compatible behavior for truly-unset/disabled values (e.g., `None`, `""`, `[]`). But other falsy non-list values should be rejected deterministically.

### Fix Focus Areas
- pr_agent/algo/ai_handlers/litellm_ai_handler.py[517-526]

### Suggested change
- Replace `if not cache_control_injection_points:` with an explicit disabled-value check, e.g.:
 - `if cache_control_injection_points in (None, "", []): return None`
- Keep the existing JSON-string parsing and `list` type enforcement so invalid types always raise `ValueError`.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Caching kwarg applied broadly 🐞 Bug ☼ Reliability
Description
When configured, chat_completion() injects cache_control_injection_points into kwargs for
every model/provider, even though the feature is Anthropic-specific. In multi-provider deployments
this broad injection can lead to provider-compatibility issues (the same function already avoids
injecting other unsupported params to prevent provider-side rejection when litellm.drop_params is
off).
Code

pr_agent/algo/ai_handlers/litellm_ai_handler.py[R742-743]

+                if cache_control_injection_points:
+                    kwargs.setdefault("cache_control_injection_points", cache_control_injection_points)
Evidence
The new injection block has no model/provider gating. Nearby logic explicitly avoids adding
unsupported params (the user field) to prevent provider-side request rejection when
litellm.drop_params is off, showing this is a real concern in this handler.

pr_agent/algo/ai_handlers/litellm_ai_handler.py[708-744]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`cache_control_injection_points` is intended for Anthropic prompt caching, but it is currently added for any request as long as the config is set. This differs from other params in the same function that are guarded to avoid passing unsupported parameters to providers.

### Issue Context
The codebase already contains logic acknowledging that some providers reject unsupported params when `litellm.drop_params` is off (see the `user` field handling). This setting should be scoped similarly to reduce unintended cross-provider impact.

### Fix Focus Areas
- pr_agent/algo/ai_handlers/litellm_ai_handler.py[708-744]

### Suggested change
- Only inject `cache_control_injection_points` when the target model/provider is Anthropic-compatible.
 - Minimal heuristic: `if isinstance(model, str) and "claude" in model: ...`
 - More robust: use `litellm.get_supported_openai_params(model=model)` (already used nearby) and inject only if it reports support for `cache_control_injection_points`.
- Optionally log a debug message when configured but skipped due to model/provider incompatibility.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Qodo Logo

… models

Address Qodo review on #2610:
- _resolve_cache_control_injection_points() only short-circuits on genuinely
  unset/disabled values (None, "", []); other falsy-but-malformed values
  (0, False, {}) now fall through to type validation and raise ValueError, per
  the method's documented contract.
- cache_control_injection_points is Anthropic-specific, so injection is gated on
  Claude models (Anthropic API, Bedrock, Vertex) to avoid passing an unsupported
  param to other providers when litellm.drop_params is off, mirroring the nearby
  user-field gating. A debug line is logged when configured but skipped.

Tests extended: falsy-malformed values rejected; kwarg not injected for a
non-Anthropic model.
@naorpeled
naorpeled merged commit 0adbeaa into main Aug 8, 2026
6 checks passed
@naorpeled
naorpeled deleted the claude/pr-2405-finalize-ac42b0 branch August 8, 2026 16:15
@qodo-free-for-open-source-projects

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit fcc8fec

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant