Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -325,7 +325,9 @@ def _reasoning_part_to_blocks(part: Part) -> list[dict[str, Any]]:
blocks.append({'reasoningContent': {'redactedContent': redacted}})
signature = _metadata_str(metadata, REASONING_SIGNATURE_METADATA_KEY)
text = part.reasoning or ''
if text and signature:
# Claude can sign a thinking block with empty text, and a tool-use turn has to
# start with it, so any signed reasoning is kept.
if signature:
blocks.append({'reasoningContent': {'reasoningText': {'text': text, 'signature': signature}}})
return blocks

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ def _blocks_to_parts(blocks: dict[int, _StreamBlock], tools: list[ToolDefinition
continue
# One block can carry both reasoning and text; reasoning comes first.
reasoning = ''.join(block.reasoning)
if reasoning or block.redacted:
if reasoning or block.redacted or block.signature:
parts.append(bedrock_reasoning_part(reasoning, block.signature, bytes(block.redacted) or None))
text = ''.join(block.text)
if text:
Expand Down
21 changes: 21 additions & 0 deletions packages/genkit-amazon-bedrock/tests/converters_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -626,6 +626,27 @@ def test_redacted_only_reasoning_part_still_replays() -> None:
assert kwargs['messages'][0]['content'] == [{'reasoningContent': {'redactedContent': b'blob'}}]


def test_empty_signed_reasoning_part_still_replays() -> None:
# Claude can sign a thinking block with empty text; it must be sent back, not dropped.
part = Part.from_reasoning('', metadata={REASONING_SIGNATURE_METADATA_KEY: 'sig-abc'})
request = ModelRequest(messages=[Message(role=Role.MODEL, content=[part])])
kwargs = build_converse_request('amazon.nova-lite-v1:0', request)
assert kwargs['messages'][0]['content'] == [
{'reasoningContent': {'reasoningText': {'text': '', 'signature': 'sig-abc'}}}
]


def test_empty_unsigned_reasoning_part_is_not_replayed() -> None:
request = ModelRequest(
messages=[
Message(role=Role.USER, content=[Part.from_text('q')]),
Message(role=Role.MODEL, content=[Part.from_reasoning('')]),
]
)
kwargs = build_converse_request('amazon.nova-lite-v1:0', request)
assert [m['role'] for m in kwargs['messages']] == ['user']


def test_generic_reasoning_part_is_not_replayed() -> None:
request = ModelRequest(
messages=[
Expand Down
36 changes: 36 additions & 0 deletions packages/genkit-amazon-bedrock/tests/stream_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -309,6 +309,42 @@ async def test_reasoning_text_streams_and_signature_accumulates() -> None:
assert text_part.text == 'answer'


async def test_signed_reasoning_with_empty_text_is_kept() -> None:
ctx, chunks = streaming_ctx()

response = await consume_converse_stream(
events(
reasoning_delta(0, {'signature': 'sig-abc'}),
tool_start(1, 'call_1', 'noop'),
tool_delta(1, '{}'),
tool_stop(1),
message_stop('tool_use'),
),
text_request(),
ctx,
)

assert response.message is not None
reasoning_part, tool_part = response.message.content
assert reasoning_part.reasoning == ''
assert reasoning_part.metadata is not None
assert reasoning_part.metadata[REASONING_SIGNATURE_METADATA_KEY] == 'sig-abc'
assert tool_part.tool_request is not None


async def test_reasoning_without_text_or_signature_is_dropped() -> None:
ctx, _ = streaming_ctx()

response = await consume_converse_stream(
events(reasoning_delta(0, {'text': ''}), text_delta(1, 'answer'), message_stop('end_turn')),
text_request(),
ctx,
)

assert response.message is not None
assert [part.text for part in response.message.content] == ['answer']


async def test_redacted_reasoning_accumulates_as_base64_without_chunks() -> None:
ctx, chunks = streaming_ctx()

Expand Down
4 changes: 3 additions & 1 deletion packages/genkit-anthropic/src/genkit_anthropic/_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -756,7 +756,9 @@ def _to_anthropic_block(self, part: Part) -> dict[str, Any] | None:
An Anthropic content block dict, or None if unrecognized.
"""
reasoning = part.reasoning
if reasoning:
# Claude can sign a thinking block with empty text, and a tool-use turn
# must start with it, so signed empty reasoning is kept.
if reasoning is not None:
# Claude only accepts thinking it signed. Unsigned reasoning, such as
# history from a model that signs nothing, is dropped, the same as on
# Bedrock's Claude path.
Expand Down
50 changes: 48 additions & 2 deletions packages/genkit-anthropic/tests/anthropic_models_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@
ModelSupports,
OutputConfig,
ToolDefinition,
ToolRequest,
ToolResponse,
)


Expand Down Expand Up @@ -1828,8 +1830,8 @@ async def test_generate_claude_drops_thinking_part_without_thought_signature(
assert sent[1] == {'role': 'assistant', 'content': [{'type': 'text', 'text': '391'}]}


def test_empty_reasoning_part_is_skipped() -> None:
"""Test that empty reasoning parts produce no Anthropic block."""
def test_empty_signed_reasoning_part_encodes_as_thinking_block() -> None:
"""Claude can sign a thinking block with empty text; it must be sent back, not dropped."""
mock_client = MagicMock()
model = AnthropicModel(model_name='claude-sonnet-4', client=mock_client)

Expand All @@ -1840,10 +1842,54 @@ def test_empty_reasoning_part_is_skipped() -> None:
),
]

anthropic_messages = model._to_anthropic_messages(messages)
assert anthropic_messages[0]['content'] == [{'type': 'thinking', 'thinking': '', 'signature': 'sig-abc'}]


def test_empty_unsigned_reasoning_part_is_skipped() -> None:
"""Test that empty reasoning without a signature produces no Anthropic block."""
mock_client = MagicMock()
model = AnthropicModel(model_name='claude-sonnet-4', client=mock_client)

messages = [Message(role=Role.MODEL, content=[Part.from_reasoning('')])]

anthropic_messages = model._to_anthropic_messages(messages)
assert anthropic_messages[0]['content'] == []


@pytest.mark.asyncio
async def test_generate_claude_sends_back_empty_signed_thinking_before_tool_use() -> None:
"""An empty signed thinking block from a tool-call turn stays at the start of that turn."""
mock_client = _mock_client_for_generate()
# The plugin checks the client for a credential before each call.
mock_client.api_key = 'test-key'
plugin = Anthropic(api_key='test-key')
plugin._runtime_client = lambda: mock_client
ai = Genkit(plugins=[plugin])
history = [
Message(role=Role.USER, content=[Part.from_text('what is the weather in Paris?')]),
Message(
role=Role.MODEL,
content=[
Part.from_reasoning('', metadata={'thoughtSignature': 'sig-abc'}),
Part(tool_request=ToolRequest(ref='toolu_1', name='getWeather', input={'city': 'Paris'})),
],
),
Message(
role=Role.TOOL,
content=[Part(tool_response=ToolResponse(ref='toolu_1', name='getWeather', output='sunny'))],
),
]

await ai.generate(model='anthropic/claude-sonnet-4', messages=history)

# No beta config here, so this must go through the standard endpoint.
mock_client.messages.create.assert_awaited_once()
sent = mock_client.messages.create.call_args.kwargs['messages']
assert sent[1]['content'][0] == {'type': 'thinking', 'thinking': '', 'signature': 'sig-abc'}
assert sent[1]['content'][1]['type'] == 'tool_use'


def test_redacted_thinking_part_round_trips() -> None:
"""Test that redacted thinking custom data encodes as a redacted block."""
mock_client = MagicMock()
Expand Down
Loading