adk-python icon indicating copy to clipboard operation
adk-python copied to clipboard

The LiteLLM wrapper does not propagate `finish_reason` from LiteLLM responses

Open aperepel opened this issue 1 year ago • 5 comments

Describe the bug

The LiteLLM wrapper does not propagate finish_reason from LiteLLM responses to LlmResponse.finish_reason. This makes it impossible for after_model_callback functions to detect when the max_tokens limit is hit or other completion conditions occur.

When using LiteLLM models, llm_response.finish_reason is always None, even when LiteLLM returns a valid finish_reason value (e.g., "length" for max_tokens truncation).

To Reproduce

Minimal reproduction code:

import asyncio
from google.adk import Agent, Runner
from google.adk.agents.callback_context import CallbackContext
from google.adk.models.lite_llm import LiteLlm
from google.adk.models.llm_response import LlmResponse
from google.adk.sessions import InMemorySessionService
from google.genai import types


def create_inspector():
    """Callback to capture finish_reason."""
    captured = {"finish_reason": None}

    def inspector(ctx: CallbackContext, resp: LlmResponse) -> LlmResponse:
        captured["finish_reason"] = resp.finish_reason
        return resp

    inspector.captured = captured
    return inspector


async def test():
    # Create model with low max_tokens to trigger truncation
    model = LiteLlm(
        model="gpt-3.5-turbo",
        api_key="your-key",
        max_tokens=50,  # Intentionally low
    )

    inspector = create_inspector()

    agent = Agent(
        model=model,
        name="test",
        instruction="Provide detailed explanations.",
        after_model_callback=inspector,
    )

    session_service = InMemorySessionService()
    runner = Runner(
        app_name="test",
        agent=agent,
        session_service=session_service
    )

    await session_service.create_session(
        app_name="test",
        user_id="user",
        session_id="session",
        state={},
    )

    message = types.Content(
        role="user",
        parts=[types.Part(text="Explain quantum computing in detail.")]
    )

    async for _ in runner.run_async(
        user_id="user",
        session_id="session",
        new_message=message
    ):
        pass

    print(f"finish_reason: {inspector.captured['finish_reason']}")
    # Output: finish_reason: None (BUG - should be "length")


asyncio.run(test())

Steps to reproduce:

  1. Install: pip install google-adk litellm openai
  2. Run the code above with a valid API key
  3. Observe that finish_reason is None even though LiteLLM returned "length"

Expected behavior

llm_response.finish_reason should contain the finish_reason value from LiteLLM:

  • "stop" for natural completion
  • "length" for max_tokens limit reached
  • "tool_calls" for tool invocations
  • "content_filter" for filtered content

This matches the behavior of native Gemini models, where finish_reason is properly populated.

Root Cause

In google/adk/models/lite_llm.py, the _model_response_to_generate_content_response() function (lines 473-499) extracts usage_metadata from the LiteLLM response but does not extract finish_reason:

def _model_response_to_generate_content_response(response):
    message = None
    if response.get("choices", None):
        message = response["choices"][0].get("message", None)
        # Missing: finish_reason = response["choices"][0].get("finish_reason", None)

    llm_response = _message_to_generate_content_response(message)
    # Missing: llm_response.finish_reason = finish_reason

    if response.get("usage", None):
        llm_response.usage_metadata = types.GenerateContentResponseUsageMetadata(...)

    return llm_response

The LiteLLM response contains response["choices"][0]["finish_reason"], but this is never extracted or set on the LlmResponse object.

Proposed Fix

Add 3 lines to extract and set finish_reason:

def _model_response_to_generate_content_response(response):
    message = None
    finish_reason = None  # ADD

    if response.get("choices", None):
        message = response["choices"][0].get("message", None)
        finish_reason = response["choices"][0].get("finish_reason", None)  # ADD

    if not message:
        raise ValueError("No message in response")

    llm_response = _message_to_generate_content_response(message)
    if finish_reason:  # ADD
        llm_response.finish_reason = finish_reason  # ADD

    if response.get("usage", None):
        llm_response.usage_metadata = types.GenerateContentResponseUsageMetadata(...)

    return llm_response

A complete patch file is available here: litellm_finish_reason.patch

Desktop (please complete the following information):

  • OS: macOS (also reproduced on Linux)
  • Python version: 3.12.0
  • ADK version: 1.11.0

Model Information:

  • Are you using LiteLLM: Yes
  • Which model is being used: gpt-3.5-turbo, gpt-4o (any LiteLLM-supported model)

Additional context

Impact: This bug prevents callbacks from:

  • Detecting when responses are truncated due to max_tokens limits
  • Implementing retry logic for incomplete responses
  • Logging completion statistics
  • Handling different completion conditions appropriately

