Skip to content

feat(litellm): support Claude adaptive thinking - #2531

Merged
IsmaelMartinez merged 4 commits into
The-PR-Agent:mainfrom
Kyzcreig:feature/claude-adaptive-thinking
Aug 30, 2026
Merged

IsmaelMartinez merged 4 commits into
The-PR-Agent:mainfrom
Kyzcreig:feature/claude-adaptive-thinking

Conversation

@Kyzcreig

Copy link
Copy Markdown
Contributor

Summary

  • add a default-off config.enable_claude_adaptive_thinking compatibility flag
  • recognize provider-prefixed Claude Opus 4.7/4.8 and Claude Sonnet/Fable 5 model names without matching older or similarly named aliases
  • send the adaptive-thinking request shape (thinking={"type": "adaptive"}) with supported output_config.effort values and the required temperature value
  • preserve the existing extended-thinking path for all other Claude models
  • document that adaptive-only models must not be placed in the manual extended-thinking override

Compatibility

The feature is disabled by default, so existing requests are unchanged unless an operator explicitly enables enable_claude_adaptive_thinking.

Testing

  • focused adaptive/extended-thinking/chat-completion tests: 40 passed
  • full unit suite: 1350 passed, 1 skipped, 1 xfailed
  • new test file passes Ruff and Flake8 (--max-line-length=120)
  • changed-file Ruff/Flake8 results introduce no violations relative to clean upstream main

@github-actions github-actions Bot added the feature 💡 label Jul 18, 2026
@qodo-free-for-open-source-projects

Copy link
Copy Markdown
Contributor

PR Summary by Qodo

feat(litellm): opt-in Claude adaptive thinking for Opus 4.7/4.8 and Claude 5

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

Grey Divider

AI Description

• Add default-off flag to enable Claude adaptive thinking request payloads.
• Detect adaptive-only Claude model families across provider-prefixed model names.
• Add unit tests covering effort handling, temperature requirements, and opt-in behavior.
Diagram

graph TD
  A[Caller] --> B["LiteLLMAIHandler.chat_completion"] --> C{"Adaptive model + flag?"}
  C -- Yes --> D["Configure adaptive thinking"] --> G(["LiteLLM acompletion"])
  C -- No --> E{"Extended model + flag?"} -- Yes --> F["Configure extended thinking"] --> G
  E -- No --> G

  subgraph Legend
    direction LR
    _p["Process"] ~~~ _d{"Decision"} ~~~ _e(["External call"])
  end
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Provider/model-capability lookup (registry-driven)
  • ➕ Avoids regex maintenance and edge cases with model naming
  • ➕ Can encode additional constraints (e.g., required temperature) per model capability
  • ➖ Requires a reliable source of truth (LiteLLM registry or provider API)
  • ➖ More moving parts and potential version skew across environments
2. Config-driven allowlist for adaptive models
  • ➕ Operators can add/remove model identifiers without code changes
  • ➕ Reduces risk of false positives from regex matching
  • ➖ More operational burden; easier to misconfigure
  • ➖ Harder to keep consistent across deployments without centralized config management
3. Unify thinking mode selection into a single policy function
  • ➕ Makes precedence (adaptive > extended) explicit and easier to test/extend
  • ➕ Keeps chat_completion simpler and reduces future branching growth
  • ➖ Primarily refactor work; limited immediate functional benefit
  • ➖ Still needs a detection mechanism (regex or registry) underneath

Recommendation: The current approach (default-off flag + tight regex + explicit precedence over extended thinking) is a good compatibility-first rollout. If model naming expands further, consider moving detection into a centralized policy/registry layer to reduce regex churn and improve observability/debuggability.

Files changed (3) +157 / -1

Enhancement (1) +31 / -1
litellm_ai_handler.pyAdd adaptive-thinking model detection and request shaping for Claude +31/-1

Add adaptive-thinking model detection and request shaping for Claude

• Introduces regex-based detection for Claude models requiring the adaptive thinking API (Opus 4.7/4.8 and Sonnet/Fable 5). When enabled via config, sends 'thinking={"type":"adaptive"}', optionally adds 'output_config.effort' for supported values, and forces 'temperature=1'. Preserves the existing extended-thinking behavior for other Claude models.

pr_agent/algo/ai_handlers/litellm_ai_handler.py

Tests (1) +121 / -0
test_litellm_claude_adaptive_thinking.pyAdd unit tests for adaptive-thinking detection and payload semantics +121/-0

Add unit tests for adaptive-thinking detection and payload semantics

• Adds focused tests validating model detection across provider prefixes, opt-in gating, supported/unsupported effort values, and required 'temperature=1'. Verifies adaptive thinking does not leak into older Claude models and does not set the legacy 'reasoning_effort' kwarg in this mode.

tests/unittest/test_litellm_claude_adaptive_thinking.py

Other (1) +5 / -0
configuration.tomlAdd default-off enable_claude_adaptive_thinking flag with guidance +5/-0

Add default-off enable_claude_adaptive_thinking flag with guidance

