Skip to content

fix(litellm): keep Gemini thought signatures on streamed tool calls - #7441

Closed
vetler wants to merge 15 commits into
google:mainfrom
vetler:fix/litellm-streamed-thought-signature
Closed

vetler wants to merge 15 commits into
google:mainfrom
vetler:fix/litellm-streamed-thought-signature

Conversation

@vetler

@vetler vetler commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Link to Issue or Description of Change

1. Link to an existing issue (if applicable):

Problem:

With LiteLlm and stream=True, the thought_signature Gemini 3 attaches to a tool call is dropped while the streamed call is reassembled. FunctionChunk only carried id, name, args and index, and the assembled ChatCompletionMessageToolCall was built from those, so _extract_thought_signature_from_tool_call found nothing. The stored function-call part had no signature and Gemini 3 rejected the next request:

Function call is missing a thought_signature in functionCall parts.

The non-streaming path keeps the signature (#3627, #4650).

Solution:

  • FunctionChunk gets an optional thought_signature. Gemini signs only the first call of a parallel batch, so most chunks carry none.
  • _model_response_to_chunk fills it with the existing _extract_thought_signature_from_tool_call, so all the places a signature can arrive are covered (extra_content.google, provider_specific_fields, an id with an embedded signature).
  • The streaming loop keeps it per tool-call index, next to name, args and id.
  • _finalize_tool_call_response sets it as extra_content.google.thought_signature on the assembled tool call. _message_to_generate_content_response then restores it onto the part exactly as for a non-streamed response, so no second code path converts signatures.

A delta that carries only a signature (no name, no arguments) used to be dropped as empty. It is now kept: the signature goes to the call at the delta's own index (not the fallback index, which may already point past that call), or is held for the call that starts at that index next. Such a delta never opens a call of its own, which would reach the model without a name. Neither Vertex AI's OpenAI-compatible endpoint nor LiteLLM's vertex_ai provider sends this shape today (see the raw deltas below); both put the signature on the delta that names the call.

Testing Plan

Unit Tests:

  • I have added or updated unit tests for my change.
  • All unit tests pass locally.

New tests in tests/unittests/models/test_litellm.py:

  • test_model_response_to_chunk_keeps_thought_signature: the signature on a streamed delta reaches the FunctionChunk.
  • test_streaming_tool_call_keeps_thought_signature: the signature on the first of two argument fragments survives assembly, and _content_to_message_param sends it back on the follow-up request.
  • test_streaming_parallel_tool_calls_keep_signature_per_call: with two parallel calls where only the first is signed, the first part keeps its signature and the second stays None.
  • test_model_response_to_chunk_keeps_a_signature_only_delta: a delta with only a signature is no longer dropped as empty.
  • test_streaming_signature_after_its_call_signs_that_call: a signature-only delta that arrives after its call, with a second call in between, signs the first call and not the second.
  • test_streaming_signature_before_its_call_signs_that_call: a signature-only delta ahead of its call opens no call of its own and signs the call that follows.

All six fail on main and pass with the fix.

$ pytest tests/unittests/models/ tests/unittests/flows -q
2594 passed

$ tox -p auto   # pytest tests/unittests on Python 3.11-3.14, with main (ea656b03) merged in
py311: 18166 passed, 4 failed
py312: 18156 passed, 5 failed
py313: 18157 passed, 4 failed
py314: 18157 passed, 4 failed

None of the failures involve this change:

  • The four on every version are TestParseToolCallArguments logging tests added in a01b226, and main's own CI fails on the same four. They pass on their own and fail after tests/unittests/a2a/utils/test_agent_to_a2a.py, on main as well: to_a2a() sets the google_adk logger to INFO, and caplog.at_level(logging.DEBUG) only lowers the root logger, so the payload the tests look for is never logged.
  • The fifth on py312 is test_bigquery_agent_analytics_plugin.py::TestExactlyOnceDelivery::test_finalization_respects_remaining_close_budget[shutdown], which missed its 50 ms shutdown budget while four suites ran at once; it passed when rerun on its own.
  • kubernetes was pinned to 36.0.3: 37.0.0 breaks five test_gke_code_executor.py tests on main (GKE code executor unit tests fail with kubernetes 37.0.0, turning main CI red #7443, fix in test: fix GKE executor tests broken by kubernetes 37.0.0 #7444). The environments used uv's managed Python, because Homebrew's ships a sitecustomize module that test_import_loading.py flags.

pre-commit run --files on both changed files passes, and mypy reports no new errors in lite_llm.py.

Manual End-to-End (E2E) Tests:

  1. The reproduction script from LiteLlm streaming drops Gemini thought_signature from tool calls; Gemini 3 then rejects the follow-up request #7438 (LiteLLM client mocked with the shape the Vertex AI OpenAI-compatible endpoint returns):

    # main
    non-streamed thought_signature: b'opaque-signature'
    streamed thought_signature:     None
    
    # this branch
    non-streamed thought_signature: b'opaque-signature'
    streamed thought_signature:     b'opaque-signature'
    
  2. Live, against gemini-3-flash-preview with parallel calls: a Runner with RunConfig(streaming_mode=StreamingMode.SSE) and an LlmAgent with two tools, asked for the weather and the local time in two cities, so the model makes four parallel calls in one step. A wrapping client prints a summary of every raw tool-call delta. Run on both routes LiteLLM offers to Gemini on Vertex AI, authenticated with Application Default Credentials.

    Script (VERTEX_PROJECT=<project> ROUTE=openai|vertex_ai LOG_DELTAS=1 python e2e_parallel.py)
    """Live parallel tool calls through LiteLlm streaming, with the raw deltas logged."""
    
    import asyncio
    import os
    import sys
    
    import google.auth
    import google.auth.transport.requests
    from google.adk.agents import LlmAgent
    from google.adk.agents.run_config import RunConfig
    from google.adk.agents.run_config import StreamingMode
    from google.adk.models.lite_llm import LiteLlm
    from google.adk.models.lite_llm import LiteLLMClient
    from google.adk.runners import Runner
    from google.adk.sessions import InMemorySessionService
    from google.genai import types
    
    ROUTE = os.environ.get("ROUTE", "openai")  # openai | vertex_ai
    PROJECT = os.environ["VERTEX_PROJECT"]
    MODEL = os.environ.get("VERTEX_MODEL", "gemini-3-flash-preview")
    LOG_DELTAS = os.environ.get("LOG_DELTAS") == "1"
    
    
    def get_weather(city: str) -> dict:
      """Returns the weather for a city."""
      return {"city": city, "forecast": "rain", "temperature_c": 9}
    
    
    def get_time(city: str) -> dict:
      """Returns the local time in a city."""
      return {"city": city, "time": "14:05"}
    
    
    class LoggingClient(LiteLLMClient):
      """Passes calls through and prints a summary of every streamed tool-call delta."""
    
      def __init__(self):
        self.call = 0
    
      async def acompletion(self, model, messages, tools, **kwargs):
        self.call += 1
        stream = await super().acompletion(model, messages, tools, **kwargs)
        if not LOG_DELTAS or not kwargs.get("stream"):
          return stream
        call = self.call
    
        async def tee():
          n = 0
          async for part in stream:
            n += 1
            for choice in part.choices or []:
              delta = choice.delta
              for tc in getattr(delta, "tool_calls", None) or []:
                fn = tc.get("function")
                name = fn.get("name") if fn else None
                args = fn.get("arguments") if fn else None
                extra = tc.get("extra_content")
                psf = tc.get("provider_specific_fields")
                fpsf = getattr(fn, "provider_specific_fields", None) if fn else None
                tc_id = tc.get("id") or ""
                print(
                    f"  [request {call} delta {n}] index={tc.get('index')} "
                    f"id={'<embedded sig>' if '__thought__' in tc_id else (tc_id[:12] or None)} "
                    f"name={name!r} args_len={len(args) if args else 0} "
                    f"extra_content.google.thought_signature={'yes' if (extra or {}).get('google', {}).get('thought_signature') else 'no'} "
                    f"provider_specific_fields.thought_signature={'yes' if ((psf or {}).get('thought_signature') or (fpsf or {}).get('thought_signature')) else 'no'} "
                    f"finish={choice.finish_reason}"
                )
            yield part
    
        return tee()
    
    
    async def main():
      credentials, _ = google.auth.default(
          scopes=["https://www.googleapis.com/auth/cloud-platform"]
      )
      credentials.refresh(google.auth.transport.requests.Request())
      if ROUTE == "openai":
        model = LiteLlm(
            model=f"google/{MODEL}",
            api_base=(
                f"https://aiplatform.googleapis.com/v1/projects/{PROJECT}"
                "/locations/global/endpoints/openapi"
            ),
            api_key=credentials.token,
            custom_llm_provider="openai",
            llm_client=LoggingClient(),
        )
      else:
        model = LiteLlm(
            model=f"vertex_ai/{MODEL}",
            vertex_project=PROJECT,
            vertex_location="global",
            llm_client=LoggingClient(),
        )
      agent = LlmAgent(
          name="assistant",
          model=model,
          instruction=(
              "Answer with the tools. When the user asks about several cities or"
              " several things, call all the tools you need in parallel in one"
              " step."
          ),
          tools=[get_weather, get_time],
      )
      sessions = InMemorySessionService()
      runner = Runner(app_name="e2e", agent=agent, session_service=sessions)
      session = await sessions.create_session(app_name="e2e", user_id="u")
      try:
        async for event in runner.run_async(
            user_id="u",
            session_id=session.id,
            new_message=types.Content(
                role="user",
                parts=[types.Part(text="What's the weather and the local time in Oslo and in Bergen?")],
            ),
            run_config=RunConfig(streaming_mode=StreamingMode.SSE),
        ):
          if event.partial:
            continue
          if event.error_code or event.error_message:
            print(f"[{event.author}] error {event.error_code}: {event.error_message}")
          for part in event.content.parts if event.content else []:
            if part.function_call:
              sig = part.thought_signature
              print(
                  f"[{event.author}] function_call {part.function_call.name}"
                  f"({part.function_call.args}) thought_signature="
                  + (f"<{len(sig)} bytes>" if sig else "None")
              )
            elif part.function_response:
              print(f"[{event.author}] function_response {part.function_response.name}")
            elif part.text and not part.thought:
              print(f"[{event.author}] text: {part.text.strip()}")
      except Exception as e:  # pylint: disable=broad-exception-caught
        print(f"{type(e).__name__}: {str(e)[:400]}")
        sys.exit(1)
    
    
    asyncio.run(main())

    OpenAI-compatible endpoint (custom_llm_provider="openai"). The signature arrives in extra_content.google on the first call's delta, together with its name and arguments; the other three calls are unsigned. On main the stored calls have no signature and Vertex rejects the follow-up request:

    [assistant] function_call get_weather({'city': 'Oslo'}) thought_signature=None
    [assistant] function_call get_time({'city': 'Oslo'}) thought_signature=None
    [assistant] function_call get_weather({'city': 'Bergen'}) thought_signature=None
    [assistant] function_call get_time({'city': 'Bergen'}) thought_signature=None
    [assistant] function_response get_weather
    [assistant] function_response get_time
    [assistant] function_response get_weather
    [assistant] function_response get_time
    BadRequestError: litellm.BadRequestError: OpenAIException - Error code: 400 - [{'error': {'code': 400, 'message': 'Unable to submit request because function call `get_weather` in the 2. content block is missing a `thought_signature`. Learn more: https://docs.cloud.google.com/vertex-ai/generative-ai/docs/thought-signatures', 'status': 'INVALID_ARGUMENT'}}]
    

    With this change:

    [request 1 delta 1] index=0 id=call_1400329 name='get_weather' args_len=15 extra_content.google.thought_signature=yes provider_specific_fields.thought_signature=no finish=None
    [request 1 delta 2] index=1 id=call_1400340 name='get_time' args_len=15 extra_content.google.thought_signature=no provider_specific_fields.thought_signature=no finish=None
    [request 1 delta 3] index=2 id=call_1400341 name='get_weather' args_len=17 extra_content.google.thought_signature=no provider_specific_fields.thought_signature=no finish=None
    [request 1 delta 4] index=3 id=call_1400353 name='get_time' args_len=17 extra_content.google.thought_signature=no provider_specific_fields.thought_signature=no finish=None
    [assistant] function_call get_weather({'city': 'Oslo'}) thought_signature=<841 bytes>
    [assistant] function_call get_time({'city': 'Oslo'}) thought_signature=None
    [assistant] function_call get_weather({'city': 'Bergen'}) thought_signature=None
    [assistant] function_call get_time({'city': 'Bergen'}) thought_signature=None
    [assistant] function_response get_weather
    [assistant] function_response get_time
    [assistant] function_response get_weather
    [assistant] function_response get_time
    [assistant] text: In Oslo, it is currently 14:05 and the weather is rainy with a temperature of 9°C. Similarly in Bergen, it is 14:05 and the weather is also rainy with a temperature of 9°C.
    

    LiteLLM vertex_ai provider. The signature arrives in provider_specific_fields and embedded in the call id, which main already handles; this change keeps it working:

    [request 1 delta 1] index=0 id=<embedded sig> name='get_weather' args_len=16 extra_content.google.thought_signature=no provider_specific_fields.thought_signature=yes finish=None
    [request 1 delta 2] index=1 id=call_1694415 name='get_weather' args_len=18 extra_content.google.thought_signature=no provider_specific_fields.thought_signature=no finish=None
    [request 1 delta 3] index=2 id=call_1694421 name='get_time' args_len=16 extra_content.google.thought_signature=no provider_specific_fields.thought_signature=no finish=None
    [request 1 delta 4] index=3 id=call_1694424 name='get_time' args_len=18 extra_content.google.thought_signature=no provider_specific_fields.thought_signature=no finish=None
    [assistant] function_call get_weather({'city': 'Oslo'}) thought_signature=<720 bytes>
    [assistant] function_call get_weather({'city': 'Bergen'}) thought_signature=None
    [assistant] function_call get_time({'city': 'Oslo'}) thought_signature=None
    [assistant] function_call get_time({'city': 'Bergen'}) thought_signature=None
    [assistant] function_response get_weather
    [assistant] function_response get_weather
    [assistant] function_response get_time
    [assistant] function_response get_time
    [assistant] text: In Oslo, it is currently 14:05 and the weather is rainy with a temperature of 9°C. In Bergen, it is also 14:05 and the weather is rainy with a temperature of 9°C.
    

Checklist

  • I have read the CONTRIBUTING.md document.
  • I have performed a self-review of my own code.
  • I have commented my code, particularly in hard-to-understand areas.
  • I have added tests that prove my fix is effective or that my feature works.
  • New and existing unit tests pass locally with my changes.
  • I have manually tested my changes end-to-end.
  • Any dependent changes have been merged and published in downstream modules.

Additional context

Gemini 3 checks signatures only for function calls in the current turn, so the bug can go unnoticed: if a user-role message follows the function response (for example the instruction ADK adds as user content when static_instruction is set), the request succeeds without the signature.

🤖 Generated with Claude Code

@google-cla

google-cla Bot commented Oct 7, 2026

Copy link
Copy Markdown

Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).

View this failed invocation of the CLA check for more information.

For the most up to date status, view the checks section at the bottom of the pull request.

The streaming path rebuilt each tool call from its id, name and arguments
only, so the thought_signature Gemini 3 attaches to a call (in extra_content
on the Vertex AI OpenAI-compatible endpoint) never reached the function-call
part. The next request then failed with "Function call is missing a
thought_signature in functionCall parts". The non-streaming path kept it.

Carry the signature on FunctionChunk, keep it per tool-call index while the
stream is assembled, and set it on the assembled tool call, so the existing
extraction restores it onto the part as it does for non-streamed responses.

Fixes google#7438
@vetler
vetler force-pushed the fix/litellm-streamed-thought-signature branch from 678a42e to 42a5da3 Compare October 7, 2026 17:01
vetler added 8 commits October 8, 2026 09:23
…'s name

A tool-call delta carrying only a signature was dropped as empty, so a
provider that sends the signature apart from the name and arguments would
still lose it. Keep such deltas, attach the signature to the call at the
delta's own index, or hold it for the call that starts there next, and never
open a call for it, which would reach the model without a name.

Neither Vertex AI's OpenAI-compatible endpoint nor LiteLLM's vertex_ai
provider sends this shape today; both put the signature on the delta that
names the call.
copybara-service Bot pushed a commit that referenced this pull request Oct 8, 2026
@adk-bot

adk-bot commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator

Thank you @vetler for your contribution! 🎉

Your changes have been successfully imported and merged via Copybara in commit 3abea3e.

Closing this PR as the changes are now in the main branch.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

merged [Status] This PR is merged

Projects

None yet

Development

Successfully merging this pull request may close these issues.

LiteLlm streaming drops Gemini thought_signature from tool calls; Gemini 3 then rejects the follow-up request

3 participants