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
35 changes: 31 additions & 4 deletions google/genai/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,31 @@ def _Candidate_from_mldev(
return to_object


def _dedupe_mldev_candidate_parts(candidates: list[dict[str, Any]]) -> None:
if len(candidates) < 2:
return

first_parts = getv(candidates[0], ['content', 'parts'])
if not isinstance(first_parts, list):
return

duplicate_tail = []
for candidate in candidates[1:]:
parts = getv(candidate, ['content', 'parts'])
if not isinstance(parts, list) or not parts:
return
duplicate_tail.extend(parts)

if (
duplicate_tail
and len(first_parts) > len(duplicate_tail)
and first_parts[-len(duplicate_tail) :] == duplicate_tail
):
content = getv(candidates[0], ['content'])
if isinstance(content, dict):
content['parts'] = first_parts[: -len(duplicate_tail)]


def _CitationMetadata_from_mldev(
from_object: Union[dict[str, Any], object],
parent_object: Optional[dict[str, Any]] = None,
Expand Down Expand Up @@ -1697,13 +1722,15 @@ def _GenerateContentResponse_from_mldev(
)

if getv(from_object, ['candidates']) is not None:
candidates = [
_Candidate_from_mldev(item, to_object, root_object)
for item in getv(from_object, ['candidates'])
]
_dedupe_mldev_candidate_parts(candidates)
setv(
to_object,
['candidates'],
[
_Candidate_from_mldev(item, to_object, root_object)
for item in getv(from_object, ['candidates'])
],
candidates,
)

if getv(from_object, ['modelVersion']) is not None:
Expand Down
35 changes: 35 additions & 0 deletions google/genai/tests/types/test_part_type.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@


import pytest
from ... import models
from ... import types


Expand Down Expand Up @@ -83,6 +84,40 @@ def test_two_candidates_text(caplog, generate_content_response):
generate_content_response.candidates = None


def test_mldev_candidate_count_keeps_candidate_parts_separate():
response_dict = models._GenerateContentResponse_from_mldev({
'candidates': [
{
'content': {
'parts': [
{'text': 'first'},
{'text': 'second'},
{'text': 'third'},
]
}
},
{'content': {'parts': [{'text': 'second'}]}},
{'content': {'parts': [{'text': 'third'}]}},
]
})

response = types.GenerateContentResponse._from_response(
response=response_dict,
kwargs={},
)

assert [part.text for part in response.candidates[0].content.parts] == [
'first'
]
assert [part.text for part in response.candidates[1].content.parts] == [
'second'
]
assert [part.text for part in response.candidates[2].content.parts] == [
'third'
]
assert response.text == 'first'


def test_thought_signature_no_warning(caplog, generate_content_response):
generate_content_response.candidates = [
types.Candidate(
Expand Down
Loading