[BUG] AI Gateway Anthropic provider merges parallel tool calls in streaming (tool_calls index always 0, block index leaks into choices)
[!WARNING] Before submitting a PR, please make sure that:
- A maintainer has triaged this issue and applied the
readylabel- 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,
98041cdf2). Same code on 3.16.x.
System information
- macOS 15, Python 3.10.21
Describe the problem
When Claude returns two or more tool calls in one turn, the streaming path of the Anthropic provider merges them into one broken call on the client side.
AnthropicAdapter.model_to_chat_streaming hardcodes ToolCallDelta(index=0) for both the tool_use block start and every input_json_delta. The Anthropic content block index is put into choices[].index instead. So a stream with tool_use blocks at index 0 and 1 comes out as:
choice=0 tool_call.index=0 id=toolu_A name=get_weather
choice=0 tool_call.index=0 args='{"city":"Paris"}'
choice=1 tool_call.index=0 id=toolu_B name=get_time
choice=1 tool_call.index=0 args='{"tz":"Asia/Tokyo"}'Clients handle this two ways, both wrong:
- openai-python's
ChatCompletionStreamStatekeys onchoices[].index, so ann=1request comes back with two choices.choices[0].message.tool_callshas onlyget_weather;get_timesits inchoices[1], which callers never read. - LangChain's
ChatOpenAIand other clients that readchoices[0]positionally merge bytool_calls[].indexand get one call:{'id': 'toolu_B', 'name': 'get_time', 'arguments': '{"city":"Paris"}{"tz":"Asia/Tokyo"}'}. The first call is lost and the arguments are not valid JSON.
The message_delta finish chunk is also emitted once per content block index, so the client sees two finish chunks.
Expected, per the OpenAI streaming format the gateway targets: every chunk in choices[0], tool_calls[].index 0 and 1, one finish chunk.
The non-streaming path is fine: model_to_chat collects all tool_use blocks into one message. The Bedrock adapter does it right for streaming (index=contentBlockIndex). Only the Anthropic adapter loses the index.
Code: mlflow/gateway/providers/anthropic.py lines 460 and 470 (index=0), 490 (index=resp["index"]), 717-732 (the per-index message_delta fan-out in chat_stream).
Tracking information
N/A, gateway only.
Code to reproduce issue
Feeds a real-shaped Anthropic SSE stream with two tool_use blocks through the provider, the same way tests/gateway/providers/test_anthropic.py does. Run from the repo root with PYTHONPATH=. python repro.py.
import asyncio, json
from unittest import mock
from fastapi.encoders import jsonable_encoder
from mlflow.gateway.config import EndpointConfig
from mlflow.gateway.providers.anthropic import AnthropicProvider
from mlflow.gateway.schemas import chat
from tests.gateway.tools import MockAsyncStreamingResponse
def ev(o):
return [f"event: {o['type']}\n".encode(), f"data: {json.dumps(o)}\n".encode(), b"\n"]
def tool_block(i, tid, name, args):
return [*ev({"type": "content_block_start", "index": i,
"content_block": {"type": "tool_use", "id": tid, "name": name, "input": {}}}),
*ev({"type": "content_block_delta", "index": i,
"delta": {"type": "input_json_delta", "partial_json": args}}),
*ev({"type": "content_block_stop", "index": i})]
stream = [
*ev({"type": "message_start", "message": {"id": "msg_1", "type": "message", "role": "assistant",
"content": [], "model": "claude-sonnet-5", "stop_reason": None, "stop_sequence": None,
"usage": {"input_tokens": 30, "output_tokens": 1}}}),
*tool_block(0, "toolu_A", "get_weather", '{"city":"Paris"}'),
*tool_block(1, "toolu_B", "get_time", '{"tz":"Asia/Tokyo"}'),
*ev({"type": "message_delta", "delta": {"stop_reason": "tool_use", "stop_sequence": None},
"usage": {"output_tokens": 40}}),
*ev({"type": "message_stop"}),
]
config = EndpointConfig(name="chat", endpoint_type="llm/v1/chat",
model={"provider": "anthropic", "name": "claude-sonnet-5", "config": {"anthropic_api_key": "key"}})
async def main():
with mock.patch("aiohttp.ClientSession.post", return_value=MockAsyncStreamingResponse(stream)):
payload = chat.RequestPayload(messages=[{"role": "user", "content": "hi"}], stream=True)
chunks = [jsonable_encoder(c) async for c in AnthropicProvider(config).chat_stream(payload)]
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 ""
print(merged)
# {0: {'id': 'toolu_B', 'name': 'get_time', 'arguments': '{"city":"Paris"}{"tz":"Asia/Tokyo"}'}}
asyncio.run(main())Stack trace
No exception in the gateway. The client fails later on json.loads of the merged arguments.
Other info / logs
The existing streaming tool-call test only has one tool_use block at index 0, so the hardcoded index and the choice index look the same and the test passes.
Proposed fix: in model_to_chat_streaming, use the content block index as ToolCallDelta.index and always emit choices[0]; in chat_stream, emit the message_delta finish chunk once instead of once per block index. Plus a test with two tool_use blocks and one with text followed by a tool call. Happy to take it if assigned.
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
Source: mlflow/mlflow