Skip to content
Closed
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
53 changes: 34 additions & 19 deletions src/google/adk/models/lite_llm.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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",
Expand All @@ -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 (
Expand All @@ -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",
Expand Down
111 changes: 111 additions & 0 deletions tests/unittests/models/test_litellm.py
Original file line number Diff line number Diff line change
Expand Up @@ -6672,6 +6672,117 @@ 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
Expand Down
Loading