fix(models): surface error when model returns STOP with empty content#5636
Closed
Oppong08 wants to merge 3 commits into
Closed
fix(models): surface error when model returns STOP with empty content#5636Oppong08 wants to merge 3 commits into
Oppong08 wants to merge 3 commits into
Conversation
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.
Collaborator
|
Hi @Oppong08 , Thank you for your contribution! We appreciate you taking the time to submit this pull request. Your PR has been received by the team and is currently under review. We will provide feedback as soon as we have an update to share. |
Collaborator
|
Hi @Jacksunwei , can you please review this. |
copybara-service Bot
pushed a commit
that referenced
this pull request
Jun 16, 2026
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 } } } Co-authored-by: George Weale <gweale@google.com> COPYBARA_INTEGRATE_REVIEW=#5636 from Oppong08:fix-empty-final-output-after-tool-call 545b969 PiperOrigin-RevId: 933249937
Collaborator
copybara-service Bot
pushed a commit
that referenced
this pull request
Jun 16, 2026
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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 before creating a pull request.
Link to Issue or Description of Change
1. Link to an existing issue (if applicable):
2. Or, if no issue exists, describe the change:
Problem:
With
gemini-2.5-flash-liteand anLlmAgentthat calls a tool, the run can sometimes terminate withfinal_output: "".The reported flow is:
function_call, such as apython_executortool call.Content(role="model", parts=[])withfinish_reason=STOPand zero output tokens.This happened because
LlmResponse.create()acceptedfinish_reason=STOPas a successful response even whencontent.partswas empty. In addition, the skip-empty guard inBaseLlmFlow._postprocess_asynconly checked whetherllm_response.contentexisted, so aContentobject withparts=[]could still pass through as a final response.Solution:
This PR tightens
LlmResponse.create()so a Gemini candidate with empty parts andfinish_reason=STOPno longer passes through as a successful empty response.Instead, it routes to the error branch with:
error_code="MODEL_RETURNED_NO_CONTENT"error_messageThis 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_asyncto treatContent(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-
STOPempty responses, such asMAX_TOKENSorSAFETY, continue to preserve their existingfinish_reasonas the error code.Testing Plan
Unit Tests:
Added/updated coverage includes:
LlmResponse.create()returnserror_code="MODEL_RETURNED_NO_CONTENT"when a candidate hasfinish_reason=STOPwith empty parts.LlmResponse.create()returns the same no-content error when candidate content is missing withfinish_reason=STOP.finish_reason=STOPstill succeeds.STOPempty responses preserve their existing finish reason as the error code.BaseLlmFlowsurfaces an error event for the post-tool empty response case instead of emitting a silent empty final event.Passed locally: