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
30 changes: 24 additions & 6 deletions python/packages/gemini/agent_framework_gemini/_chat_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -1099,9 +1099,7 @@ def _process_generate_response(
messages=[Message(role="assistant", contents=contents, raw_representation=candidate)],
usage_details=self._parse_usage(response.usage_metadata),
model=response.model_version or model or self.model,
finish_reason=self._map_finish_reason(
candidate.finish_reason.name if candidate and candidate.finish_reason else None
),
finish_reason=self._response_finish_reason(response, candidate),
response_format=response_format,
raw_representation=response,
)
Expand All @@ -1123,9 +1121,7 @@ def _process_chunk(self, chunk: types.GenerateContentResponse, model: str) -> Ch
parts: list[types.Part] = (candidate.content.parts or []) if candidate and candidate.content else []
contents = self._parse_parts(parts, streaming=True)

finish_reason = self._map_finish_reason(
candidate.finish_reason.name if candidate and candidate.finish_reason else None
)
finish_reason = self._response_finish_reason(chunk, candidate)

# Attach usage to the final chunk only (when finish_reason is set).
if finish_reason and (usage := self._parse_usage(chunk.usage_metadata)):
Expand Down Expand Up @@ -1285,6 +1281,28 @@ def _parse_usage(self, usage: types.GenerateContentResponseUsageMetadata | None)
details["reasoning_output_token_count"] = v
return details or None

def _response_finish_reason(
self, response: types.GenerateContentResponse, candidate: types.Candidate | None
) -> FinishReasonLiteral | FinishReason | None:
"""Return the finish reason for a response or streaming chunk.

Args:
response: The ``GenerateContentResponse`` (or streaming chunk) from the Gemini API.
candidate: The first candidate of ``response``, or None if it has none.

Returns:
The mapped candidate finish reason, ``"content_filter"`` when Gemini blocked the prompt
itself, or None.
"""
if candidate and candidate.finish_reason:
return self._map_finish_reason(candidate.finish_reason.name)
# A blocked prompt sets prompt_feedback.block_reason. There are usually no candidates, but when
# a later automatic-continuation hop is blocked, the SDK keeps the earlier candidate with its
# finish_reason cleared.
if response.prompt_feedback and response.prompt_feedback.block_reason:
return "content_filter"
return None

def _map_finish_reason(self, reason: str | None) -> FinishReasonLiteral | FinishReason | None:
"""Map a Gemini finish reason string to the framework's FinishReasonLiteral.

Expand Down
49 changes: 49 additions & 0 deletions python/packages/gemini/tests/test_gemini_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,7 @@ def _make_response(
response.candidates = [candidate]
response.finish_reason = finish_reason
response.model_version = model_version
response.prompt_feedback = None

if prompt_tokens is not None or output_tokens is not None:
usage = MagicMock()
Expand Down Expand Up @@ -2963,6 +2964,54 @@ async def test_empty_candidates_in_stream_does_not_raise(candidates: list | None
assert updates[0].finish_reason is None


@pytest.mark.parametrize("stream", [False, True])
async def test_blocked_prompt_reports_content_filter(stream: bool) -> None:
"""A prompt blocked by Gemini (no candidates, prompt_feedback.block_reason set) reports content_filter."""
client, mock = _make_gemini_client()
blocked = types.GenerateContentResponse.model_validate({
"promptFeedback": {"blockReason": "SAFETY"},
"usageMetadata": {"promptTokenCount": 8, "totalTokenCount": 8},
"modelVersion": "gemini-2.5-flash",
})
mock.aio.models.generate_content = AsyncMock(return_value=blocked)
mock.aio.models.generate_content_stream = AsyncMock(return_value=_async_iter([blocked]))
messages = [Message(role="user", contents=[Content.from_text("Hi")])]

if stream:
response = await client.get_response(messages=messages, stream=True).get_final_response()
else:
response = await client.get_response(messages=messages)

assert response.text == ""
assert response.finish_reason == "content_filter"
assert response.usage_details is not None
assert response.usage_details["input_token_count"] == 8


@pytest.mark.parametrize("stream", [False, True])
async def test_blocked_continuation_hop_reports_content_filter(stream: bool) -> None:
"""A blocked automatic-continuation hop after an earlier hop returned text still reports content_filter."""
client, mock = _make_gemini_client()
partial = {"candidates": [{"content": {"role": "model", "parts": [{"text": "partial answer"}]}}]}
blocked = {"promptFeedback": {"blockReason": "SAFETY"}}
# generate_content merges the hops: the earlier candidate stays, with its finish_reason cleared.
mock.aio.models.generate_content = AsyncMock(
return_value=types.GenerateContentResponse.model_validate({**partial, **blocked})
)
mock.aio.models.generate_content_stream = AsyncMock(
return_value=_async_iter([types.GenerateContentResponse.model_validate(hop) for hop in (partial, blocked)])
)
messages = [Message(role="user", contents=[Content.from_text("Hi")])]

if stream:
response = await client.get_response(messages=messages, stream=True).get_final_response()
else:
response = await client.get_response(messages=messages)

assert response.text == "partial answer"
assert response.finish_reason == "content_filter"


# service_url


Expand Down
Loading