• Adds 'enable_claude_adaptive_thinking=false' and documents the adaptive payload behavior and precedence over extended thinking. Notes that adaptive-only models should not be placed in the manual extended-thinking override list.

pr_agent/settings/configuration.toml

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

Copy link
Copy Markdown
Contributor

Code Review by Qodo

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

Grey Divider


Action required

1. _is_claude_adaptive_thinking_model() lacks type guard 📘 Rule violation ☼ Reliability
Description
The new adaptive-thinking model detector calls model.lower() without first ensuring model is a
string, which can raise at runtime if a non-string slips through. This introduces an unhandled
exception path in request handling.
Code

pr_agent/algo/ai_handlers/litellm_ai_handler.py[R361-368]

+    @staticmethod
+    def _is_claude_adaptive_thinking_model(model: str) -> bool:
+        """Return whether a Claude model requires the adaptive thinking API."""
+        normalized_model = model.lower().replace("_", "-").replace(".", "-")
+        return re.search(
+            r"claude-(?:opus-4-(?:7|8)|(?:sonnet|fable)-5)(?:[^0-9]|$)",
+            normalized_model,
+        ) is not None
Evidence
PR Compliance ID 3 requires anticipating and handling edge cases. The added
_is_claude_adaptive_thinking_model() calls model.lower() without validating type, and
chat_completion() invokes it directly, creating a new unhandled-exception path if model is not a
str.

Rule 3: Robust Error Handling
pr_agent/algo/ai_handlers/litellm_ai_handler.py[361-368]
pr_agent/algo/ai_handlers/litellm_ai_handler.py[590-593]

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

## Issue description
`LiteLLMAIHandler._is_claude_adaptive_thinking_model()` assumes `model` is a `str` and calls `model.lower()`. Elsewhere in `chat_completion()` the code defensively uses `isinstance(model, str)` checks, so passing a non-string model is a plausible edge case; the new adaptive-thinking path can now raise `AttributeError`.

## Issue Context
The adaptive-thinking path is reached from `chat_completion()` before extended-thinking logic. If `model` is not a string, `_is_claude_adaptive_thinking_model(model)` will raise and fail the request.

## Fix Focus Areas
- pr_agent/algo/ai_handlers/litellm_ai_handler.py[361-368]
- pr_agent/algo/ai_handlers/litellm_ai_handler.py[590-593]

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



Remediation recommended

2. Seed check mismatch 🐞 Bug ≡ Correctness
Description
chat_completion() validates/sets seed using the original temperature argument, but adaptive
thinking overwrites kwargs["temperature"] to 1, so a call with temperature=0 can still send a seed
alongside an effective temperature of 1. This can bypass the intended seed/temperature guard and
lead to request errors or non-deterministic behavior despite seed being set.
Code

pr_agent/algo/ai_handlers/litellm_ai_handler.py[R370-382]

+    def _configure_claude_adaptive_thinking(self, model: str, kwargs: dict) -> dict:
+        """Configure thinking for Claude models that reject token budgets."""
+        kwargs["thinking"] = {"type": "adaptive"}
+        effort = get_settings().config.reasoning_effort
+        if effort in ("low", "medium", "high", "xhigh", "max"):
+            kwargs["output_config"] = {"effort": effort}
+        get_logger().info(
+            f"Using adaptive thinking for model {model}"
+            + (f" with output_config effort '{effort}'" if "output_config" in kwargs else "")
+        )
+        # temperature may only be set to 1 when thinking is enabled
+        kwargs["temperature"] = 1
+        return kwargs
Evidence
Adaptive thinking unconditionally sets kwargs["temperature"] = 1, but the seed guard later checks
if temperature > 0 using the original argument, not the mutated outgoing request, so the
validation can be bypassed by passing a nonpositive temperature argument.

pr_agent/algo/ai_handlers/litellm_ai_handler.py[370-382]
pr_agent/algo/ai_handlers/litellm_ai_handler.py[590-599]
pr_agent/algo/ai_handlers/litellm_ai_handler.py[603-609]

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

### Issue description
Adaptive thinking forces `kwargs["temperature"] = 1`, but later seed validation uses the `temperature` function parameter rather than the effective outgoing temperature in `kwargs`. This allows inconsistent payload construction (e.g., passing `temperature=0` + `seed>=0` will pass validation but still send `temperature=1`).

### Issue Context
- Adaptive thinking mutates `kwargs` before the seed block.
- Seed validation should reflect what will actually be sent to LiteLLM (`kwargs`).

### Fix Focus Areas
- pr_agent/algo/ai_handlers/litellm_ai_handler.py[370-382]
- pr_agent/algo/ai_handlers/litellm_ai_handler.py[590-609]
- pr_agent/algo/ai_handlers/litellm_ai_handler.py[603-609]

### Suggested change
Derive an `effective_temperature = kwargs.get("temperature", temperature)` immediately before the seed guard and use that for the `temperature > 0` check (and/or skip the check when the outgoing request has no temperature key).

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


