Skip to content

Commit 0cee093

Browse files
committed
fix(py/google-genai): keep thought signatures on every part kind and coalesce streamed text
- PartConverter dropped thought_signature on text, inline_data, fileData, executable_code and code_execution_result parts in both directions, which breaks Gemini 3 multi-turn and compaction. It now round-trips on all of them; a signature-only part becomes empty reasoning (JS parity), and fileData in a response becomes media instead of empty text. - Language/Outcome enum members leaked into custom.executableCode and custom.codeExecutionResult; they are now the wire strings. - The streamed final message kept every fragment plus a trailing empty text part, so post-model guardrails saw split text. Adjacent text and reasoning fragments now merge; a fragment carrying a signature closes its block and keeps the signature. Chunks still stream unchanged. - Parts with no Gemini field (Part.data from a2ui replays) converted to an empty Part(), which Gemini rejects. They are skipped, as are messages left with no parts. Bugbash: PR4-10
1 parent 66cf271 commit 0cee093

3 files changed

Lines changed: 267 additions & 27 deletions

File tree

‎packages/genkit-google-genai/src/genkit_google_genai/_models/_gemini.py‎

Lines changed: 37 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,35 @@ def _candidate_metadata(candidate: genai_types.Candidate | None) -> dict[str, An
222222
return out
223223

224224

225+
def _coalesce_stream_parts(parts: list[Part]) -> list[Part]:
226+
"""Join the text and reasoning fragments a stream delivers into whole parts.
227+
228+
Adjacent parts of the same kind merge while the earlier one carries no
229+
metadata; the merged part takes the later part's metadata, so a
230+
thought signature that closes a block stays on it. Empty text with no
231+
metadata is dropped. Other parts pass through in order.
232+
"""
233+
out: list[Part] = []
234+
for part in parts:
235+
kind = 'text' if part.text is not None else 'reasoning' if part.reasoning is not None else None
236+
if kind == 'text' and not part.text and not part.metadata:
237+
continue
238+
prev = out[-1] if out else None
239+
if (
240+
kind is not None
241+
and prev is not None
242+
and not prev.metadata
243+
and (prev.text is not None if kind == 'text' else prev.reasoning is not None)
244+
):
245+
if kind == 'text':
246+
out[-1] = Part.from_text((prev.text or '') + (part.text or ''), metadata=part.metadata)
247+
else:
248+
out[-1] = Part.from_reasoning((prev.reasoning or '') + (part.reasoning or ''), metadata=part.metadata)
249+
continue
250+
out.append(part)
251+
return out or [Part.from_text('')]
252+
253+
225254
def _no_candidates_response(
226255
feedback: genai_types.GenerateContentResponsePromptFeedback | None,
227256
usage_metadata: Any, # noqa: ANN401
@@ -2260,7 +2289,7 @@ async def _streaming_generate(
22602289
return ModelResponse(
22612290
message=Message(
22622291
role=Role.MODEL,
2263-
content=accumulated_content,
2292+
content=_coalesce_stream_parts(accumulated_content),
22642293
),
22652294
finish_reason=finish_reason,
22662295
usage=_usage_from_metadata(usage_metadata),
@@ -2316,12 +2345,14 @@ async def _build_messages(
23162345
content_parts: list[genai_types.Part] = []
23172346
for p in msg.content:
23182347
converted = await PartConverter.to_gemini(p, tools=tools)
2319-
if isinstance(converted, list):
2320-
content_parts.extend(converted)
2321-
else:
2322-
content_parts.append(converted)
2348+
for gemini_part in converted if isinstance(converted, list) else [converted]:
2349+
# A part Gemini has no field for (Part.data, say) converts
2350+
# to an empty Part(), which the API rejects.
2351+
if gemini_part.model_dump(exclude_none=True):
2352+
content_parts.append(gemini_part)
23232353
role = 'model' if msg.role in (Role.MODEL, 'model') else 'user'
2324-
request_contents.append(genai_types.Content(parts=content_parts, role=role))
2354+
if content_parts:
2355+
request_contents.append(genai_types.Content(parts=content_parts, role=role))
23252356

23262357
if use_cache and msg.metadata and msg.metadata.get('cache'):
23272358
cache = await self._retrieve_cached_content(

‎packages/genkit-google-genai/src/genkit_google_genai/_models/_utils.py‎

Lines changed: 49 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -198,8 +198,9 @@ async def to_gemini(
198198
Returns:
199199
A `genai.types.Part` object representing the converted content.
200200
"""
201+
signature = cls._extract_thought_signature(part.metadata)
201202
if part.text is not None:
202-
return genai.types.Part(text=part.text or ' ')
203+
return genai.types.Part(text=part.text or ' ', thought_signature=signature)
203204
if part.tool_request is not None:
204205
args = part.tool_request.input
205206
entry = tools.for_original(part.tool_request.name) if tools else None
@@ -298,7 +299,8 @@ async def to_gemini(
298299
inline_data=genai.types.Blob(
299300
mime_type=_media_type(part.media.content_type) or uri_mime or 'application/octet-stream',
300301
data=data,
301-
)
302+
),
303+
thought_signature=signature,
302304
)
303305

304306
if url.startswith('http'):
@@ -310,7 +312,8 @@ async def to_gemini(
310312
file_data=genai.types.FileData(
311313
mime_type=part.media.content_type,
312314
file_uri=url,
313-
)
315+
),
316+
thought_signature=signature,
314317
)
315318

316319
# TODO(#4360): Replace inline download with downloadRequestMedia
@@ -329,7 +332,8 @@ async def to_gemini(
329332
inline_data=genai.types.Blob(
330333
mime_type=mime_type,
331334
data=data,
332-
)
335+
),
336+
thought_signature=signature,
333337
)
334338

335339
# Non-HTTP, non-data URIs (e.g. gs://, Files API URIs) are
@@ -341,7 +345,8 @@ async def to_gemini(
341345
file_data=genai.types.FileData(
342346
mime_type=part.media.content_type,
343347
file_uri=url,
344-
)
348+
),
349+
thought_signature=signature,
345350
)
346351
if part.custom is not None:
347352
return cls._to_gemini_custom(part)
@@ -368,15 +373,17 @@ def _to_gemini_custom(cls, part: Part) -> genai.types.Part:
368373
executable_code=genai.types.ExecutableCode(
369374
code=custom_data[cls.EXECUTABLE_CODE][cls.CODE],
370375
language=custom_data[cls.EXECUTABLE_CODE][cls.LANGUAGE],
371-
)
376+
),
377+
thought_signature=cls._extract_thought_signature(part.metadata),
372378
)
373379
if part.custom and cls.CODE_EXECUTION_RESULT in part.custom:
374380
custom_data = cast(dict, part.custom)
375381
return genai.types.Part(
376382
code_execution_result=genai.types.CodeExecutionResult(
377383
outcome=custom_data[cls.CODE_EXECUTION_RESULT][cls.OUTCOME],
378384
output=custom_data[cls.CODE_EXECUTION_RESULT][cls.OUTPUT],
379-
)
385+
),
386+
thought_signature=cls._extract_thought_signature(part.metadata),
380387
)
381388
if part.custom and cls.GEMINI_TOOL_CALL in part.custom:
382389
return genai.types.Part(
@@ -407,8 +414,10 @@ def from_gemini(cls, part: genai.types.Part, *, tools: ToolTable | None = None)
407414
"""
408415
if part.thought:
409416
return Part.from_reasoning(part.text or '', metadata=cls._encode_thought_signature(part.thought_signature))
417+
signature = cls._encode_thought_signature(part.thought_signature)
410418
if part.text is not None:
411-
return Part.from_text(part.text)
419+
# Gemini 3 signs text parts too; dropping the signature breaks the next turn.
420+
return Part.from_text(part.text, metadata=signature)
412421
if part.function_call:
413422
# Tool refs come only from the model's call id. A synthetic part
414423
# index isn't unique across turns, so resume can't tell repeated
@@ -457,22 +466,33 @@ def from_gemini(cls, part: genai.types.Part, *, tools: ToolTable | None = None)
457466
if part.inline_data and part.inline_data.data:
458467
b64_data = base64.b64encode(part.inline_data.data).decode('utf-8')
459468
return Part.from_media(
460-
f'data:{part.inline_data.mime_type};base64,{b64_data}', content_type=part.inline_data.mime_type
469+
f'data:{part.inline_data.mime_type};base64,{b64_data}',
470+
content_type=part.inline_data.mime_type,
471+
metadata=signature,
461472
)
473+
if part.file_data and part.file_data.file_uri:
474+
return Part.from_media(part.file_data.file_uri, content_type=part.file_data.mime_type, metadata=signature)
462475
if part.executable_code:
463-
return Part.from_custom({
464-
cls.EXECUTABLE_CODE: {
465-
cls.LANGUAGE: part.executable_code.language,
466-
cls.CODE: part.executable_code.code,
467-
}
468-
})
476+
# Enum members aren't JSON; keep the wire string (PYTHON, OUTCOME_OK).
477+
return Part.from_custom(
478+
{
479+
cls.EXECUTABLE_CODE: {
480+
cls.LANGUAGE: _enum_value(part.executable_code.language),
481+
cls.CODE: part.executable_code.code,
482+
}
483+
},
484+
metadata=signature,
485+
)
469486
if part.code_execution_result:
470-
return Part.from_custom({
471-
cls.CODE_EXECUTION_RESULT: {
472-
cls.OUTCOME: part.code_execution_result.outcome,
473-
cls.OUTPUT: part.code_execution_result.output,
474-
}
475-
})
487+
return Part.from_custom(
488+
{
489+
cls.CODE_EXECUTION_RESULT: {
490+
cls.OUTCOME: _enum_value(part.code_execution_result.outcome),
491+
cls.OUTPUT: part.code_execution_result.output,
492+
}
493+
},
494+
metadata=signature,
495+
)
476496
if part.tool_call:
477497
# A built-in tool the server ran (include_server_side_tool_invocations).
478498
# Kept wire-shaped so the next turn can send it back unchanged.
@@ -487,6 +507,9 @@ def from_gemini(cls, part: genai.types.Part, *, tools: ToolTable | None = None)
487507
},
488508
metadata=cls._encode_thought_signature(part.thought_signature),
489509
)
510+
if part.thought_signature:
511+
# A signature with no content (streaming sends these); JS keeps it as reasoning.
512+
return Part.from_reasoning('', metadata=signature)
490513

491514
return Part.from_text('')
492515

@@ -622,6 +645,11 @@ def _redact_url(url: str) -> str:
622645
return urlunsplit((parts.scheme, parts.netloc.rpartition('@')[2], parts.path, '', ''))
623646

624647

648+
def _enum_value(value: object) -> object:
649+
"""The wire value of a google-genai enum member; anything else unchanged."""
650+
return getattr(value, 'value', value)
651+
652+
625653
def _media_too_large(url: str) -> GenkitError:
626654
return GenkitError(status='INVALID_ARGUMENT', message=f'media at {_redact_url(url)} is larger than 20MB')
627655

Lines changed: 181 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,181 @@
1+
# Copyright 2026 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
#
15+
# SPDX-License-Identifier: Apache-2.0
16+
17+
"""PartConverter fidelity: thought signatures on every part kind, enum values, stream coalescing."""
18+
19+
import json
20+
from typing import Any
21+
22+
import pytest
23+
from genkit_google_genai._models._gemini import GeminiModel, _coalesce_stream_parts
24+
from genkit_google_genai._models._utils import PartConverter
25+
from google.genai import types as genai_types
26+
from pytest_mock import MockerFixture
27+
28+
from genkit import Message, Part, Role
29+
from genkit.model import ModelContext, ModelRequest
30+
31+
SIG = b'opaque-signature'
32+
33+
34+
@pytest.mark.asyncio
35+
@pytest.mark.parametrize(
36+
'gemini_part',
37+
[
38+
genai_types.Part(text='The eigenvalues sum to 12.', thought_signature=SIG),
39+
genai_types.Part(
40+
executable_code=genai_types.ExecutableCode(code='print(1)', language=genai_types.Language.PYTHON),
41+
thought_signature=SIG,
42+
),
43+
genai_types.Part(
44+
code_execution_result=genai_types.CodeExecutionResult(outcome=genai_types.Outcome.OUTCOME_OK, output='1\n'),
45+
thought_signature=SIG,
46+
),
47+
genai_types.Part(inline_data=genai_types.Blob(mime_type='image/png', data=b'\x89PNG'), thought_signature=SIG),
48+
],
49+
ids=['text', 'executable_code', 'code_execution_result', 'inline_data'],
50+
)
51+
async def test_thought_signature_survives_round_trip(gemini_part: genai_types.Part) -> None:
52+
"""Gemini 3 signs text and code parts; the signature must come back on the next turn."""
53+
genkit_part = PartConverter.from_gemini(gemini_part)
54+
assert genkit_part.metadata is not None and 'thoughtSignature' in genkit_part.metadata
55+
56+
# JSON persistence (chat history in a DB) must not lose it either.
57+
rehydrated = Part.model_validate_json(genkit_part.model_dump_json(by_alias=True))
58+
back = await PartConverter.to_gemini(rehydrated)
59+
60+
assert not isinstance(back, list)
61+
assert back.thought_signature == SIG
62+
assert back == gemini_part
63+
64+
65+
def test_code_execution_enums_are_wire_strings() -> None:
66+
"""Language/Outcome come back as JSON strings, not google-genai enum members."""
67+
code = PartConverter.from_gemini(
68+
genai_types.Part(executable_code=genai_types.ExecutableCode(code='x', language=genai_types.Language.PYTHON))
69+
)
70+
result = PartConverter.from_gemini(
71+
genai_types.Part(code_execution_result=genai_types.CodeExecutionResult(outcome=genai_types.Outcome.OUTCOME_OK))
72+
)
73+
74+
assert code.custom is not None and result.custom is not None
75+
assert type(code.custom['executableCode']['language']) is str
76+
assert type(result.custom['codeExecutionResult']['outcome']) is str
77+
assert json.loads(code.model_dump_json())['custom']['executableCode']['language'] == 'PYTHON'
78+
79+
80+
def test_signature_only_part_is_kept_as_reasoning() -> None:
81+
"""A streamed part that carries only a signature is not flattened to empty text."""
82+
part = PartConverter.from_gemini(genai_types.Part(thought_signature=SIG))
83+
84+
assert part.reasoning == ''
85+
assert part.metadata is not None and 'thoughtSignature' in part.metadata
86+
87+
88+
def test_file_data_comes_back_as_media() -> None:
89+
"""A fileData part in a response is media, not an empty text part."""
90+
part = PartConverter.from_gemini(
91+
genai_types.Part(file_data=genai_types.FileData(file_uri='gs://menus/today.pdf', mime_type='application/pdf'))
92+
)
93+
94+
assert part.media is not None
95+
assert part.media.url == 'gs://menus/today.pdf'
96+
assert part.media.content_type == 'application/pdf'
97+
98+
99+
def test_coalesce_joins_fragments_and_keeps_closing_signature() -> None:
100+
"""Text and reasoning fragments merge; the signature that closes a block stays; empty text drops."""
101+
sig = {'thoughtSignature': 'c2ln'}
102+
parts = [
103+
Part.from_reasoning('Think '),
104+
Part.from_reasoning('hard.', metadata=sig),
105+
Part.from_text('Pesto '),
106+
Part.from_text('has '),
107+
Part.from_text('pine nuts.'),
108+
Part.from_text(''),
109+
]
110+
111+
out = _coalesce_stream_parts(parts)
112+
113+
assert [p.model_dump(exclude_none=True) for p in out] == [
114+
{'reasoning': 'Think hard.', 'metadata': sig},
115+
{'text': 'Pesto has pine nuts.'},
116+
]
117+
118+
119+
def test_coalesce_does_not_merge_across_signed_part_or_tool_call() -> None:
120+
"""A signed part ends a block; tool requests split text runs."""
121+
sig = {'thoughtSignature': 'c2ln'}
122+
parts = [
123+
Part.from_text('A', metadata=sig),
124+
Part.from_text('B'),
125+
Part.from_tool_request('lookup_menu', {}),
126+
Part.from_text('C'),
127+
]
128+
129+
out = _coalesce_stream_parts(parts)
130+
131+
assert [p.text for p in out] == ['A', 'B', None, 'C']
132+
133+
134+
@pytest.mark.asyncio
135+
async def test_streaming_final_message_is_coalesced(mocker: MockerFixture) -> None:
136+
"""Chunks still stream as fragments; the final message has whole parts for guardrails to read."""
137+
138+
def chunk(text: str, **kw: Any) -> genai_types.GenerateContentResponse: # noqa: ANN401
139+
return genai_types.GenerateContentResponse(
140+
candidates=[genai_types.Candidate(content=genai_types.Content(parts=[genai_types.Part(text=text)]), **kw)]
141+
)
142+
143+
async def chunks() -> Any: # noqa: ANN401
144+
yield chunk('Pesto ')
145+
yield chunk('has pine nuts.')
146+
yield chunk('', finish_reason=genai_types.FinishReason.STOP)
147+
148+
client = mocker.AsyncMock()
149+
client.aio.models.generate_content_stream.return_value = chunks()
150+
on_chunk = mocker.MagicMock()
151+
152+
response = await GeminiModel('gemini-flash-latest', client).generate(
153+
ModelRequest(messages=[Message(role=Role.USER, content=[Part.from_text('Nut-free?')])]),
154+
ModelContext(streaming_callback=on_chunk),
155+
)
156+
157+
assert response.message is not None
158+
assert [p.text for p in response.message.content] == ['Pesto has pine nuts.']
159+
assert on_chunk.call_count == 3
160+
161+
162+
@pytest.mark.asyncio
163+
async def test_parts_without_a_gemini_field_are_not_sent(mocker: MockerFixture) -> None:
164+
"""Replaying Part.data (a2ui) used to send an empty Part(), which Gemini rejects."""
165+
client = mocker.AsyncMock()
166+
client.aio.models.generate_content.return_value = genai_types.GenerateContentResponse(
167+
candidates=[genai_types.Candidate(content=genai_types.Content(parts=[genai_types.Part(text='ok')]))]
168+
)
169+
request = ModelRequest(
170+
messages=[
171+
Message(role=Role.USER, content=[Part.from_text('Show the menu.')]),
172+
Message(role=Role.MODEL, content=[Part.from_text('Here it is.'), Part.from_data({'surface': 'menu'})]),
173+
Message(role=Role.MODEL, content=[Part.from_data({'surface': 'cart'})]),
174+
Message(role=Role.USER, content=[Part.from_text('Add pesto.')]),
175+
]
176+
)
177+
178+
await GeminiModel('gemini-flash-latest', client).generate(request, ModelContext())
179+
180+
contents = client.aio.models.generate_content.call_args.kwargs['contents']
181+
assert [[p.text for p in c.parts] for c in contents] == [['Show the menu.'], ['Here it is.'], ['Add pesto.']]

0 commit comments

Comments
 (0)