Repository navigation
feat(litellm): support Claude adaptive thinking - #2531
Conversation
PR Summary by Qodofeat(litellm): opt-in Claude adaptive thinking for Opus 4.7/4.8 and Claude 5
AI Description
Diagram
High-Level Assessment
Files changed (3)
|
Code Review by Qodo
1. _is_claude_adaptive_thinking_model() lacks type guard
|
| @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 |
There was a problem hiding this comment.
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
|
Checked the model set against main. So Opus 5 would keep taking the extended-thinking path while its siblings get adaptive. Deliberate, or should the alternation include |
|
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:
Happy to re-test after changes. |
… 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>
dbfc6f0 to
1ed6669
Compare
|
@IsmaelMartinez — both findings verified and fixed at head
Not deliberate — a straight omission, and main's own comment block (
Confirmed against main — every adaptive-gate model is in that list (added after #2400/#2449). The adaptive configurator now does
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. |
Code Review by Qodo
1.
|
|
Thanks for turning both of those around, and for adding the Verified locally: the regex matches the bare, Bedrock and OpenRouter forms and correctly rejects Two things first. Agreed on leaving the litellm-native |
|
|
||
| import pytest | ||
|
|
||
| import pr_agent.algo.ai_handlers.litellm_ai_handler as litellm_handler |
IsmaelMartinez
left a comment
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
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.
| 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): |
There was a problem hiding this comment.
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.
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>
|
@IsmaelMartinez — both points fixed at head
Confirmed live at the previous head. I took your inline suggestion as written — the extended branch now checks Plus a companion test proving ordinary extended-thinking models (
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.
Agreed, and left as is. Also adopted the
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 |
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>
f3fcc76 to
4c66c9c
Compare
|
Correction to the head SHA above: main moved while I was writing that comment (a new "Output token limit" section landed in Rebased and resolved — kept both, my note plus the new section. Current head is
|
IsmaelMartinez
left a comment
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
|
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 I also could not reproduce it on any litellm from 1.93 through 1.98, in isolation or with a bare |
IsmaelMartinez
left a comment
There was a problem hiding this comment.
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.
Summary
config.enable_claude_adaptive_thinkingcompatibility flagthinking={"type": "adaptive"}) with supportedoutput_config.effortvalues and the required temperature valueCompatibility
The feature is disabled by default, so existing requests are unchanged unless an operator explicitly enables
enable_claude_adaptive_thinking.Testing
40 passed1350 passed, 1 skipped, 1 xfailed--max-line-length=120)main