Validation: A standalone reproduction script with automated validation is available at litellm_finish_reason_bug.py. This script demonstrates both the bug and validates the proposed fix.

Note on Tracing: After this fix is applied, google/adk/telemetry/tracing.py:222 will need updating to handle both enum (Gemini) and string (LiteLLM) finish_reason values:

if llm_response.finish_reason:
    if hasattr(llm_response.finish_reason, 'value'):
        finish_reason_str = llm_response.finish_reason.value.lower()
    else:
        finish_reason_str = str(llm_response.finish_reason)
    span.set_attribute('gen_ai.response.finish_reasons', [finish_reason_str])

Without this, tracing will raise AttributeError: 'str' object has no attribute 'value'.

aperepel avatar Oct 08 '25 02:10 aperepel

diff --git a/google/adk/models/lite_llm.py b/google/adk/models/lite_llm.py
index 1234567..abcdefg 100644
--- a/google/adk/models/lite_llm.py
+++ b/google/adk/models/lite_llm.py
@@ -482,13 +482,18 @@ def _model_response_to_generate_content_response(
     The LlmResponse.
   """

   message = None
+  finish_reason = None
+
   if response.get("choices", None):
     message = response["choices"][0].get("message", None)
+    finish_reason = response["choices"][0].get("finish_reason", None)

   if not message:
     raise ValueError("No message in response")

   llm_response = _message_to_generate_content_response(message)
+  if finish_reason:
+    llm_response.finish_reason = finish_reason
+
   if response.get("usage", None):
     llm_response.usage_metadata = types.GenerateContentResponseUsageMetadata(
         prompt_token_count=response["usage"].get("prompt_tokens", 0),
--
2.39.0

aperepel avatar Oct 08 '25 02:10 aperepel

"""
Bug Report: LiteLLM finish_reason not propagated to LlmResponse
================================================================

ISSUE: google.adk.models.lite_llm._model_response_to_generate_content_response()
       does not propagate finish_reason from LiteLLM response to LlmResponse.

IMPACT: Callbacks cannot detect max_tokens truncation or other finish conditions.

REPRODUCTION:
    1. Use LiteLLM with low max_tokens (e.g., 50 tokens)
    2. Prompt model to generate verbose response
    3. LiteLLM returns finish_reason="length" in response
    4. ADK LlmResponse.finish_reason is None (should be "length")

EXPECTED: LlmResponse.finish_reason should contain the finish_reason from LiteLLM.
ACTUAL:   LlmResponse.finish_reason is always None.

LOCATION: google/adk/models/lite_llm.py:473-499
          _model_response_to_generate_content_response() function

ROOT CAUSE:
    The function extracts usage_metadata from response["usage"] but never
    extracts finish_reason from response["choices"][0]["finish_reason"].

PROPOSED FIX: Extract and set finish_reason in LlmResponse.

Requirements:
    pip install google-adk litellm openai

Usage:
    # Test with OpenAI-compatible endpoint (e.g., LM Studio, OpenAI)
    export LLM_API_BASE="http://localhost:1234/v1"  # Or use OpenAI default
    export LLM_API_KEY="your-key"
    export LLM_MODEL="gpt-3.5-turbo"  # Or your model

    python litellm_finish_reason_bug.py
"""

import asyncio
import os
from typing import Optional

from google.adk import Agent, Runner
from google.adk.agents.callback_context import CallbackContext
from google.adk.models.lite_llm import LiteLlm
from google.adk.models.llm_response import LlmResponse
from google.adk.sessions import InMemorySessionService
from google.genai import types


# =============================================================================
# Test Configuration
# =============================================================================

API_BASE = os.getenv("LLM_API_BASE", "https://api.openai.com/v1")
API_KEY = os.getenv("LLM_API_KEY", "dummy")
MODEL = os.getenv("LLM_MODEL", "gpt-3.5-turbo")
LOW_MAX_TOKENS = 50  # Intentionally low to trigger truncation


# =============================================================================
# Callback to inspect finish_reason
# =============================================================================

def create_finish_reason_inspector():
    """Creates callback that captures finish_reason for inspection."""
    captured = {"finish_reason": None}

    def inspector(
        callback_context: CallbackContext,
        llm_response: LlmResponse
    ) -> LlmResponse:
        captured["finish_reason"] = llm_response.finish_reason
        return llm_response

    inspector.captured = captured
    return inspector


# =============================================================================
# BUG: finish_reason is None
# =============================================================================

async def test_bug_finish_reason_not_propagated():
    """
    Demonstrates the bug: finish_reason is None despite LiteLLM returning "length".
    """
    print("="*80)
    print("TEST 1: BUG - finish_reason not propagated")
    print("="*80)

    # Create model with low max_tokens to trigger truncation
    model = LiteLlm(
        model=MODEL,
        api_base=API_BASE if API_BASE != "https://api.openai.com/v1" else None,
        api_key=API_KEY,
        temperature=0.0,
        max_tokens=LOW_MAX_TOKENS,
    )

    # Create inspector callback
    inspector = create_finish_reason_inspector()

    # Create agent
    agent = Agent(
        model=model,
        name="test_agent",
        instruction="Provide verbose, detailed explanations.",
        after_model_callback=inspector,
    )

    # Run agent
    session_service = InMemorySessionService()
    runner = Runner(
        app_name="bug_test",
        agent=agent,
        session_service=session_service
    )

    await session_service.create_session(
        app_name="bug_test",
        user_id="user",
        session_id="session",
        state={},
    )

    message = types.Content(
        role="user",
        parts=[types.Part(text="Explain quantum computing in detail.")]
    )

    async for _ in runner.run_async(
        user_id="user",
        session_id="session",
        new_message=message
    ):
        pass

    # Check result
    finish_reason = inspector.captured["finish_reason"]

    print(f"\nResult:")
    print(f"  finish_reason: {finish_reason}")
    print(f"  Type: {type(finish_reason)}")

    if finish_reason is None:
        print(f"\n❌ BUG CONFIRMED: finish_reason is None")
        print(f"   Expected: 'length' (from LiteLLM response)")
        print(f"   Actual: None")
        return False
    else:
        print(f"\n✓ finish_reason propagated: {finish_reason}")
        return True


# =============================================================================
# FIX: Monkey patch to propagate finish_reason
# =============================================================================

def apply_finish_reason_fix():
    """
    Applies fix to propagate finish_reason from LiteLLM response.

    This is the proposed fix for the bug.
    """
    import google.adk.models.lite_llm as lite_llm_module
    from google.adk.models.lite_llm import _message_to_generate_content_response
    from google.genai import types

    def _fixed_model_response_to_generate_content_response(response):
        """
        Fixed version that propagates finish_reason.

        Changes from original:
        - Line 70: Extract finish_reason from response
        - Line 77: Set finish_reason on llm_response
        """
        message = None
        finish_reason = None  # ← FIX: Capture finish_reason

        if response.get("choices", None):
            message = response["choices"][0].get("message", None)
            finish_reason = response["choices"][0].get("finish_reason", None)  # ← FIX

        if not message:
            raise ValueError("No message in response")

        llm_response = _message_to_generate_content_response(message)

        # ← FIX: Set finish_reason
        if finish_reason:
            llm_response.finish_reason = finish_reason

        if response.get("usage", None):
            llm_response.usage_metadata = types.GenerateContentResponseUsageMetadata(
                prompt_token_count=response["usage"].get("prompt_tokens", 0),
                candidates_token_count=response["usage"].get("completion_tokens", 0),
                total_token_count=response["usage"].get("total_tokens", 0),
            )

        return llm_response

    # Apply fix
    lite_llm_module._model_response_to_generate_content_response = (
        _fixed_model_response_to_generate_content_response
    )


async def test_fix_finish_reason_propagated():
    """
    Demonstrates the fix: finish_reason is properly propagated.

    Note: This also applies a tracing fix to avoid AttributeError when
    tracing.py tries to call .value on string finish_reason.
    """
    print("\n" + "="*80)
    print("TEST 2: FIX - finish_reason propagated correctly")
    print("="*80)

    # Apply fix BEFORE creating agents
    apply_finish_reason_fix()

    # Also need to fix tracing to handle string finish_reason
    import google.adk.telemetry.tracing as tracing_module
    import google.adk.flows.llm_flows.base_llm_flow as base_llm_flow_module
    from google.adk.telemetry.tracing import (
        _build_llm_request_for_trace,
        _safe_json_serialize,
    )
    from opentelemetry import trace

    def _patched_trace_call_llm(invocation_context, event_id, llm_request, llm_response):
        """Handle both enum (Gemini) and string (LiteLLM) finish_reason."""
        span = trace.get_current_span()
        span.set_attribute('gen_ai.system', 'gcp.vertex.agent')
        span.set_attribute('gen_ai.request.model', llm_request.model)
        span.set_attribute('gcp.vertex.agent.invocation_id', invocation_context.invocation_id)
        span.set_attribute('gcp.vertex.agent.session_id', invocation_context.session.id)
        span.set_attribute('gcp.vertex.agent.event_id', event_id)
        span.set_attribute(
            'gcp.vertex.agent.llm_request',
            _safe_json_serialize(_build_llm_request_for_trace(llm_request)),
        )

        if llm_request.config:
            if llm_request.config.top_p:
                span.set_attribute('gen_ai.request.top_p', llm_request.config.top_p)
            if llm_request.config.max_output_tokens:
                span.set_attribute('gen_ai.request.max_tokens', llm_request.config.max_output_tokens)

        try:
            llm_response_json = llm_response.model_dump_json(exclude_none=True)
        except Exception:
            llm_response_json = '<not serializable>'
        span.set_attribute('gcp.vertex.agent.llm_response', llm_response_json)

        if llm_response.usage_metadata is not None:
            span.set_attribute('gen_ai.usage.input_tokens', llm_response.usage_metadata.prompt_token_count)
            if llm_response.usage_metadata.candidates_token_count is not None:
                span.set_attribute('gen_ai.usage.output_tokens', llm_response.usage_metadata.candidates_token_count)

        # Handle finish_reason (both enum and string)
        if llm_response.finish_reason:
            if hasattr(llm_response.finish_reason, 'value'):
                finish_reason_str = llm_response.finish_reason.value.lower()
            else:
                finish_reason_str = str(llm_response.finish_reason)
            span.set_attribute('gen_ai.response.finish_reasons', [finish_reason_str])

    tracing_module.trace_call_llm = _patched_trace_call_llm
    base_llm_flow_module.trace_call_llm = _patched_trace_call_llm

    # Create model with low max_tokens
    model = LiteLlm(
        model=MODEL,
        api_base=API_BASE if API_BASE != "https://api.openai.com/v1" else None,
        api_key=API_KEY,
        temperature=0.0,
        max_tokens=LOW_MAX_TOKENS,
    )

    # Create inspector callback
    inspector = create_finish_reason_inspector()

    # Create agent
    agent = Agent(
        model=model,
        name="test_agent",
        instruction="Provide verbose, detailed explanations.",
        after_model_callback=inspector,
    )

    # Run agent
    session_service = InMemorySessionService()
    runner = Runner(
        app_name="fix_test",
        agent=agent,
        session_service=session_service
    )

    await session_service.create_session(
        app_name="fix_test",
        user_id="user",
        session_id="session",
        state={},
    )

    message = types.Content(
        role="user",
        parts=[types.Part(text="Explain quantum computing in detail.")]
    )

    async for _ in runner.run_async(
        user_id="user",
        session_id="session",
        new_message=message
    ):
        pass

    # Check result
    finish_reason = inspector.captured["finish_reason"]

    print(f"\nResult:")
    print(f"  finish_reason: {finish_reason}")
    print(f"  Type: {type(finish_reason)}")

    if finish_reason is not None:
        print(f"\n✅ FIX VALIDATED: finish_reason propagated correctly")
        print(f"   Value: '{finish_reason}'")
        print(f"   This matches LiteLLM response finish_reason")
        return True
    else:
        print(f"\n❌ FIX FAILED: finish_reason is still None")
        return False


# =============================================================================
# Main
# =============================================================================

async def main():
    """Run both tests to demonstrate bug and fix."""
    print("\n" + "="*80)
    print("GOOGLE ADK BUG REPORT: LiteLLM finish_reason not propagated")
    print("="*80)
    print(f"\nConfiguration:")
    print(f"  API_BASE: {API_BASE}")
    print(f"  MODEL: {MODEL}")
    print(f"  max_tokens: {LOW_MAX_TOKENS} (intentionally low)")
    print()

    # Test 1: Show bug
    bug_result = await test_bug_finish_reason_not_propagated()

    # Test 2: Show fix
    fix_result = await test_fix_finish_reason_propagated()

    # Summary
    print("\n" + "="*80)
    print("SUMMARY")
    print("="*80)
    print(f"Bug confirmed: {not bug_result}")
    print(f"Fix validated: {fix_result}")

    if not bug_result and fix_result:
        print("\n✅ Bug successfully reproduced and fix validated!")
        print("\nProposed changes to google/adk/models/lite_llm.py:")
        print("  Line ~475: Add: finish_reason = None")
        print("  Line ~479: Add: finish_reason = response['choices'][0].get('finish_reason', None)")
        print("  Line ~486: Add: if finish_reason: llm_response.finish_reason = finish_reason")
    else:
        print("\n⚠️  Unexpected test results")


if __name__ == "__main__":
    asyncio.run(main())

aperepel avatar Oct 08 '25 02:10 aperepel

I have successfully completed a PR review with Gemini bot, appreciate you giving a final thumbs up.

aperepel avatar Oct 15 '25 17:10 aperepel

@lizzij will take a look at this issue.

lizzij avatar Oct 27 '25 16:10 lizzij

Hi @lizzij for getting a fix in. The next release will have this fix! If it does not fix your issue please reopen!

GWeale avatar Oct 30 '25 22:10 GWeale