Skip to content

Commit 2f28b02

Browse files
sararobcopybara-github
authored andcommitted
fix: convert 'citationSources' key in CitationMetadata to 'citations' when present (fixes #1222)
PiperOrigin-RevId: 839751451
1 parent 97cc7e4 commit 2f28b02

2 files changed

Lines changed: 42 additions & 0 deletions

File tree

google/genai/tests/types/test_types.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515

1616

1717
import copy
18+
import json
1819
import sys
1920
import typing
2021
from typing import Optional, assert_never
@@ -2866,3 +2867,37 @@ def test_user_content_unsupported_type_in_list():
28662867
def test_user_content_unsupported_role():
28672868
with pytest.raises(TypeError):
28682869
types.UserContent(role='model', parts=['hi'])
2870+
2871+
2872+
def test_instantiate_response_from_batch_json():
2873+
test_batch_json = json.dumps({
2874+
'candidates': [{
2875+
'citationMetadata': {
2876+
'citationSources': [{
2877+
'endIndex': 2009,
2878+
'startIndex': 1880,
2879+
'uri': 'http://someurl.com',
2880+
}]
2881+
},
2882+
'content': {
2883+
'parts': [{
2884+
'text': (
2885+
'This recipe makes a moist and delicious banana bread!'
2886+
)
2887+
}],
2888+
'role': 'model',
2889+
},
2890+
'finishReason': 'STOP',
2891+
}],
2892+
'modelVersion': 'gemini-1.5-flash-002@default',
2893+
})
2894+
parsed = types.GenerateContentResponse.model_validate_json(test_batch_json)
2895+
assert isinstance(parsed, types.GenerateContentResponse)
2896+
assert isinstance(parsed.candidates[0].citation_metadata, types.CitationMetadata)
2897+
assert isinstance(
2898+
parsed.candidates[0].citation_metadata.citations[0], types.Citation
2899+
)
2900+
assert(
2901+
parsed.candidates[0].citation_metadata.citations[0].uri
2902+
== 'http://someurl.com'
2903+
)

google/genai/types.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5444,6 +5444,13 @@ class CitationMetadata(_common.BaseModel):
54445444
""",
54455445
)
54465446

5447+
@model_validator(mode='before')
5448+
@classmethod
5449+
def _rename_citation_sources(cls, data: Any) -> Any:
5450+
if isinstance(data, dict) and 'citationSources' in data:
5451+
data['citations'] = data.pop('citationSources')
5452+
return data
5453+
54475454

54485455
class CitationMetadataDict(TypedDict, total=False):
54495456
"""Citation information when the model quotes another source."""

0 commit comments

Comments
 (0)