3. Adaptive regex overmatches 🐞 Bug ≡ Correctness
Description
_is_claude_adaptive_thinking_model() uses an unanchored substring regex, so unrelated model IDs that
merely contain a matching substring can be misclassified as adaptive-only Claude models. When
enabled, this will incorrectly force Claude-specific thinking/output_config and set
temperature=1 on those requests.
Code

pr_agent/algo/ai_handlers/litellm_ai_handler.py[R361-368]

+    @staticmethod
+    def _is_claude_adaptive_thinking_model(model: str) -> bool:
+        """Return whether a Claude model requires the adaptive thinking API."""
+        normalized_model = model.lower().replace("_", "-").replace(".", "-")
+        return re.search(
+            r"claude-(?:opus-4-(?:7|8)|(?:sonnet|fable)-5)(?:[^0-9]|$)",
+            normalized_model,
+        ) is not None
Evidence
The regex is applied via re.search() without anchoring, and its boolean result controls whether
the handler forces adaptive-thinking kwargs and temperature=1 for that request.

pr_agent/algo/ai_handlers/litellm_ai_handler.py[361-368]
pr_agent/algo/ai_handlers/litellm_ai_handler.py[449-477]
pr_agent/algo/ai_handlers/litellm_ai_handler.py[590-599]
pr_agent/algo/ai_handlers/litellm_ai_handler.py[370-382]

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

### Issue description
The adaptive-thinking model detector uses `re.search()` with a pattern that can match anywhere in the model string. This can misclassify model IDs where the matching token appears as part of a larger word/path segment (e.g., `.../myclaude-opus-4-8...`).

### Issue Context
The detector is applied directly to the user-provided `model` string inside `chat_completion()`, and if it returns true it mutates the outgoing request.

### Fix Focus Areas
- pr_agent/algo/ai_handlers/litellm_ai_handler.py[361-368]
- pr_agent/algo/ai_handlers/litellm_ai_handler.py[590-599]

### Suggested change
Tighten the regex to require a non-alphanumeric boundary before `claude-` (e.g., `(?<![a-z0-9])claude-(...)`) or otherwise parse/provider-split the model string and match only on the actual Claude model component. Add a unit test that proves `"anthropic/myclaude-opus-4-8"` does **not** match.

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



Informational

4. Extended override footgun 🐞 Bug ☼ Reliability
Description
If an operator (incorrectly) adds adaptive-only Claude models to
claude_extended_thinking_models_override and enables extended thinking while adaptive thinking is
disabled, the code will still send the legacy budget_tokens payload even though the repo documents
those models reject it with HTTP 400.
Code

pr_agent/algo/ai_handlers/litellm_ai_handler.py[R591-598]

+                if self._is_claude_adaptive_thinking_model(model) and get_settings().config.get(
+                        "enable_claude_adaptive_thinking", False):
+                    kwargs = self._configure_claude_adaptive_thinking(model, kwargs)
+                elif (
+                    model in self.claude_extended_thinking_models
+                    and get_settings().config.get("enable_claude_extended_thinking", False)
+                ):
                    kwargs = self._configure_claude_extended_thinking(model, kwargs)
Evidence
The repo documents that Opus 4.7/4.8 and Claude 5 models reject budget_tokens, but the
chat_completion branching will still route them into the extended-thinking path when adaptive
thinking is disabled and extended thinking is enabled (and the model is in the configured override
list).

pr_agent/algo/init.py[377-383]
pr_agent/algo/ai_handlers/litellm_ai_handler.py[590-599]
pr_agent/algo/ai_handlers/litellm_ai_handler.py[246-266]

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

### Issue description
Adaptive-only Claude models are known to reject the extended-thinking `budget_tokens` shape, but the current branching only uses the adaptive path when `enable_claude_adaptive_thinking` is true. With adaptive disabled and extended thinking enabled (plus an override list that includes an adaptive-only model), requests will be shaped in a way the repo already warns will 400.

### Issue Context
This is an unsupported configuration (documented), but adding a defensive guard would reduce operator error impact.

### Fix Focus Areas
- pr_agent/algo/ai_handlers/litellm_ai_handler.py[246-266]
- pr_agent/algo/ai_handlers/litellm_ai_handler.py[590-599]

### Suggested change
If `_is_claude_adaptive_thinking_model(model)` is true and extended thinking is enabled, either:
- skip `_configure_claude_extended_thinking()` regardless of override membership and log a warning that the model is adaptive-only, or
- validate `claude_extended_thinking_models_override` during `__init__` and warn/remove adaptive-only models from that list.

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


Grey Divider

ⓘ  1 issues published inline · 4 in summary

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

Qodo Logo

Comment on lines +361 to +368
@staticmethod
def _is_claude_adaptive_thinking_model(model: str) -> bool:
"""Return whether a Claude model requires the adaptive thinking API."""
normalized_model = model.lower().replace("_", "-").replace(".", "-")
return re.search(
r"claude-(?:opus-4-(?:7|8)|(?:sonnet|fable)-5)(?:[^0-9]|$)",
normalized_model,
) is not None

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.

