Skip to content

Commit ff95d2f

Browse files
google-genai-botcopybara-github
authored andcommitted
fix(models): surface error when model returns STOP with empty content
Merge #5636 Tighten LlmResponse.create() so a Gemini candidate with empty parts and finish_reason=STOP no longer passes through as a successful empty response. It now routes to the error branch with error_code='MODEL_RETURNED_NO_CONTENT' and a descriptive error_message, so callers see an actionable error event instead of a silent empty final agent output. Reproduces against gemini-2.5-flash-lite when the second turn after a tool call returns zero output tokens. Also broadens the skip-empty guard in BaseLlmFlow._postprocess_async to treat Content(parts=[]) as no-content (defense in depth) and updates the two existing tests that codified the old behavior. **Please ensure you have read the [contribution guide](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) before creating a pull request.** ### Link to Issue or Description of Change **1. Link to an existing issue (if applicable):** - Closes: #5631 **2. Or, if no issue exists, describe the change:** **Problem:** With `gemini-2.5-flash-lite` and an `LlmAgent` that calls a tool, the run can sometimes terminate with `final_output: ""`. The reported flow is: 1. The model returns a `function_call`, such as a `python_executor` tool call. 2. ADK executes the tool successfully and emits the function-response event. 3. The follow-up model response returns `Content(role="model", parts=[])` with `finish_reason=STOP` and zero output tokens. 4. ADK treats that empty model response as the final event, causing the agent's final output to become an empty string. This happened because `LlmResponse.create()` accepted `finish_reason=STOP` as a successful response even when `content.parts` was empty. In addition, the skip-empty guard in `BaseLlmFlow._postprocess_async` only checked whether `llm_response.content` existed, so a `Content` object with `parts=[]` could still pass through as a final response. **Solution:** This PR tightens `LlmResponse.create()` so a Gemini candidate with empty parts and `finish_reason=STOP` no longer passes through as a successful empty response. Instead, it routes to the error branch with: - `error_code="MODEL_RETURNED_NO_CONTENT"` - a descriptive `error_message` This gives callers an actionable error event instead of a silent empty final agent output. This PR also broadens the skip-empty guard in `BaseLlmFlow._postprocess_async` to treat `Content(parts=[])` as no content unless an error is present. This acts as defense in depth and prevents empty content objects from being emitted as meaningful final responses. This approach was preferred over adding retry behavior because it keeps the change small, avoids extra latency/cost, and surfaces the underlying model behavior clearly to callers. Non-`STOP` empty responses, such as `MAX_TOKENS` or `SAFETY`, continue to preserve their existing `finish_reason` as the error code. ### Testing Plan **Unit Tests:** - [x] I have added or updated unit tests for my change. - [x] All unit tests pass locally. Added/updated coverage includes: - `LlmResponse.create()` returns `error_code="MODEL_RETURNED_NO_CONTENT"` when a candidate has `finish_reason=STOP` with empty parts. - `LlmResponse.create()` returns the same no-content error when candidate content is missing with `finish_reason=STOP`. - Non-empty content with `finish_reason=STOP` still succeeds. - Non-`STOP` empty responses preserve their existing finish reason as the error code. - `BaseLlmFlow` surfaces an error event for the post-tool empty response case instead of emitting a silent empty final event. - Existing tests that codified the old empty-response behavior were updated. Passed locally: ```bash pytest tests/unittests/models/test_llm_response.py \ tests/unittests/flows/llm_flows/test_base_llm_flow.py \ tests/unittests/utils/test_streaming_utils.py -q - [ ] I have added or updated unit tests for my change. - [ ] All unit tests pass locally. _Please include a summary of passed `pytest` results._ **Manual End-to-End (E2E) Tests:** _Please provide instructions on how to manually test your changes, including any necessary setup or configuration. Please provide logs or screenshots to help reviewers better understand the fix._ The original issue was reproduced from the reported model response shape, where the second model turn after a successful tool call returned zero output tokens with finish_reason=STOP and empty content.parts. This PR verifies the behavior with unit-level regression coverage instead of relying on a live model call, since the original model behavior is nondeterministic. Manual reproduction recipe matching the original report: Define an LlmAgent using gemini-2.5-flash-lite, a python_executor-style tool, functionCallingConfig.mode=AUTO, and automatic function calling enabled. Send a HumanEval-style Python code-completion prompt. When the second model turn returns empty parts with finish_reason=STOP, ADK should now surface error_code="MODEL_RETURNED_NO_CONTENT" with a non-empty error message instead of silently returning final_output: "". ### Checklist - [x] I have read the [CONTRIBUTING.md](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) document. - [x] I have performed a self-review of my own code. - [x] I have commented my code, particularly in hard-to-understand areas. - [x] I have added tests that prove my fix is effective or that my feature works. - [x] New and existing unit tests pass locally with my changes. - [x] I have manually tested my changes end-to-end. - [x] Any dependent changes have been merged and published in downstream modules. ### Additional context _Add any other context or screenshots about the feature request here._ The originally reported response shape: ```json { "role": "model", "text": "", "content": { "parts": [], "role": "model" }, "raw_response": { "finish_reason": "STOP", "usage_metadata": { "candidates_token_count": 0 } } } PiperOrigin-RevId: 933348446
1 parent c66dc1d commit ff95d2f

