Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
45 changes: 36 additions & 9 deletions src/google/adk/models/anthropic_llm.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,19 +221,28 @@ def _build_anthropic_thinking_param(
explicit (mirroring the Anthropic API).
* ``0``: thinking is DISABLED (``thinking.type: "disabled"``).
* negative (e.g. ``-1`` AUTOMATIC): maps to Anthropic's adaptive thinking
(``thinking.type: "adaptive"``, ``thinking.display: "summarized"``). The
model picks the depth itself (controlled by the separate
``output_config.effort`` parameter when set) and returns its reasoning
as summarized thoughts. REQUIRED for Claude Opus 4.7 and later models
that reject ``"enabled"`` with a 400 error; also recommended for Opus
4.6 and Sonnet 4.6 where ``"enabled"`` is deprecated.
(``thinking.type: "adaptive"``). The model picks the depth itself
(controlled by the separate ``output_config.effort`` parameter when
set). REQUIRED for Claude Opus 4.7 and later models that reject
``"enabled"`` with a 400 error; also recommended for Opus 4.6 and
Sonnet 4.6 where ``"enabled"`` is deprecated.
* positive int: budget in tokens for legacy manual mode
(``thinking.type: "enabled"``; Anthropic requires ``>= 1024`` and
``< max_tokens``; validation is delegated to the Anthropic API so the
caller gets the canonical error message). Rejected by Claude Opus 4.7
-- callers targeting 4.7+ must use a negative value (adaptive) or
``0`` (disabled).

``include_thoughts`` sets ``thinking.display`` when thinking is on:
* ``None`` or ``True``: adaptive thinking asks for ``"summarized"``, so
the reasoning comes back as summarized thought parts. A manual budget
sends no ``display``; the models that accept one return summaries by
default.
* ``False``: ``"omitted"`` in both modes. Claude still thinks, and bills
the same, but its thinking blocks come back with empty text and a
signature. They become thought parts with empty text, which are sent
back unchanged on later turns.

Args:
config: Optional GenerateContentConfig object.

Expand All @@ -256,23 +265,31 @@ def _build_anthropic_thinking_param(
if thinking_budget == 0:
return anthropic_types.ThinkingConfigDisabledParam(type="disabled")

# Only an explicit False hides the reasoning. None keeps the summaries ADK
# has always asked for, so existing configs send the same request.
omit_thoughts = config.thinking_config.include_thoughts is False

if thinking_budget < 0:
# genai AUTOMATIC (-1) and any other negative value map to Anthropic
# adaptive thinking. Required for Claude Opus 4.7 (which returns a 400
# error for ``"enabled"``) and recommended for Opus 4.6 / Sonnet 4.6
# where ``"enabled"`` is deprecated. Adaptive does not accept a budget;
# depth is controlled by the model itself (or by the separate
# ``output_config.effort`` parameter when set).
# Without ``display``, Claude redacts the reasoning it just billed for.
# Claude Opus 4.7 and later default to ``display: "omitted"``, so the
# summaries must be asked for explicitly.
return anthropic_types.ThinkingConfigAdaptiveParam(
type="adaptive",
display="summarized",
display="omitted" if omit_thoughts else "summarized",
)

return anthropic_types.ThinkingConfigEnabledParam(
enabled = anthropic_types.ThinkingConfigEnabledParam(
type="enabled",
budget_tokens=thinking_budget,
)
if omit_thoughts:
enabled["display"] = "omitted"
return enabled


def _thinking_is_enabled(
Expand Down Expand Up @@ -1439,6 +1456,11 @@ class AnthropicLlm(BaseLlm):
To configure thinking effort, user must use `AnthropicGenerateContentConfig`
and set its `effort` field directly (e.g., `effort="xhigh"`).

When `thinking_config` turns thinking on, ADK returns a summary of
Claude's reasoning as thought parts. Set
`thinking_config.include_thoughts=False` to get those parts with empty
text instead (Claude's `thinking.display: "omitted"`).

Attributes:
model: The name of the Claude model.
max_tokens: The maximum number of tokens to generate.
Expand Down Expand Up @@ -2064,6 +2086,11 @@ class Claude(AnthropicLlm):
To configure thinking effort, user must use `AnthropicGenerateContentConfig`
and set its `effort` field directly (e.g., `effort="xhigh"`).

When `thinking_config` turns thinking on, ADK returns a summary of
Claude's reasoning as thought parts. Set
`thinking_config.include_thoughts=False` to get those parts with empty
text instead (Claude's `thinking.display: "omitted"`).

Attributes:
model: The name of the Claude model.
max_tokens: The maximum number of tokens to generate.
Expand Down
136 changes: 132 additions & 4 deletions tests/unittests/models/test_anthropic_llm.py
Original file line number Diff line number Diff line change
Expand Up @@ -3070,17 +3070,71 @@ def test_build_anthropic_thinking_param_other_negative_uses_adaptive():
)


def test_build_anthropic_thinking_param_manual_budget_omits_display():
"""``display`` belongs to adaptive thinking only, not to a manual budget."""
@pytest.mark.parametrize(
("include_thoughts", "display"),
[(None, "summarized"), (True, "summarized"), (False, "omitted")],
)
def test_build_anthropic_thinking_param_adaptive_display_follows_include_thoughts(
include_thoughts, display
):
"""Adaptive thinking hides the reasoning only when include_thoughts is False."""
from google.adk.models.anthropic_llm import _build_anthropic_thinking_param

config = types.GenerateContentConfig(
thinking_config=types.ThinkingConfig(thinking_budget=2048),
thinking_config=types.ThinkingConfig(
thinking_budget=-1, include_thoughts=include_thoughts
),
)
result = _build_anthropic_thinking_param(config)
assert result == anthropic_types.ThinkingConfigAdaptiveParam(
type="adaptive", display=display
)


@pytest.mark.parametrize("include_thoughts", [None, True])
def test_build_anthropic_thinking_param_manual_budget_omits_display(
include_thoughts,
):
"""A manual budget sends no ``display`` unless thoughts are excluded."""
from google.adk.models.anthropic_llm import _build_anthropic_thinking_param

config = types.GenerateContentConfig(
thinking_config=types.ThinkingConfig(
thinking_budget=2048, include_thoughts=include_thoughts
),
)
result = _build_anthropic_thinking_param(config)
assert "display" not in result


def test_build_anthropic_thinking_param_manual_budget_omits_excluded_thoughts():
"""include_thoughts=False hides the reasoning under a manual budget too."""
from google.adk.models.anthropic_llm import _build_anthropic_thinking_param

config = types.GenerateContentConfig(
thinking_config=types.ThinkingConfig(
thinking_budget=2048, include_thoughts=False
),
)
result = _build_anthropic_thinking_param(config)
assert result == anthropic_types.ThinkingConfigEnabledParam(
type="enabled", budget_tokens=2048, display="omitted"
)


def test_build_anthropic_thinking_param_disabled_ignores_include_thoughts():
"""Disabled thinking sends no ``display``, which Claude rejects there."""
from google.adk.models.anthropic_llm import _build_anthropic_thinking_param

config = types.GenerateContentConfig(
thinking_config=types.ThinkingConfig(
thinking_budget=0, include_thoughts=False
),
)
result = _build_anthropic_thinking_param(config)
assert result == anthropic_types.ThinkingConfigDisabledParam(type="disabled")


def test_build_anthropic_thinking_param_no_config():
"""Returns NOT_GIVEN when no thinking config is set."""
from anthropic import NOT_GIVEN
Expand Down Expand Up @@ -3261,6 +3315,43 @@ def test_message_to_generate_content_response_with_thinking():
assert text_part.thought is not True


def test_omitted_thinking_block_is_sent_back_unchanged():
"""A thinking block with empty text replays as the same thinking block.

``display: "omitted"`` returns signed thinking blocks with empty text, and
Claude requires them back unchanged on the next request. They must not
turn into ``redacted_thinking`` blocks.
"""
message = anthropic_types.Message(
id="msg_omitted",
content=[
anthropic_types.ThinkingBlock(
thinking="", signature="sig_omitted", type="thinking"
),
anthropic_types.ToolUseBlock(
id="toolu_1", name="clock", input={}, type="tool_use"
),
],
model="claude-opus-4-7",
role="assistant",
stop_reason="tool_use",
stop_sequence=None,
type="message",
usage=anthropic_types.Usage(input_tokens=10, output_tokens=20),
)

response = message_to_generate_content_response(message)
replayed = content_to_message_param(response.content)

assert replayed == {
"role": "assistant",
"content": [
{"type": "thinking", "thinking": "", "signature": "sig_omitted"},
{"type": "tool_use", "id": "toolu_1", "name": "clock", "input": {}},
],
}


def test_message_to_generate_content_response_reports_cache_read_tokens():
"""cache_read_input_tokens maps to usage_metadata.cached_content_token_count."""
from google.adk.models.anthropic_llm import message_to_generate_content_response
Expand Down Expand Up @@ -3804,6 +3895,41 @@ async def test_non_streaming_passes_thinking_param():
)


@pytest.mark.asyncio
async def test_non_streaming_requests_omitted_display_without_thoughts():
"""include_thoughts=False asks Claude to omit the reasoning text."""
llm = AnthropicLlm(model="claude-opus-4-7")
mock_message = anthropic_types.Message(
id="msg_omit",
content=[
anthropic_types.TextBlock(text="Answer.", type="text", citations=None)
],
model="claude-opus-4-7",
role="assistant",
stop_reason="end_turn",
stop_sequence=None,
type="message",
usage=anthropic_types.Usage(input_tokens=5, output_tokens=2),
)
mock_client = MagicMock()
mock_client.messages.create = AsyncMock(return_value=mock_message)
request = LlmRequest(
model="claude-opus-4-7",
contents=[Content(role="user", parts=[Part.from_text(text="Think")])],
config=types.GenerateContentConfig(
thinking_config=types.ThinkingConfig(
thinking_budget=-1, include_thoughts=False
),
),
)

with mock.patch.object(llm, "_anthropic_client", mock_client):
_ = [r async for r in llm.generate_content_async(request, stream=False)]

_, kwargs = mock_client.messages.create.call_args
assert kwargs["thinking"] == {"type": "adaptive", "display": "omitted"}


@pytest.mark.asyncio
async def test_non_streaming_no_thinking_param_without_config():
"""Without thinking_config, thinking kwarg should be NOT_GIVEN."""
Expand Down Expand Up @@ -4044,7 +4170,9 @@ async def test_streaming_reports_thinking_tokens_disjoint_from_candidates():


@pytest.mark.asyncio
@pytest.mark.parametrize("thinking_deltas", [["Reason."], []])
# [""] is how ``display: "omitted"`` streams a thinking block: one empty
# thinking_delta, then the signature.
@pytest.mark.parametrize("thinking_deltas", [["Reason."], [], [""]])
async def test_streaming_thinking_captures_signature_delta(thinking_deltas):
"""A streamed signature_delta must land on the final thinking Part.

Expand Down