Action required

1. _is_claude_adaptive_thinking_model() lacks type guard 📘 Rule violation ☼ Reliability

The new adaptive-thinking model detector calls model.lower() without first ensuring model is a
string, which can raise at runtime if a non-string slips through. This introduces an unhandled
exception path in request handling.
Agent Prompt
## Issue description
`LiteLLMAIHandler._is_claude_adaptive_thinking_model()` assumes `model` is a `str` and calls `model.lower()`. Elsewhere in `chat_completion()` the code defensively uses `isinstance(model, str)` checks, so passing a non-string model is a plausible edge case; the new adaptive-thinking path can now raise `AttributeError`.

## Issue Context
The adaptive-thinking path is reached from `chat_completion()` before extended-thinking logic. If `model` is not a string, `_is_claude_adaptive_thinking_model(model)` will raise and fail the request.

## Fix Focus Areas
- pr_agent/algo/ai_handlers/litellm_ai_handler.py[361-368]
- pr_agent/algo/ai_handlers/litellm_ai_handler.py[590-593]

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

@IsmaelMartinez

Copy link
Copy Markdown
Collaborator

Checked the model set against main. pr_agent/algo/__init__.py:399-404 documents the adaptive-only models as Claude Opus 4.7/4.8, Opus 5, Sonnet 5 and Fable 5 — but _is_claude_adaptive_thinking_model's regex, claude-(?:opus-4-(?:7|8)|(?:sonnet|fable)-5), does not match claude-opus-5.

So Opus 5 would keep taking the extended-thinking path while its siblings get adaptive. Deliberate, or should the alternation include opus-5?

@IsmaelMartinez

Copy link
Copy Markdown
Collaborator

