Repository navigation
fix(py/google-genai): pass Gemini finish_message through and explain empty image replies #127
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
|
|
@@ -226,6 +226,31 @@ def _no_candidates_response( | |||||
| ) | ||||||
|
|
||||||
|
|
||||||
| _NO_IMAGE_MESSAGE = 'No image was returned. Try a clearer image prompt (for example, "draw a red circle on white").' | ||||||
|
|
||||||
|
|
||||||
| def _finish_message(fr: Any, message: str | None, content: list[Part], model_name: str) -> str | None: # noqa: ANN401 | ||||||
| """The candidate's finish message, or why an image model returned no image. | ||||||
|
|
||||||
| An image model that answers with no media would otherwise read as a plain | ||||||
| success, since ambiguous prompts often come back STOP with empty parts. | ||||||
| """ | ||||||
| if message: | ||||||
| return message | ||||||
| if not is_image_model(model_name) or any(part.media is not None for part in content): | ||||||
| return None | ||||||
| fr_name = getattr(fr, 'name', fr) if fr is not None else None | ||||||
| finish_reason = _to_finish_reason(fr) | ||||||
| if finish_reason == FinishReason.BLOCKED: | ||||||
| return f'Image blocked by safety filters ({fr_name}).' | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. nit:
Suggested change
|
||||||
| # A truncated reply already says so in finish_reason; a prompt hint would mislead. | ||||||
| if finish_reason == FinishReason.LENGTH: | ||||||
| return None | ||||||
| if fr_name == 'IMAGE_OTHER': | ||||||
| return 'Image generation stopped (IMAGE_OTHER). Try revising the prompt.' | ||||||
| return _NO_IMAGE_MESSAGE | ||||||
|
|
||||||
|
|
||||||
| from genkit_google_genai._models._utils import ( # noqa: E402 | ||||||
| TOOL_INPUT_FIELD, | ||||||
| PartConverter, | ||||||
|
|
@@ -2120,16 +2145,15 @@ async def _generate( | |||||
| content = [Part.from_text('')] | ||||||
|
|
||||||
| # The reply is candidate 0, the same one _contents_from_response reads. | ||||||
| finish_reason = FinishReason.OTHER | ||||||
| if response.candidates: | ||||||
| finish_reason = _to_finish_reason(response.candidates[0].finish_reason) | ||||||
| candidate = response.candidates[0] | ||||||
|
|
||||||
| return ModelResponse( | ||||||
| message=Message( | ||||||
| content=content, | ||||||
| role=Role.MODEL, | ||||||
| ), | ||||||
| finish_reason=finish_reason, | ||||||
| finish_reason=_to_finish_reason(candidate.finish_reason), | ||||||
| finish_message=_finish_message(candidate.finish_reason, candidate.finish_message, content, model_name), | ||||||
| usage=_usage_from_metadata(response.usage_metadata), | ||||||
| custom=_custom_from_feedback(response.prompt_feedback), | ||||||
| ) | ||||||
|
|
@@ -2161,6 +2185,8 @@ async def _streaming_generate( | |||||
| raise missing_api_key_error() | ||||||
| accumulated_content: list[Part] = [] | ||||||
| finish_reason = FinishReason.UNKNOWN | ||||||
| last_fr: Any = None | ||||||
| finish_message: str | None = None | ||||||
| usage_metadata: Any = None | ||||||
| prompt_feedback: genai_types.GenerateContentResponsePromptFeedback | None = None | ||||||
| saw_chunk = False | ||||||
|
|
@@ -2190,9 +2216,12 @@ async def _streaming_generate( | |||||
| # otherwise a streamed turn reports no finish reason and no usage at all. | ||||||
| if response_chunk.candidates and response_chunk.candidates[0] is not None: | ||||||
| saw_candidates = True | ||||||
| fr = response_chunk.candidates[0].finish_reason | ||||||
| if fr: | ||||||
| finish_reason = _to_finish_reason(fr) | ||||||
| candidate = response_chunk.candidates[0] | ||||||
| if candidate.finish_reason: | ||||||
| last_fr = candidate.finish_reason | ||||||
| finish_reason = _to_finish_reason(last_fr) | ||||||
| if candidate.finish_message: | ||||||
| finish_message = candidate.finish_message | ||||||
| if response_chunk.usage_metadata is not None: | ||||||
| usage_metadata = response_chunk.usage_metadata | ||||||
| if response_chunk.prompt_feedback is not None: | ||||||
|
|
@@ -2216,6 +2245,7 @@ async def _streaming_generate( | |||||
| content=accumulated_content, | ||||||
| ), | ||||||
| finish_reason=finish_reason, | ||||||
| finish_message=_finish_message(last_fr, finish_message, accumulated_content, model_name), | ||||||
| usage=_usage_from_metadata(usage_metadata), | ||||||
| custom=_custom_from_feedback(prompt_feedback), | ||||||
| ) | ||||||
|
|
||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2358,6 +2358,149 @@ def test_to_finish_reason_image_other_and_unexpected_tool() -> None: | |
| assert _to_finish_reason('UNEXPECTED_TOOL_CALL') == FinishReason.OTHER | ||
|
|
||
|
|
||
| def _image_candidate( | ||
| parts: list[genai_types.Part], | ||
| finish_reason: genai_types.FinishReason | None = genai_types.FinishReason.STOP, | ||
| finish_message: str | None = None, | ||
| ) -> genai_types.GenerateContentResponse: | ||
| candidate = genai_types.Candidate( | ||
| content=genai_types.Content(parts=parts), | ||
| finish_reason=finish_reason, | ||
| finish_message=finish_message, | ||
| ) | ||
| return genai_types.GenerateContentResponse(candidates=[candidate]) | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| @pytest.mark.parametrize( | ||
| ('finish_reason', 'expected'), | ||
| [ | ||
| (genai_types.FinishReason.STOP, 'No image was returned'), | ||
| (genai_types.FinishReason.NO_IMAGE, 'No image was returned'), | ||
| (genai_types.FinishReason.IMAGE_SAFETY, 'Image blocked by safety filters (IMAGE_SAFETY).'), | ||
| ( | ||
| genai_types.FinishReason.IMAGE_PROHIBITED_CONTENT, | ||
| 'Image blocked by safety filters (IMAGE_PROHIBITED_CONTENT).', | ||
| ), | ||
| (genai_types.FinishReason.SAFETY, 'Image blocked by safety filters (SAFETY).'), | ||
| (genai_types.FinishReason.IMAGE_OTHER, 'Image generation stopped (IMAGE_OTHER)'), | ||
| ], | ||
| ) | ||
| async def test_generate_image_model_without_media_explains_why( | ||
| mocker: MockerFixture, finish_reason: genai_types.FinishReason, expected: str | ||
| ) -> None: | ||
| """An image model reply with no media carries a finish message, not a silent success.""" | ||
| client = mocker.AsyncMock() | ||
| client.aio.models.generate_content.return_value = _image_candidate( | ||
| [genai_types.Part(text='Sure!')], finish_reason=finish_reason | ||
| ) | ||
| gemini = GeminiModel('gemini-2.5-flash-image', client) | ||
|
|
||
| response = await gemini.generate(_hi_request(), ModelContext()) | ||
|
|
||
| assert response.finish_message is not None | ||
| assert response.finish_message.startswith(expected) | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_generate_image_model_truncated_has_no_prompt_hint(mocker: MockerFixture) -> None: | ||
| """A reply cut off by max tokens reports length, not advice about the prompt.""" | ||
| client = mocker.AsyncMock() | ||
| client.aio.models.generate_content.return_value = _image_candidate( | ||
| [genai_types.Part(text='Here is')], finish_reason=genai_types.FinishReason.MAX_TOKENS | ||
| ) | ||
| gemini = GeminiModel('gemini-2.5-flash-image', client) | ||
|
|
||
| response = await gemini.generate(_hi_request(), ModelContext()) | ||
|
|
||
| assert response.finish_reason == FinishReason.LENGTH | ||
| assert response.finish_message is None | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_generate_image_model_with_media_has_no_finish_message(mocker: MockerFixture) -> None: | ||
| """A reply that carries an image needs no explanation.""" | ||
| client = mocker.AsyncMock() | ||
| client.aio.models.generate_content.return_value = _image_candidate([ | ||
| genai_types.Part(inline_data=genai_types.Blob(data=b'\x89PNG\r\n\x1a\n', mime_type='image/png')) | ||
| ]) | ||
| gemini = GeminiModel('gemini-2.5-flash-image', client) | ||
|
|
||
| response = await gemini.generate(_hi_request(), ModelContext()) | ||
|
|
||
| assert response.finish_message is None | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| @pytest.mark.parametrize('version', ['gemini-2.5-flash', 'gemini-2.5-flash-image']) | ||
| async def test_generate_passes_candidate_finish_message_through(mocker: MockerFixture, version: str) -> None: | ||
| """The service's own finish message wins over the synthesized one.""" | ||
| client = mocker.AsyncMock() | ||
| client.aio.models.generate_content.return_value = _image_candidate( | ||
| [genai_types.Part(text='')], | ||
| finish_reason=genai_types.FinishReason.MALFORMED_FUNCTION_CALL, | ||
| finish_message='Malformed function call: foo', | ||
| ) | ||
| gemini = GeminiModel(version, client) | ||
|
|
||
| response = await gemini.generate(_hi_request(), ModelContext()) | ||
|
|
||
| assert response.finish_message == 'Malformed function call: foo' | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_generate_text_model_without_media_has_no_finish_message(mocker: MockerFixture) -> None: | ||
| """Text models are expected to answer without media.""" | ||
| client = mocker.AsyncMock() | ||
| client.aio.models.generate_content.return_value = _image_candidate([genai_types.Part(text='Yes.')]) | ||
| gemini = GeminiModel('gemini-2.5-flash', client) | ||
|
|
||
| response = await gemini.generate(_hi_request(), ModelContext()) | ||
|
|
||
| assert response.finish_message is None | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_generate_stream_image_model_finish_message(mocker: MockerFixture) -> None: | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Could we add tests for a reply that is only a tool request, a text-only reply on an image model, and a stream that ends with no finish reason? Those are the cases where the hint should not show. The stream tests also don't pin a few things. Each of these changes to
Maybe add: a stream with an image in chunk 1 and text with STOP after (expect |
||
| """Streaming keeps the trailing finish message, and explains a stream with no image.""" | ||
| client = mocker.AsyncMock() | ||
|
|
||
| async def mock_stream() -> Any: # noqa: ANN401 | ||
| yield _image_candidate([genai_types.Part(text='Here')], finish_reason=None) | ||
| yield _image_candidate([genai_types.Part(text=' you go')], finish_reason=genai_types.FinishReason.NO_IMAGE) | ||
|
|
||
| client.aio.models.generate_content_stream.return_value = mock_stream() | ||
| gemini = GeminiModel('gemini-2.5-flash-image', client) | ||
|
|
||
| response = await gemini.generate(_hi_request(), ModelContext(streaming_callback=mocker.MagicMock())) | ||
|
|
||
| assert response.finish_reason == FinishReason.OTHER | ||
| assert response.finish_message is not None | ||
| assert response.finish_message.startswith('No image was returned') | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_generate_stream_passes_candidate_finish_message_through(mocker: MockerFixture) -> None: | ||
| """Streaming keeps the service's finish message from the trailing chunk.""" | ||
| client = mocker.AsyncMock() | ||
|
|
||
| async def mock_stream() -> Any: # noqa: ANN401 | ||
| yield _image_candidate([genai_types.Part(text='Calling')], finish_reason=None) | ||
| yield _image_candidate( | ||
| [genai_types.Part(text='')], | ||
| finish_reason=genai_types.FinishReason.MALFORMED_FUNCTION_CALL, | ||
| finish_message='Malformed function call: foo', | ||
| ) | ||
|
|
||
| client.aio.models.generate_content_stream.return_value = mock_stream() | ||
| gemini = GeminiModel('gemini-2.5-flash', client) | ||
|
|
||
| response = await gemini.generate(_hi_request(), ModelContext(streaming_callback=mocker.MagicMock())) | ||
|
|
||
| assert response.finish_reason == FinishReason.OTHER | ||
| assert response.finish_message == 'Malformed function call: foo' | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def tts_model_instance() -> GeminiModel: | ||
| """Common initialization of a TTS GeminiModel.""" | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This only checks the model and whether a media part came back. It never looks at the request. On an image model, the hint "No image was returned. Try a clearer image prompt" also fires when:
toolRequest(GEMINI_IMAGE_SUPPORTSsetstools=True)multiturn=True)response_modalities=['TEXT']is setMALFORMED_FUNCTION_CALL,UNEXPECTED_TOOL_CALL,TOO_MANY_TOOL_CALLS,OTHER,FINISH_REASON_UNSPECIFIED, or a reason the SDK doesn't know yet, with no service messagefr is None), which givesunknownplus the hintIn those cases the hint reads as prompt advice and doesn't name the reason. I reproduced the tool-request, text-reply and TEXT-only cases. Maybe only add the prompt hint for
STOPandNO_IMAGEwhen the reply has no tool requests and no text, and otherwise name the raw reason? It's also fine to returnNonewhenfrisNone.