Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -188,11 +188,16 @@ def validate_anthropic_messages_environment(
return headers, api_base

@staticmethod
def _translate_reasoning_effort_to_anthropic(model: str, optional_params: Dict, custom_llm_provider: str) -> None:
def _translate_reasoning_effort_to_anthropic(
model: str, optional_params: dict, max_tokens: int | None, custom_llm_provider: str
) -> None:
"""Map OpenAI-style ``reasoning_effort`` to native Anthropic params.

Caller-supplied ``thinking`` / ``output_config`` win over the alias.
``effort='none'`` clears both. Invalid efforts raise a 400.
``effort='none'`` clears both. Invalid efforts raise a 400. Legacy
``budget_tokens`` is capped below ``max_tokens`` (Anthropic requires
``max_tokens > budget_tokens``) and thinking is dropped when ``max_tokens``
can't fit even the minimum budget.
"""
from litellm.exceptions import BadRequestError as _BadRequestError
from litellm.llms.anthropic.chat.transformation import (
Expand All @@ -218,7 +223,12 @@ def _translate_reasoning_effort_to_anthropic(model: str, optional_params: Dict,
optional_params.pop("output_config", None)
return

optional_params.setdefault("thinking", mapped_thinking)
if "thinking" not in optional_params:
capped_thinking = AnthropicConfig._cap_thinking_budget_to_max_tokens(mapped_thinking, max_tokens)
if capped_thinking is not None:
optional_params["thinking"] = capped_thinking
else:
verbose_logger.warning(DROP_UNSUPPORTED_ADAPTIVE_EFFORT_WARNING, model)

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.

P2 Misleading warning message reused from adaptive path

DROP_UNSUPPORTED_ADAPTIVE_EFFORT_WARNING says "Dropping adaptive thinking/output_config.effort…" but here the thinking being dropped was derived from the reasoning_effort OpenAI alias, not from an adaptive interface. An operator seeing this warning in logs while using reasoning_effort will have a hard time understanding the root cause — max_tokens too small for the translated budget is the real reason, not an adaptive-thinking rejection.

if AnthropicModelInfo._is_adaptive_thinking_model(model, custom_llm_provider):
mapped_effort = REASONING_EFFORT_TO_OUTPUT_CONFIG_EFFORT.get(reasoning_effort)
if mapped_effort is None:
Expand Down Expand Up @@ -375,6 +385,36 @@ def _translate_adaptive_effort_for_non_adaptive_model(
else:
optional_params.pop("output_config", None)

@staticmethod
def _drop_incompatible_temperature_for_thinking(
model: str, optional_params: dict, custom_llm_provider: str
) -> None:
"""Anthropic rejects any ``temperature`` other than 1 while extended thinking
is enabled ("temperature may only be set to 1 when thinking is enabled").

Clients like Claude Code send ``thinking``/``output_config.effort`` together
with a pinned ``temperature`` (e.g. the safety classifier uses ``temperature=0``
for determinism). When the request lands on a non-adaptive model, the effort
interface is reshaped above into legacy ``thinking={type: enabled}`` (or kept
as ``output_config.effort`` on Opus 4.5), and the leftover ``temperature`` would
400. Preserving the thinking the caller asked for wins over an unhonorable
sampling value (Anthropic forces ``temperature=1`` under thinking regardless),
so drop it and let the API default apply.

Adaptive models (4.6+) own this natively and are left untouched.
"""
if AnthropicModelInfo._is_adaptive_thinking_model(model, custom_llm_provider):
return
temperature = optional_params.get("temperature")
if temperature is None or temperature == 1:
return
thinking = optional_params.get("thinking")
output_config = optional_params.get("output_config")
thinking_enabled = isinstance(thinking, dict) and thinking.get("type") == "enabled"
effort_enabled = isinstance(output_config, dict) and output_config.get("effort") is not None
if thinking_enabled or effort_enabled:
optional_params.pop("temperature", None)

def transform_anthropic_messages_request(
self,
model: str,
Expand All @@ -399,6 +439,7 @@ def transform_anthropic_messages_request(
self._translate_reasoning_effort_to_anthropic(
model=model,
optional_params=anthropic_messages_optional_request_params,
max_tokens=max_tokens,
custom_llm_provider=self._resolved_provider,
)

Expand All @@ -415,6 +456,12 @@ def transform_anthropic_messages_request(
custom_llm_provider=self._resolved_provider,
)

self._drop_incompatible_temperature_for_thinking(
model=model,
optional_params=anthropic_messages_optional_request_params,
custom_llm_provider=self._resolved_provider,
)

system_param = anthropic_messages_optional_request_params.get("system")
if self.should_strip_billing_metadata() and system_param is not None:
filtered_system = self._filter_billing_headers_from_system(system_param)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from litellm.constants import (
DEFAULT_REASONING_EFFORT_HIGH_THINKING_BUDGET,
DEFAULT_REASONING_EFFORT_LOW_THINKING_BUDGET,
DEFAULT_REASONING_EFFORT_MEDIUM_THINKING_BUDGET,
DEFAULT_REASONING_EFFORT_XHIGH_THINKING_BUDGET,
)
Expand Down Expand Up @@ -174,6 +175,105 @@ def test_unrecognized_effort_raises_clean_400():
assert exc_info.value.status_code == 400


def test_pinned_temperature_dropped_when_adaptive_downgraded_to_enabled():
"""Regression (#33203): Claude Code's safety classifier sends adaptive thinking +
temperature=0 to Haiku 4.5. The adaptive interface is downgraded to legacy enabled
thinking, but Anthropic rejects "temperature may only be set to 1 when thinking is
enabled". The pinned temperature must be dropped so the request succeeds while the
downgraded thinking is preserved."""
params = _claude_code_payload(effort="medium")
params["temperature"] = 0
result = _transform("claude-haiku-4-5", params)

assert result["thinking"] == {
"type": "enabled",
"budget_tokens": DEFAULT_REASONING_EFFORT_MEDIUM_THINKING_BUDGET,
}
assert "temperature" not in result


def test_temperature_one_preserved_with_enabled_thinking():
"""temperature=1 is compatible with extended thinking, so it must be kept."""
params = _claude_code_payload(effort="medium")
params["temperature"] = 1
result = _transform("claude-haiku-4-5", params)

assert result["thinking"]["type"] == "enabled"
assert result["temperature"] == 1


def test_pinned_temperature_preserved_when_thinking_dropped():
"""When thinking is dropped entirely (non-reasoning model), there is no thinking
conflict, so a pinned temperature must survive untouched."""
params = _claude_code_payload(effort="medium")
params["temperature"] = 0
result = _transform("claude-3-5-haiku-latest", params)

assert "thinking" not in result
assert result["temperature"] == 0


def test_pinned_temperature_preserved_for_adaptive_model():
"""Adaptive models (4.6+) own the thinking/temperature relationship natively, so
the passthrough must not strip a pinned temperature for them."""
params = _claude_code_payload(effort="high")
params["temperature"] = 0
result = _transform("claude-sonnet-4-6", params)

assert result["thinking"] == {"type": "adaptive"}
assert result["temperature"] == 0


def test_pinned_temperature_dropped_for_opus_4_5_effort():
"""Opus 4.5 keeps native output_config.effort (extended thinking), which is equally
incompatible with a pinned non-1 temperature, so the temperature must be dropped."""
params = _claude_code_payload(effort="medium")
params["temperature"] = 0
result = _transform("claude-opus-4-5", params)

assert result["output_config"] == {"effort": "medium"}
assert "temperature" not in result


def test_reasoning_effort_budget_capped_below_max_tokens():
"""Sibling defect (#33203): the reasoning_effort alias mapped effort to legacy
thinking without capping budget_tokens below max_tokens, emitting
budget_tokens >= max_tokens which Anthropic rejects. A high-effort budget with
max_tokens=3000 must be capped to 2999."""
result = _transform(
"claude-haiku-4-5",
{"max_tokens": 3000, "reasoning_effort": "high"},
)

assert result["thinking"] == {"type": "enabled", "budget_tokens": 2999}


def test_reasoning_effort_thinking_dropped_when_max_tokens_too_small():
"""reasoning_effort thinking is dropped when max_tokens can't fit even the minimum
budget, so the request still succeeds."""
result = _transform(
"claude-haiku-4-5",
{"max_tokens": 512, "reasoning_effort": "medium"},
)

assert "thinking" not in result


def test_reasoning_effort_with_pinned_temperature_drops_temperature():
"""The reasoning_effort alias synthesizes legacy enabled thinking on a non-adaptive
model; a co-pinned non-1 temperature must be dropped to avoid the Anthropic 400."""
result = _transform(
"claude-haiku-4-5",
{"max_tokens": 8192, "reasoning_effort": "low", "temperature": 0},
)

assert result["thinking"] == {
"type": "enabled",
"budget_tokens": DEFAULT_REASONING_EFFORT_LOW_THINKING_BUDGET,
}
assert "temperature" not in result


def test_non_adaptive_request_without_effort_is_untouched():
"""A non-adaptive model receiving a request with no adaptive interface (no
effort, no adaptive thinking) must pass through untouched."""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,8 @@ def test_reasoning_effort_none_clears_thinking_and_output_config():

def test_reasoning_effort_on_non_adaptive_model_uses_thinking_budget():
config = AnthropicMessagesConfig()
optional_params = {"max_tokens": 1024, "reasoning_effort": "high"}
max_tokens = 8192
optional_params = {"max_tokens": max_tokens, "reasoning_effort": "high"}

result = config.transform_anthropic_messages_request(
model="claude-opus-4-5",
Expand All @@ -103,7 +104,8 @@ def test_reasoning_effort_on_non_adaptive_model_uses_thinking_budget():
assert isinstance(thinking, dict)
assert thinking.get("type") == "enabled"
assert isinstance(thinking.get("budget_tokens"), int)
assert thinking["budget_tokens"] >= 1024
assert thinking["budget_tokens"] == DEFAULT_REASONING_EFFORT_HIGH_THINKING_BUDGET
assert thinking["budget_tokens"] < max_tokens


@pytest.mark.parametrize("bad_effort", ["invalid", "disabled", ""])
Expand Down
Loading