Following up on the model-gate point above (still open at the current head) — I re-ran this branch's tests against current main with the changes applied: 11/11 pass. Two more things surfaced:

  1. kwargs["temperature"] = 1 should be dropped — all of these models are in NO_SUPPORT_TEMPERATURE_MODELS (added after [Bug] temperature parameter sent to claude-opus-4-7 causes 400 from Anthropic #2400/Opus 4.7/4.8 and Fable 5 reject temperature → /improve & /review 400 and silently fall back #2449), and Anthropic documents sampling params as removed on several of them.
  2. Main is now on litellm 1.95.0, which natively maps reasoning_effort to thinking: adaptive + output_config.effort for adaptive Claude models (including Opus 5, Bedrock/Vertex, and per-model effort validation). A reasoning_effort passthrough might replace the hand-rolled regex entirely — and would close the gate gap as a side effect.

Happy to re-test after changes.

Kyzcreig pushed a commit to Kyzcreig/pr-agent that referenced this pull request Aug 17, 2026
… stop sending temperature

Two fixes from review on The-PR-Agent#2531, both verified against current main:

- The detector regex matched Opus 4.7/4.8, Sonnet 5 and Fable 5 but not
  claude-opus-5, even though the CLAUDE_EXTENDED_THINKING_MODELS comment names
  Opus 5 as adaptive-only. Opus 5 would have kept taking the extended-thinking
  budget_tokens path and 400'd. Caught by @IsmaelMartinez.

- Drop kwargs["temperature"] = 1 in the adaptive path. All adaptive-thinking
  Claude models are in NO_SUPPORT_TEMPERATURE_MODELS (post The-PR-Agent#2400/The-PR-Agent#2449) and
  Anthropic documents sampling params as removed on them; the adaptive
  configurator now strips temperature instead of setting it.
  Caught by @IsmaelMartinez.

Co-authored-by: IsmaelMartinez <IsmaelMartinez@users.noreply.github.com>
@Kyzcreig
Kyzcreig force-pushed the feature/claude-adaptive-thinking branch from dbfc6f0 to 1ed6669 Compare August 17, 2026 00:54
@Kyzcreig

Copy link
Copy Markdown
Contributor Author

@IsmaelMartinez — both findings verified and fixed at head 1ed6669; thanks for re-testing against main, twice.

the regex, claude-(?:opus-4-(?:7|8)|(?:sonnet|fable)-5), does not match claude-opus-5. Deliberate, or should the alternation include opus-5?

Not deliberate — a straight omission, and main's own comment block (pr_agent/algo/__init__.py) names Opus 5 as adaptive-only. Without your catch, Opus 5 would have kept taking the budget_tokens extended-thinking path and 400'd exactly the way this PR exists to prevent. Alternation is now (?:opus|sonnet|fable)-5, with claude-opus-5 / bedrock/us.anthropic.claude-opus-5 positive cases and a claude-opus-50 negative case in the params.

kwargs["temperature"] = 1 should be dropped — all of these models are in NO_SUPPORT_TEMPERATURE_MODELS

Confirmed against main — every adaptive-gate model is in that list (added after #2400/#2449). The adaptive configurator now does kwargs.pop("temperature", None) instead of setting it, so it also strips one if an earlier code path added it.

A reasoning_effort passthrough might replace the hand-rolled regex entirely

Agreed that's the better end state now that main is on litellm ≥1.95 — but I'd rather land this as the explicit, tested version first and do the litellm-native passthrough as a follow-up, since it changes behavior for Bedrock/Vertex prefixes too and deserves its own test surface. If maintainers prefer the passthrough shape up front, happy to rework.

Rebased onto current main; full unit suite green (1762 passed). Your offer to re-test is very welcome — this head is the one to hit.

Co-authored credit is in the commit.

@qodo-code-review

qodo-code-review Bot commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

Code Review by Qodo

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

Grey Divider


Remediation recommended

1. Test leaks LiteLLM globals ✓ Resolved 🐞 Bug ☼ Reliability
Description
The new adaptive-thinking unit tests construct LiteLLMAIHandler() but do not snapshot/restore
process-wide litellm/openai globals that LiteLLMAIHandler.__init__ mutates (e.g., litellm.api_key
and litellm.openai_key when OPENAI_API_KEY is absent). This can make the test suite order-dependent
and flaky when other tests assume a clean LiteLLM global state.
Code

tests/unittest/test_litellm_claude_adaptive_thinking.py[R41-44]

+        completion.return_value = _response()
+        handler = LiteLLMAIHandler()
+        await handler.chat_completion(model=model, system="sys", user="usr")
+        return completion.call_args.kwargs
Relevance

●●● Strong

They’ve accepted fixes to snapshot/restore LiteLLM globals to prevent cross-test leakage/flakiness.

PR-#2464
PR-#2293

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The test file instantiates LiteLLMAIHandler() inside helper code without any restore fixture.
LiteLLMAIHandler.__init__ contains branches that explicitly mutate
litellm.api_key/litellm.openai_key when OPENAI_API_KEY is absent; other tests in this repo add
autouse fixtures to restore these globals for this reason.

tests/unittest/test_litellm_claude_adaptive_thinking.py[35-44]
pr_agent/algo/ai_handlers/litellm_ai_handler.py[54-73]
tests/unittest/test_litellm_openrouter_controls.py[33-52]

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

### Issue description
`tests/unittest/test_litellm_claude_adaptive_thinking.py` creates `LiteLLMAIHandler()` instances, but the module does not isolate/restore global state (`litellm.api_key`, `litellm.openai_key`, `openai.api_key`) that `LiteLLMAIHandler.__init__` can mutate. This can leak into subsequent tests.

### Issue Context
Other LiteLLM-related test modules in this repo explicitly snapshot/restore these globals via an autouse fixture because `LiteLLMAIHandler.__init__` modifies them.

### Fix Focus Areas
- tests/unittest/test_litellm_claude_adaptive_thinking.py[35-44]

### Suggested fix
Add an `@pytest.fixture(autouse=True)` similar to `test_litellm_openrouter_controls.py` that:
- snapshots `litellm.api_key`, `litellm.openai_key`, and `openai.api_key`
- (optionally) snapshots relevant env vars like `OPENAI_API_KEY` / `AWS_USE_IMDS`
- restores them in `finally`

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


2. Overbroad Claude model match 🐞 Bug ≡ Correctness
Description
_is_claude_adaptive_thinking_model() searches for a Claude substring anywhere in the normalized
model string, so non-Claude model identifiers that merely contain that token can be misclassified
and get Anthropic-specific thinking/output_config kwargs when enable_claude_adaptive_thinking is
enabled. This can break requests for providers whose model naming conventions (e.g., arbitrary
serving-endpoint names) legitimately include “claude-*” as part of a larger token.
Code

pr_agent/algo/ai_handlers/litellm_ai_handler.py[R405-409]

+        normalized_model = model.lower().replace("_", "-").replace(".", "-")
+        return re.search(
+            r"claude-(?:opus-4-(?:7|8)|(?:opus|sonnet|fable)-5)(?:[^0-9]|$)",
+            normalized_model,
+        ) is not None
Relevance

●●● Strong

Team often gates Anthropic-only kwargs to avoid breaking other providers; overbroad Claude match
risks that.

PR-#2610
PR-#2464

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The detector uses an unanchored regex over the full normalized model string, and chat_completion
applies adaptive-thinking based on that boolean. The Databricks docs show the model name after
databricks/ is just the serving endpoint name, demonstrating that non-Claude providers can
naturally include claude-* substrings in model identifiers.

pr_agent/algo/ai_handlers/litellm_ai_handler.py[402-409]
pr_agent/algo/ai_handlers/litellm_ai_handler.py[707-715]
docs/docs/usage-guide/changing_a_model.md[471-483]

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

### Issue description
`LiteLLMAIHandler._is_claude_adaptive_thinking_model()` matches `claude-...` anywhere in the model string after aggressive normalization (`.` -> `-`). That makes it possible to accidentally classify non-Claude model identifiers (e.g., provider endpoint names) as adaptive-Claude and inject Anthropic-specific kwargs.

### Issue Context
Adaptive thinking is applied in `chat_completion()` purely based on this predicate and the opt-in config flag. The repo docs also show providers (e.g., Databricks) where the model name after the provider prefix is an arbitrary serving endpoint name that can contain substrings like `claude-*`.

### Fix Focus Areas
- pr_agent/algo/ai_handlers/litellm_ai_handler.py[402-409]
- pr_agent/algo/ai_handlers/litellm_ai_handler.py[707-715]

### Suggested fix
1. Make the match boundary-aware so `claude-...` must start a true model segment, not appear mid-token. For example:
  - Stop replacing `.` with `-`, and instead allow `.` as a delimiter in the regex.
  - Use a regex like `r"(?:^|/|\.)claude-(?:opus-4-(?:7|8)|(?:opus|sonnet|fable)-5)(?:[^0-9]|$)"`.
2. Add (or extend) a unit test asserting that strings like `databricks/databricks-claude-opus-5` (or another non-Claude endpoint-like name containing `-claude-opus-5`) do **not** match.

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

Grey Divider

Context sources
✅ Compliance rules (platform): 34 rules
Review mode: ⚖️ Balanced: This changes runtime Claude model detection and request payload construction behind a config flag, with provider-specific matching and API compatibility implications; it warrants a careful single-pass review.

Grey Divider

Tip of the day
💡 Did you know, you can enable the Remediation agent and Qodo fixes findings in a dedicated fix PR

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

@IsmaelMartinez

Copy link
Copy Markdown
Collaborator

Thanks for turning both of those around, and for adding the claude-opus-50 negative case.

Verified locally: the regex matches the bare, Bedrock and OpenRouter forms and correctly rejects claude-opus-50; suite 1762 pass, and the new tests do fail without the fix.

Two things first. docs/docs/usage-guide/changing_a_model.md (~L587) still says adaptive-only models "reject budget_tokens and will error if you add them to the list", which this PR makes stale. And the new branch is an elif against extended thinking, so an adaptive-only model in claude_extended_thinking_models_override with enable_claude_adaptive_thinking unset still sends budget_tokens and 400s. The TOML comment warns about it, the code does not.

Agreed on leaving the litellm-native reasoning_effort passthrough as a follow-up.


import pytest

import pr_agent.algo.ai_handlers.litellm_ai_handler as litellm_handler

@IsmaelMartinez IsmaelMartinez left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nudging: the two points from 17 August are still open at this head, so this needs one more pass.

I re-checked against today's main: still merges clean, suite green, and the new tests fail without the change. I would leave Qodo's regex-breadth finding as is; an endpoint named ...claude-opus-5 almost certainly is that model, and the flag is opt-in.

The override path is the blocker. An adaptive-only model in claude_extended_thinking_models_override with enable_claude_adaptive_thinking unset still takes the extended branch and sends budget_tokens. Suggestion inline, and the suite stays green with it applied.

The docs note in changing_a_model.md still needs updating too. Happy to take this as soon as those two land.

Comment on lines 711 to 715
elif (
model in self.claude_extended_thinking_models
and get_settings().config.get("enable_claude_extended_thinking", False)
):
kwargs = self._configure_claude_extended_thinking(model, kwargs)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This is the override case: with enable_claude_adaptive_thinking unset, an adaptive-only model in claude_extended_thinking_models_override still lands here and gets budget_tokens. The TOML comment warns about it; the code does not enforce it.

Suggested change
elif (
model in self.claude_extended_thinking_models
and get_settings().config.get("enable_claude_extended_thinking", False)
):
kwargs = self._configure_claude_extended_thinking(model, kwargs)
elif model in self.claude_extended_thinking_models and get_settings().config.get(
"enable_claude_extended_thinking", False):
if self._is_claude_adaptive_thinking_model(model):
get_logger().warning(
f"Skipping extended thinking for {model}: adaptive-only models reject "
f"budget_tokens. Enable config.enable_claude_adaptive_thinking instead."
)
else:
kwargs = self._configure_claude_extended_thinking(model, kwargs)

return response


async def _run_completion(monkeypatch, model, reasoning_effort="medium", enabled=False):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Qodo's second finding here is worth taking: LiteLLMAIHandler.__init__ writes litellm.api_key/openai.api_key and reads AWS_USE_IMDS. test_litellm_openrouter_controls.py has a _restore_litellm_globals autouse fixture for exactly this; borrowing it keeps the file order-independent.

Kyzcreig pushed a commit to Kyzcreig/pr-agent that referenced this pull request Aug 30, 2026
Caught by @IsmaelMartinez in review on The-PR-Agent#2531: the adaptive-thinking branch was
an `elif` against extended thinking, so an adaptive-only model placed in
`claude_extended_thinking_models_override` with `enable_claude_adaptive_thinking`
unset still took the extended branch and sent `budget_tokens` -- the exact HTTP 400
this PR exists to prevent. As he put it, "The TOML comment warns about it, the code
does not."

The extended-thinking branch now checks `_is_claude_adaptive_thinking_model()` and
skips the payload with a warning that points at the right flag, using his inline
suggestion.

Also fixes the docs he flagged as made stale by this PR:
`changing_a_model.md` said adaptive-only models "will error if you add them to the
list"; they are now skipped with a warning instead. Adds Opus 5 to that note's model
list for consistency with the widened gate.

Tests: adds a regression test for the override path (fails without the guard) and one
proving ordinary extended-thinking models are undisturbed. Also adopts the
`_restore_litellm_globals` autouse fixture from `test_litellm_openrouter_controls.py`,
per his note that `LiteLLMAIHandler.__init__` mutates `litellm.api_key`/`openai.api_key`
and reads `AWS_USE_IMDS`, which made this file order-dependent.

tests/unittest: 1764 passed, 1 skipped, 1 xfailed.

Co-authored-by: IsmaelMartinez <IsmaelMartinez@users.noreply.github.com>
@Kyzcreig

Copy link
Copy Markdown
Contributor Author

@IsmaelMartinez — both points fixed at head f3fcc76. You were right on both.

the new branch is an elif against extended thinking, so an adaptive-only model in claude_extended_thinking_models_override with enable_claude_adaptive_thinking unset still sends budget_tokens and 400s. The TOML comment warns about it, the code does not.

Confirmed live at the previous head. I took your inline suggestion as written — the extended branch now checks _is_claude_adaptive_thinking_model() first and skips the payload with a warning naming the right flag. The reason this needed your eye and not just mine: the failure only shows up in a configuration the TOML explicitly tells people not to create, so nothing in my own test matrix was ever going to reach it. It's now a regression test that fails without the guard:

test_adaptive_only_model_in_extended_override_does_not_get_budget_tokens
  with guard:    passes
  guard removed: FAILED - assert 'thinking' not in {...}

Plus a companion test proving ordinary extended-thinking models (claude-opus-4-6) still get budget_tokens — the obvious way to break this fix is to over-broaden it.

docs/docs/usage-guide/changing_a_model.md (~L587) still says adaptive-only models "reject budget_tokens and will error if you add them to the list", which this PR makes stale.

Fixed, and you were more right than the note implied: the sentence was stale in two ways. It described an error that no longer happens (we now skip and warn), and its model list still omitted Opus 5 — the same omission you caught in the regex last time, sitting in the prose two files away. Both corrected.

I would leave Qodo's regex-breadth finding as is; an endpoint named ...claude-opus-5 almost certainly is that model, and the flag is opt-in.

Agreed, and left as is.

Also adopted the _restore_litellm_globals autouse fixture from test_litellm_openrouter_controls.py per your other note — you were right that __init__ mutates litellm.api_key/openai.api_key and reads AWS_USE_IMDS, which made this file order-dependent.

tests/unittest: 1764 passed, 1 skipped, 1 xfailed. Credit is in the commit trailer.

One ask, since it's the part I can't check from here: you've now caught two real defects by running this against your own main, both in the configuration space rather than the happy path. If you have a deployment that actually sets claude_extended_thinking_models_override, the warning-and-skip path is the one worth a look — I've asserted the request shape, but not what an operator sees in their logs when they hit it.

Kyzcreig and others added 3 commits August 30, 2026 07:47
Add opt-in adaptive thinking payloads for Claude Opus 4.7/4.8 and Claude 5 model families.

Tests: 1350 passed, 1 skipped, 1 xfailed.
… stop sending temperature

Two fixes from review on The-PR-Agent#2531, both verified against current main:

- The detector regex matched Opus 4.7/4.8, Sonnet 5 and Fable 5 but not
  claude-opus-5, even though the CLAUDE_EXTENDED_THINKING_MODELS comment names
  Opus 5 as adaptive-only. Opus 5 would have kept taking the extended-thinking
  budget_tokens path and 400'd. Caught by @IsmaelMartinez.

- Drop kwargs["temperature"] = 1 in the adaptive path. All adaptive-thinking
  Claude models are in NO_SUPPORT_TEMPERATURE_MODELS (post The-PR-Agent#2400/The-PR-Agent#2449) and
  Anthropic documents sampling params as removed on them; the adaptive
  configurator now strips temperature instead of setting it.
  Caught by @IsmaelMartinez.

Co-authored-by: IsmaelMartinez <IsmaelMartinez@users.noreply.github.com>
Caught by @IsmaelMartinez in review on The-PR-Agent#2531: the adaptive-thinking branch was
an `elif` against extended thinking, so an adaptive-only model placed in
`claude_extended_thinking_models_override` with `enable_claude_adaptive_thinking`
unset still took the extended branch and sent `budget_tokens` -- the exact HTTP 400
this PR exists to prevent. As he put it, "The TOML comment warns about it, the code
does not."

The extended-thinking branch now checks `_is_claude_adaptive_thinking_model()` and
skips the payload with a warning that points at the right flag, using his inline
suggestion.

Also fixes the docs he flagged as made stale by this PR:
`changing_a_model.md` said adaptive-only models "will error if you add them to the
list"; they are now skipped with a warning instead. Adds Opus 5 to that note's model
list for consistency with the widened gate.

Tests: adds a regression test for the override path (fails without the guard) and one
proving ordinary extended-thinking models are undisturbed. Also adopts the
`_restore_litellm_globals` autouse fixture from `test_litellm_openrouter_controls.py`,
per his note that `LiteLLMAIHandler.__init__` mutates `litellm.api_key`/`openai.api_key`
and reads `AWS_USE_IMDS`, which made this file order-dependent.

tests/unittest: 1764 passed, 1 skipped, 1 xfailed.

Co-authored-by: IsmaelMartinez <IsmaelMartinez@users.noreply.github.com>
@Kyzcreig
Kyzcreig force-pushed the feature/claude-adaptive-thinking branch from f3fcc76 to 4c66c9c Compare August 30, 2026 14:50
@Kyzcreig

Copy link
Copy Markdown
Contributor Author

Correction to the head SHA above: main moved while I was writing that comment (a new "Output token limit" section landed in changing_a_model.md, right where my docs edit sits), so f3fcc76 went briefly conflicted.

Rebased and resolved — kept both, my note plus the new section. Current head is 4c66c9c4, mergeable: MERGEABLE. Everything in the previous comment still applies; only the SHA changed.

tests/unittest/test_litellm_claude_adaptive_thinking.py: 16 passed. Flagging one thing so it isn't mistaken for my breakage: the full tests/unittest run is currently 43 failed, 2667 passed on this branch — and an identical 43 failures (same tests, test_webhook_logic_core.py / GitLab draft + bot-indicator cases) reproduce on pristine upstream/main at a64730af. They're pre-existing on main and untouched by this PR, but main is red right now if that's news.

@IsmaelMartinez IsmaelMartinez left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for turning both round, and for the override regression test in particular: that case only bites in a configuration the TOML tells people not to create, so it was never going to come out of your own matrix.

Both fixed, and the coverage is real. 16 pass on the merged tree, 14 go red with your tests against main's handler, and main does send thinking: {"type": "enabled", "budget_tokens": 2048} there.

On your ask, the operator sees:

WARNING | ...litellm_ai_handler:chat_completion:876 - Skipping extended thinking for anthropic/claude-opus-5: adaptive-only models reject budget_tokens. Enable config.enable_claude_adaptive_thinking instead.

Right flag, and the model interpolates. Nothing asserts it though, so a silent skip would keep the suite green.

Main is not red: a64730af gives 2694 passed and zero failures on a clean uv sync, and test_webhook_logic_core.py collects 37 tests in total, so it cannot carry 43 failures. Stale venv, most likely.

One inline, then this is good to go.

+ (f" with output_config effort '{effort}'" if "output_config" in kwargs else "")
)
# Adaptive-thinking Claude models have sampling parameters removed
# (NO_SUPPORT_TEMPERATURE_MODELS covers them after #2400/#2449), so

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This pop is load-bearing rather than defensive, and the comment above it is not quite right. bedrock/us.anthropic.claude-opus-4-7-v1:0 is not in NO_SUPPORT_TEMPERATURE_MODELS: the list carries bedrock/anthropic.claude-opus-4-7-v1:0 and bedrock/us.anthropic.claude-opus-4-7, but not the two combined. So for that id this pop is the only thing stopping a temperature reaching the model, and with the flag off one still goes. Worth saying that here, so nobody later removes the pop on the strength of the comment.

@IsmaelMartinez

Copy link
Copy Markdown
Collaborator

Correction to my own message above. The 37-test count does not settle it: you also named the GitLab draft and bot-indicator cases, and those live in test_gitlab_reviewer_assignment.py, which a64730af added and which collects 12. That is 49 across the two files you named, so 43 failures is reachable and my arithmetic argument against it was wrong.

I also could not reproduce it on any litellm from 1.93 through 1.98, in isolation or with a bare pytest, so the stale-venv line was a guess and I should not have offered it as a diagnosis. What does hold is the count: a64730af gives 2694 passed and zero failures here, and the merged tree 2712. If you paste your litellm version and the exact pytest invocation, I will try to reproduce it properly.

@qodo-code-review

qodo-code-review Bot commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Code Review by Qodo

Grey Divider

Sorry, something went wrong

We weren't able to complete the code review on our side. Please try again manually by commenting /agentic_review on this PR.

Grey Divider

Qodo Logo

@IsmaelMartinez IsmaelMartinez left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Carried the comment fix myself in 88fceb34 rather than send you round again for one line. It now says why the pop is load-bearing and names the bedrock id the list misses. Everything else here is yours.

Thanks for two rounds of fixes in a day, and for the regression test on the override case in particular.

@IsmaelMartinez
IsmaelMartinez merged commit 7267ae1 into The-PR-Agent:main Aug 30, 2026
5 checks passed
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.

3 participants