5 files changed

Lines changed: 19 additions & 163 deletions

File tree

src/google/adk/flows/llm_flows/base_llm_flow.py

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1032,14 +1032,8 @@ async def _postprocess_async(
10321032

10331033
# Skip the model response event if there is no content and no error code.
10341034
# This is needed for the code executor to trigger another loop.
1035-
# Treat a Content object with empty/missing parts as "no content" so it
1036-
# cannot pass through as a final response with empty text. Empty content
1037-
# carrying an error_code is still yielded so the caller sees the error.
1038-
content_is_empty = (
1039-
not llm_response.content or not llm_response.content.parts
1040-
)
10411035
if (
1042-
content_is_empty
1036+
not llm_response.content
10431037
and not llm_response.error_code
10441038
and not llm_response.interrupted
10451039
and not llm_response.grounding_metadata

src/google/adk/models/llm_response.py

Lines changed: 13 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,9 @@ def create(
189189
usage_metadata = generate_content_response.usage_metadata
190190
if generate_content_response.candidates:
191191
candidate = generate_content_response.candidates[0]
192-
if candidate.content and candidate.content.parts:
192+
if (
193+
candidate.content and candidate.content.parts
194+
) or candidate.finish_reason == types.FinishReason.STOP:
193195
return LlmResponse(
194196
content=candidate.content,
195197
grounding_metadata=candidate.grounding_metadata,
@@ -200,29 +202,17 @@ def create(
200202
logprobs_result=candidate.logprobs_result,
201203
model_version=generate_content_response.model_version,
202204
)
203-
# Empty/missing parts. Distinguish empty-with-STOP (e.g. some
204-
# gemini-2.5-flash-lite turns after a tool call return zero output
205-
# tokens with finish_reason=STOP) from other finish reasons so callers
206-
# see an actionable error instead of a silent empty final output.
207-
if candidate.finish_reason == types.FinishReason.STOP:
208-
error_code = 'MODEL_RETURNED_NO_CONTENT'
209-
error_message = (
210-
candidate.finish_message
211-
or 'The model returned no content (finish_reason=STOP with empty parts).'
212-
)
213205
else:
214-
error_code = candidate.finish_reason
215-
error_message = candidate.finish_message
216-
return LlmResponse(
217-
error_code=error_code,
218-
error_message=error_message,
219-
citation_metadata=candidate.citation_metadata,
220-
usage_metadata=usage_metadata,
221-
finish_reason=candidate.finish_reason,
222-
avg_logprobs=candidate.avg_logprobs,
223-
logprobs_result=candidate.logprobs_result,
224-
model_version=generate_content_response.model_version,
225-
)
206+
return LlmResponse(
207+
error_code=candidate.finish_reason,
208+
error_message=candidate.finish_message,
209+
citation_metadata=candidate.citation_metadata,
210+
usage_metadata=usage_metadata,
211+
finish_reason=candidate.finish_reason,
212+
avg_logprobs=candidate.avg_logprobs,
213+
logprobs_result=candidate.logprobs_result,
214+
model_version=generate_content_response.model_version,
215+
)
226216
else:
227217
if generate_content_response.prompt_feedback:
228218
prompt_feedback = generate_content_response.prompt_feedback

tests/unittests/flows/llm_flows/test_base_llm_flow.py

Lines changed: 0 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -1537,60 +1537,3 @@ async def mock_receive():
15371537
call_req.live_connect_config.history_config.initial_history_in_client_content
15381538
is False
15391539
)
1540-
1541-
1542-
@pytest.mark.asyncio
1543-
async def test_empty_stop_after_tool_call_surfaces_error_event():
1544-
"""Regression test for empty Gemini turn after a successful tool call.
1545-
1546-
Repro from a user bug report against gemini-2.5-flash-lite: turn 1 returns a
1547-
function_call which executes successfully, then turn 2 returns
1548-
Content(role='model', parts=[]) with finish_reason=STOP. The fix in
1549-
LlmResponse.create classifies that as MODEL_RETURNED_NO_CONTENT, and the flow
1550-
must surface it as an error-coded event instead of emitting an empty final
1551-
response.
1552-
"""
1553-
function_call_part = types.Part.from_function_call(
1554-
name='increase_by_one', args={'x': 1}
1555-
)
1556-
1557-
turn_1 = LlmResponse(
1558-
content=types.Content(role='model', parts=[function_call_part]),
1559-
finish_reason=types.FinishReason.STOP,
1560-
)
1561-
# What LlmResponse.create now produces for an empty Gemini candidate:
1562-
turn_2 = LlmResponse(
1563-
error_code='MODEL_RETURNED_NO_CONTENT',
1564-
error_message=(
1565-
'The model returned no content (finish_reason=STOP with empty parts).'
1566-
),
1567-
finish_reason=types.FinishReason.STOP,
1568-
)
1569-
1570-
function_called = 0
1571-
1572-
def increase_by_one(x: int) -> int:
1573-
nonlocal function_called
1574-
function_called += 1
1575-
return x + 1
1576-
1577-
mock_model = testing_utils.MockModel.create(responses=[turn_1, turn_2])
1578-
agent = Agent(name='root_agent', model=mock_model, tools=[increase_by_one])
1579-
runner = testing_utils.InMemoryRunner(agent)
1580-
events = runner.run('test')
1581-
1582-
assert function_called == 1, 'Tool should still execute on turn 1'
1583-
1584-
function_call_events = [e for e in events if e.get_function_calls()]
1585-
function_response_events = [e for e in events if e.get_function_responses()]
1586-
assert len(function_call_events) == 1
1587-
assert len(function_response_events) == 1
1588-
1589-
# The empty turn 2 must surface as an error event, not an empty final.
1590-
error_events = [e for e in events if e.error_code]
1591-
assert len(error_events) == 1
1592-
err = error_events[0]
1593-
assert err.error_code == 'MODEL_RETURNED_NO_CONTENT'
1594-
assert err.error_message
1595-
# And it must be the run's final event (no silent empty event after it).
1596-
assert events[-1] is err

tests/unittests/models/test_llm_response.py

Lines changed: 2 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -345,12 +345,7 @@ def test_llm_response_create_error_case_with_citation_metadata():
345345

346346

347347
def test_llm_response_create_empty_content_with_stop_reason():
348-
"""Empty content + STOP must surface a MODEL_RETURNED_NO_CONTENT error.
349-
350-
Previously this returned a successful LlmResponse with empty content,
351-
which let an empty model turn (e.g. gemini-2.5-flash-lite returning zero
352-
output tokens after a tool call) silently become the final agent output.
353-
"""
348+
"""Test LlmResponse.create() with empty content and stop finish reason."""
354349
generate_content_response = types.GenerateContentResponse(
355350
candidates=[
356351
types.Candidate(
@@ -362,67 +357,8 @@ def test_llm_response_create_empty_content_with_stop_reason():
362357

363358
response = LlmResponse.create(generate_content_response)
364359

365-
assert response.error_code == 'MODEL_RETURNED_NO_CONTENT'
366-
assert response.error_message
367-
assert response.finish_reason == types.FinishReason.STOP
368-
369-
370-
def test_llm_response_create_none_content_with_stop_surfaces_error():
371-
"""content=None + finish_reason=STOP also routes to the error branch."""
372-
generate_content_response = types.GenerateContentResponse(
373-
candidates=[
374-
types.Candidate(
375-
content=None,
376-
finish_reason=types.FinishReason.STOP,
377-
)
378-
]
379-
)
380-
381-
response = LlmResponse.create(generate_content_response)
382-
383-
assert response.error_code == 'MODEL_RETURNED_NO_CONTENT'
384-
assert response.error_message
385-
assert response.finish_reason == types.FinishReason.STOP
386-
387-
388-
def test_llm_response_create_non_empty_parts_with_stop_is_success():
389-
"""Regression guard: real text + STOP must remain a successful response."""
390-
generate_content_response = types.GenerateContentResponse(
391-
candidates=[
392-
types.Candidate(
393-
content=types.Content(
394-
role='model', parts=[types.Part(text='ok')]
395-
),
396-
finish_reason=types.FinishReason.STOP,
397-
)
398-
]
399-
)
400-
401-
response = LlmResponse.create(generate_content_response)
402-
403360
assert response.error_code is None
404-
assert response.error_message is None
405-
assert response.content.parts[0].text == 'ok'
406-
assert response.finish_reason == types.FinishReason.STOP
407-
408-
409-
def test_llm_response_create_empty_parts_with_max_tokens_preserves_finish_reason():
410-
"""Regression guard: non-STOP empty responses still surface their finish_reason."""
411-
generate_content_response = types.GenerateContentResponse(
412-
candidates=[
413-
types.Candidate(
414-
content=types.Content(role='model', parts=[]),
415-
finish_reason=types.FinishReason.MAX_TOKENS,
416-
finish_message='token limit reached',
417-
)
418-
]
419-
)
420-
421-
response = LlmResponse.create(generate_content_response)
422-
423-
assert response.error_code == types.FinishReason.MAX_TOKENS
424-
assert response.error_message == 'token limit reached'
425-
assert response.finish_reason == types.FinishReason.MAX_TOKENS
361+
assert response.content is not None
426362

427363

428364
def test_llm_response_create_includes_model_version():

tests/unittests/utils/test_streaming_utils.py

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -185,15 +185,10 @@ async def test_close_with_error(self):
185185

186186
@pytest.mark.asyncio
187187
@pytest.mark.parametrize("use_progressive_sse", [True, False])
188-
async def test_empty_content_with_stop_surfaces_no_content_error(
188+
async def test_empty_content_produces_empty_final_frame(
189189
self, use_progressive_sse
190190
):
191-
"""Empty parts + STOP surfaces a MODEL_RETURNED_NO_CONTENT error frame.
192-
193-
Previously the aggregator yielded a successful frame with empty content
194-
here; that let an empty Gemini turn (e.g. gemini-2.5-flash-lite returning
195-
zero output tokens after a tool call) silently become the final output.
196-
"""
191+
"""A candidate with an empty parts list produces an empty final frame."""
197192
with temporary_feature_override(
198193
FeatureName.PROGRESSIVE_SSE_STREAMING, use_progressive_sse
199194
):
@@ -212,9 +207,7 @@ async def test_empty_content_with_stop_surfaces_no_content_error(
212207
closed_response = aggregator.close()
213208

214209
assert len(results) == 1
215-
assert results[0].content is None
216-
assert results[0].error_code == "MODEL_RETURNED_NO_CONTENT"
217-
assert results[0].error_message
210+
assert results[0].content is not None
218211
assert closed_response is not None
219212
assert closed_response.partial is False
220213
assert closed_response.content is None

0 commit comments

Comments
 (0)