#26212·mlflow

[BUG] AI Gateway Gemini and LiteLLM providers merge parallel tool calls in streaming (tool_calls index always 0)

Author: r14ddCreated Sep 27, 2026Updated Sep 29, 2026
Labelsbughas-closing-prreadyarea/gateway

[!WARNING] Before submitting a PR, please make sure that:

  • A maintainer has triaged this issue and applied the ready label
  • This issue has no assignee
  • No duplicate PR exists

PRs not meeting these requirements may be automatically closed.

Issues Policy acknowledgement

  • I have read and agree to submit bug reports in accordance with the issues policy

Where did you encounter this bug?

Local machine

MLflow version

  • Client: 3.16.2.dev0 (master, e7c895489).

System information

  • macOS 15, Python 3.10.21

Describe the problem

Same bug class as #26199, in two more providers. When the model returns two tool calls in one turn, the streaming path gives both tool_calls[].index=0. A client that merges deltas by index (openai-python, LangChain ChatOpenAI) gets one call: the second call's id and name, and both argument strings glued together, which is not valid JSON.

  • Gemini: GeminiAdapter builds ToolCallDelta(index=0) for every functionCall part (mlflow/gateway/providers/gemini.py:315). Gemini sends all parallel calls in one chunk, so every call in it gets index 0.
  • LiteLLM: LiteLLMProvider.chat_stream renumbers tool calls with enumerate inside each chunk (mlflow/gateway/providers/litellm.py:258,268) and drops tc.index. LiteLLM streams one tool call per chunk, so every call gets index 0.

Expected, per the OpenAI streaming format: tool_calls[].index 0 and 1, one entry per call.

I checked every provider with a streaming tool-call path against two scenarios (two parallel calls; text then one call), feeding real-shaped upstream streams through chat_stream:

provider parallel: index parallel: args
anthropic FAIL (#26199) PASS
bedrock PASS PASS
gemini FAIL FAIL, merged
litellm FAIL FAIL, merged
mistral PASS* PASS*
openai PASS PASS

* Mistral was fed an OpenAI-shaped stream, so this only shows the adapter passes the index through.

Cohere and TogetherAI have no streaming tool-call support, so they are out of scope.

Two smaller findings from the same run:

  • Gemini's _normalize_finish_reason (gemini.py:100-106) returns stop on a tool-call turn instead of tool_calls.
  • Bedrock uses contentBlockIndex as the tool-call index (bedrock.py:637,666), so text followed by one call gives index=1. Arguments survive, so clients cope, but it is not the OpenAI numbering.

Tracking information

N/A, gateway only.

Code to reproduce issue

Run from the repo root with PYTHONPATH=. python repro.py. Mocks the upstream the same way tests/gateway/providers/test_gemini.py and test_litellm.py do.

python
import asyncio, json
from types import SimpleNamespace as NS
from unittest import mock
from fastapi.encoders import jsonable_encoder
from mlflow.gateway.config import EndpointConfig
from mlflow.gateway.providers.gemini import GeminiProvider
from mlflow.gateway.providers.litellm import LiteLLMProvider
from mlflow.gateway.schemas import chat
from tests.gateway.tools import MockAsyncStreamingResponse

def merge(chunks):
    merged = {}
    for c in chunks:
        for tc in c["choices"][0]["delta"].get("tool_calls") or []:
            s = merged.setdefault(tc["index"], {"id": None, "name": None, "arguments": ""})
            s["id"] = tc.get("id") or s["id"]
            s["name"] = tc["function"].get("name") or s["name"]
            s["arguments"] += tc["function"].get("arguments") or ""
    return merged

def config(provider, name, cfg):
    return EndpointConfig(name="chat", endpoint_type="llm/v1/chat",
                          model={"provider": provider, "name": name, "config": cfg})

payload = chat.RequestPayload(messages=[{"role": "user", "content": "hi"}], stream=True)

async def gemini():
    body = {"candidates": [{"index": 0, "finishReason": "STOP", "content": {"role": "model", "parts": [
        {"functionCall": {"name": "get_weather", "args": {"city": "Paris"}}},
        {"functionCall": {"name": "get_time", "args": {"tz": "Asia/Tokyo"}}},
    ]}}]}
    stream = [f"data: {json.dumps(body)}\n".encode(), b"\n"]
    with mock.patch("aiohttp.ClientSession.post", return_value=MockAsyncStreamingResponse(stream)):
        p = GeminiProvider(config("gemini", "gemini-2.0-flash", {"gemini_api_key": "key"}))
        return merge([jsonable_encoder(c) async for c in p.chat_stream(payload)])

def tc(index, id=None, name=None, args=""):
    return NS(index=index, id=id, type="function" if id else None, function=NS(name=name, arguments=args))

def chunk(tool_call, finish=None):
    delta = NS(role=None, content=None, tool_calls=[tool_call])
    return NS(id="c", object="chat.completion.chunk", created=0, model="m", usage=None,
              choices=[NS(index=0, finish_reason=finish, delta=delta)])

async def litellm():
    chunks = [chunk(tc(0, "call_1", "get_weather")), chunk(tc(0, args='{"city":"Paris"}')),
              chunk(tc(1, "call_2", "get_time")), chunk(tc(1, args='{"tz":"Asia/Tokyo"}'), "tool_calls")]
    async def gen():
        for c in chunks:
            yield c
    with mock.patch("litellm.acompletion", return_value=gen()):
        p = LiteLLMProvider(config("litellm", "gpt-4o", {"litellm_auth_config": {"api_key": "key"}}))
        return merge([jsonable_encoder(c) async for c in p.chat_stream(payload)])

print("gemini: ", asyncio.run(gemini()))
print("litellm:", asyncio.run(litellm()))

Output:

gemini:  {0: {'id': 'call_2816b59cc1eeac50c49def699869e747', 'name': 'get_time', 'arguments': '{"city": "Paris"}{"tz": "Asia/Tokyo"}'}}
litellm: {0: {'id': 'call_2', 'name': 'get_time', 'arguments': '{"city":"Paris"}{"tz":"Asia/Tokyo"}'}}

Stack trace

No exception in the gateway. The client fails later on json.loads of the merged arguments.

Other info / logs

The existing streaming tests for both providers use a single tool call, so a hardcoded 0 looks correct.

Proposed fix:

  • Gemini: give each functionCall part its own index, counted across the whole stream.
  • LiteLLM: pass through tc.index instead of the enumerate counter.
  • Add one parametrized streaming test that runs two parallel calls through each provider with tool-call support and asserts distinct indices and parseable arguments. That would also have caught #26199.

Happy to take it if assigned. I would keep the Gemini finish_reason and the Bedrock offset out of this PR unless you want them in.

Willingness to contribute

Yes. I can contribute a fix for this bug independently.

What component(s) does this bug affect?

  • area/gateway: MLflow AI Gateway client APIs, server, and third-party integrations