From ef76578032e76b4e3b232b2b8c48e6b9b649ebd0 Mon Sep 17 00:00:00 2001 From: xxwtiancai <761295965@qq.com> Date: Mon, 26 Oct 2026 22:28:19 +0800 Subject: [PATCH 1/2] fix(litellm): report a finish-less text stream as truncated, not stopped A stream that never delivers a finish_reason chunk finalized its buffered text as a clean STOP, so a cut-off answer looked complete to the agent, callbacks and telemetry. litellm usually hides this by substituting a synthetic stop, but the fallback is reachable through custom llm_client implementations streaming raw chunks, and older litellm versions end hard drops the same way. Finalize that case as FinishReason.OTHER with error_code and an explicit message. Tool-call streams keep their existing completeness discriminator (argument parseability) and the empty-stream default stays a clean stop. Refs #7693 (ADK-side half; the litellm synthetic-stop substitution needs an upstream litellm fix as discussed in the issue). --- src/google/adk/models/lite_llm.py | 53 +++++++----- tests/unittests/models/test_litellm.py | 112 +++++++++++++++++++++++++ 2 files changed, 146 insertions(+), 19 deletions(-) diff --git a/src/google/adk/models/lite_llm.py b/src/google/adk/models/lite_llm.py index e06eb32248b..59c3e492ee1 100644 --- a/src/google/adk/models/lite_llm.py +++ b/src/google/adk/models/lite_llm.py @@ -138,6 +138,12 @@ "content_filter": types.FinishReason.SAFETY, } +_STREAM_ENDED_WITHOUT_FINISH_REASON = "stream_ended_without_finish_reason" +"""Finish reason handed to the stream finalizers when a stream ended without +ever delivering a finish_reason chunk. Unmapped on purpose, so it becomes +``FinishReason.OTHER`` and the finalized response carries an ``error_code`` +instead of a clean ``STOP``.""" + def _quote_unquoted_json_object_keys(value: str) -> str: """Quotes simple unquoted object keys without touching string contents.""" @@ -4844,6 +4850,24 @@ def _finalized_thought_parts( ] return thought_parts or None + def _stamp_final_finish_reason( + llm_response: LlmResponse, finish_reason: str + ) -> LlmResponse: + mapped_finish_reason = _map_finish_reason(finish_reason) + if _malformed_args_outrank_provider( + response_finish_reason=llm_response.finish_reason, + provider_finish_reason=mapped_finish_reason, + ): + return llm_response + + _apply_provider_finish_reason(llm_response, mapped_finish_reason) + if finish_reason == _STREAM_ENDED_WITHOUT_FINISH_REASON: + llm_response.error_message = ( + "The stream ended without a finish reason; the response may" + " be truncated." + ) + return llm_response + def _finalize_tool_call_response( *, model_version: str, finish_reason: str ) -> LlmResponse: @@ -4949,15 +4973,7 @@ def _finalize_tool_call_response( has_tool_calls=bool(tool_calls) ), ) - mapped_finish_reason = _map_finish_reason(finish_reason) - if _malformed_args_outrank_provider( - response_finish_reason=llm_response.finish_reason, - provider_finish_reason=mapped_finish_reason, - ): - return llm_response - - _apply_provider_finish_reason(llm_response, mapped_finish_reason) - return llm_response + return _stamp_final_finish_reason(llm_response, finish_reason) def _finalize_text_response( *, model_version: str, finish_reason: str @@ -4971,15 +4987,7 @@ def _finalize_text_response( model_version=model_version, thought_parts=_finalized_thought_parts(has_tool_calls=False), ) - mapped_finish_reason = _map_finish_reason(finish_reason) - if _malformed_args_outrank_provider( - response_finish_reason=llm_response.finish_reason, - provider_finish_reason=mapped_finish_reason, - ): - return llm_response - - _apply_provider_finish_reason(llm_response, mapped_finish_reason) - return llm_response + return _stamp_final_finish_reason(llm_response, finish_reason) def _reset_stream_buffers() -> None: nonlocal reasoning_parts, last_finish_reason, saw_structured_tool_calls @@ -5259,6 +5267,9 @@ def _has_held_back_tool_calls() -> bool: if ( function_calls or _has_held_back_tool_calls() ) and not aggregated_llm_response_with_tool_call: + # A tool call has its own completeness discriminator — whether its + # arguments parse — so a stream missing only its terminal chunk still + # yields the finished call; keep that pinned contract. aggregated_llm_response_with_tool_call = _finalize_tool_call_response( model_version=resolved_model_version, finish_reason=last_finish_reason or "tool_calls", @@ -5280,7 +5291,9 @@ def _has_held_back_tool_calls() -> bool: if (text_parts or reasoning_parts) and not aggregated_llm_response: aggregated_llm_response = _finalize_text_response( model_version=resolved_model_version, - finish_reason=last_finish_reason or "stop", + finish_reason=( + last_finish_reason or _STREAM_ENDED_WITHOUT_FINISH_REASON + ), ) _reset_stream_buffers() elif ( @@ -5292,6 +5305,8 @@ def _has_held_back_tool_calls() -> bool: # normal stop/tool_calls/function_call/EOF with empty deltas). Finalize # an empty response so the finish_reason, error, and usage are # preserved rather than ending the generator having yielded nothing. + # The clean-stop default stays: with nothing buffered there is no + # partial answer to report as truncated. aggregated_llm_response = _finalize_text_response( model_version=resolved_model_version, finish_reason=last_finish_reason or "stop", diff --git a/tests/unittests/models/test_litellm.py b/tests/unittests/models/test_litellm.py index 080985bc3e5..db76221c1ab 100644 --- a/tests/unittests/models/test_litellm.py +++ b/tests/unittests/models/test_litellm.py @@ -6672,6 +6672,118 @@ async def test_generate_content_async_stream_sets_finish_reason( assert responses[-1].content.parts[0].text == "Hello world" +@pytest.mark.asyncio +async def test_generate_content_async_stream_without_finish_reason_reports_truncated_text( + mock_completion, lite_llm_instance +): + """A text stream ending without any finish chunk is not a clean stop. + + Reachable through custom ``llm_client`` implementations streaming raw + chunks (litellm itself substitutes a synthetic stop); the buffered text + is kept but finalized with an error so callers and telemetry can tell the + answer was cut off. + """ + mock_completion.return_value = iter([ + ModelResponseStream( + model="test_model", + choices=[ + StreamingChoices( + finish_reason=None, + delta=Delta(role="assistant", content="Oslo is "), + ) + ], + ), + ModelResponseStream( + model="test_model", + choices=[ + StreamingChoices( + finish_reason=None, delta=Delta(content="4C and") + ) + ], + ), + ]) + + llm_request = LlmRequest( + contents=[ + types.Content( + role="user", parts=[types.Part.from_text(text="Test prompt")] + ) + ], + ) + + responses = [ + response + async for response in lite_llm_instance.generate_content_async( + llm_request, stream=True + ) + if not response.partial + ] + + assert len(responses) == 1 + assert responses[0].content.parts[0].text == "Oslo is 4C and" + assert responses[0].finish_reason == types.FinishReason.OTHER + assert responses[0].error_code == types.FinishReason.OTHER + assert responses[0].error_message == ( + "The stream ended without a finish reason; the response may be" + " truncated." + ) + + +@pytest.mark.asyncio +async def test_generate_content_async_stream_trailing_usage_chunk_keeps_stop( + mock_completion, lite_llm_instance +): + """A finish chunk followed by a usage-only chunk keeps its clean stop. + + The finish reason belongs to the segment it ended; a later chunk without + one must not demote the finalized reason to a truncation report. + """ + mock_completion.return_value = iter([ + ModelResponseStream( + model="test_model", + choices=[ + StreamingChoices( + finish_reason=None, + delta=Delta(role="assistant", content="Hello world"), + ) + ], + ), + ModelResponseStream( + model="test_model", + choices=[StreamingChoices(finish_reason="stop", delta=Delta())], + ), + ModelResponseStream( + model="test_model", + choices=[StreamingChoices(finish_reason=None, delta=Delta())], + usage={ + "prompt_tokens": 5, + "completion_tokens": 2, + "total_tokens": 7, + }, + ), + ]) + + llm_request = LlmRequest( + contents=[ + types.Content( + role="user", parts=[types.Part.from_text(text="Test prompt")] + ) + ], + ) + + responses = [ + response + async for response in lite_llm_instance.generate_content_async( + llm_request, stream=True + ) + ] + + assert responses[-1].partial is False + assert responses[-1].finish_reason == types.FinishReason.STOP + assert responses[-1].error_code is None + assert responses[-1].content.parts[0].text == "Hello world" + + @pytest.mark.asyncio async def test_generate_content_async_stream_reports_content_filter( mock_completion, lite_llm_instance From 24fe017e50710b7e647bfca4b8be604e18ba5427 Mon Sep 17 00:00:00 2001 From: xxwtiancai <761295965@qq.com> Date: Tue, 27 Oct 2026 22:31:07 +0800 Subject: [PATCH 2/2] style: join truncated-stream message assertion line --- tests/unittests/models/test_litellm.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tests/unittests/models/test_litellm.py b/tests/unittests/models/test_litellm.py index db76221c1ab..cd4aeb034fa 100644 --- a/tests/unittests/models/test_litellm.py +++ b/tests/unittests/models/test_litellm.py @@ -6724,8 +6724,7 @@ async def test_generate_content_async_stream_without_finish_reason_reports_trunc assert responses[0].finish_reason == types.FinishReason.OTHER assert responses[0].error_code == types.FinishReason.OTHER assert responses[0].error_message == ( - "The stream ended without a finish reason; the response may be" - " truncated." + "The stream ended without a finish reason; the response may be truncated." )