From 0efa4d2d66cce9a70ff45f4ab8c7c04c0202b701 Mon Sep 17 00:00:00 2001 From: Alex Castillo Date: Wed, 18 Nov 2026 04:10:29 -0400 Subject: [PATCH 1/2] fix(py/openai): keep streamed tool calls apart when the endpoint omits index OpenAI-compatible endpoints such as Gemini omit tool_call.index in streamed fragments, so every call accumulated into slot None and parallel calls were merged into invalid JSON. Choose the slot from the fragment id/name when index is absent. --- .../src/genkit_openai/_models/_model.py | 28 +++++++-- .../genkit-openai/tests/openai_model_test.py | 62 +++++++++++++++++++ 2 files changed, 86 insertions(+), 4 deletions(-) diff --git a/packages/genkit-openai/src/genkit_openai/_models/_model.py b/packages/genkit-openai/src/genkit_openai/_models/_model.py index ec00050c1..c467406e5 100644 --- a/packages/genkit-openai/src/genkit_openai/_models/_model.py +++ b/packages/genkit-openai/src/genkit_openai/_models/_model.py @@ -181,6 +181,25 @@ def _usage_from_completion(usage: CompletionUsage | None) -> GenerationUsage: ) +def _tool_call_key(tool_call: Any, accumulated: dict[int, Any]) -> int: # noqa: ANN401 + """The slot a streamed tool call fragment accumulates into. + + OpenAI sends an ``index`` on every fragment. Some OpenAI-compatible endpoints + (Gemini) omit it: a fragment with a new ``id`` (or, lacking an id, a function name) + then starts a new call, and any other fragment continues the latest one. + """ + if tool_call.index is not None: + return tool_call.index + if not accumulated: + return 0 + latest = max(accumulated) + if tool_call.id: + starts_new_call = tool_call.id != accumulated[latest].id + else: + starts_new_call = bool(tool_call.function and tool_call.function.name) + return latest + 1 if starts_new_call else latest + + def _failure_message(extras: dict[str, Any] | None) -> str | None: """The message of an error object a provider attached to a choice. @@ -708,14 +727,15 @@ async def _generate_stream( if delta.tool_calls: for tool_call in delta.tool_calls: fragment = (tool_call.function.arguments or '') if tool_call.function else '' + key = _tool_call_key(tool_call, tool_calls) # Accumulate fragmented tool call arguments - if tool_call.index not in tool_calls: - tool_calls[tool_call.index] = tool_call + if key not in tool_calls: + tool_calls[key] = tool_call else: - existing = tool_calls[tool_call.index] + existing = tool_calls[key] if hasattr(existing, 'function') and existing.function and tool_call.function: existing.function.arguments = (existing.function.arguments or '') + fragment - call = tool_calls[tool_call.index] + call = tool_calls[key] if call.function and call.function.name in wrapped: # Fragments are pieces of '{"input": ...}'; sent unwrapped once complete. continue diff --git a/packages/genkit-openai/tests/openai_model_test.py b/packages/genkit-openai/tests/openai_model_test.py index 4340bc1d9..8f7e4e336 100644 --- a/packages/genkit-openai/tests/openai_model_test.py +++ b/packages/genkit-openai/tests/openai_model_test.py @@ -1850,3 +1850,65 @@ def handler(request: httpx.Request) -> httpx.Response: assert chunks == ['Grilled'] assert exc_info.value.status == status assert exc_info.value.__cause__ is drop + + +@pytest.mark.asyncio +async def test__generate_stream_keeps_parallel_tool_calls_apart_without_an_index( + sample_request: ModelRequest, make_chunk: Callable[..., ChatCompletionChunk] +) -> None: + """Endpoints that omit `index` (Gemini) still yield one tool request per call.""" + mock_client = MagicMock() + mock_client.chat.completions.create = _mock_stream([ + _delta_chunk( + make_chunk, + tool_calls=[ + {'id': 'call_a', 'type': 'function', 'function': {'name': 'get_weather', 'arguments': '{"city": '}} + ], + ), + _delta_chunk(make_chunk, tool_calls=[{'function': {'arguments': '"Paris"}'}}]), + _delta_chunk( + make_chunk, + tool_calls=[ + {'id': 'call_b', 'type': 'function', 'function': {'name': 'get_time', 'arguments': '{"tz": "UTC"}'}} + ], + ), + ]) + + model = OpenAIModel(model='gemini-2.5-flash', client=mock_client) + + response = await model._generate_stream(sample_request, lambda chunk: None) + + assert response.message is not None + requests = [p.tool_request for p in response.message.content if p.tool_request is not None] + assert [(r.ref, r.name, r.input) for r in requests] == [ + ('call_a', 'get_weather', {'city': 'Paris'}), + ('call_b', 'get_time', {'tz': 'UTC'}), + ] + + +@pytest.mark.asyncio +async def test__generate_stream_treats_a_repeated_id_without_an_index_as_the_same_call( + sample_request: ModelRequest, make_chunk: Callable[..., ChatCompletionChunk] +) -> None: + """A fragment that repeats the current call's id continues it.""" + mock_client = MagicMock() + mock_client.chat.completions.create = _mock_stream([ + _delta_chunk( + make_chunk, + tool_calls=[ + {'id': 'call_a', 'type': 'function', 'function': {'name': 'get_weather', 'arguments': '{"city": '}} + ], + ), + _delta_chunk( + make_chunk, + tool_calls=[{'id': 'call_a', 'type': 'function', 'function': {'arguments': '"Paris"}'}}], + ), + ]) + + model = OpenAIModel(model='gemini-2.5-flash', client=mock_client) + + response = await model._generate_stream(sample_request, lambda chunk: None) + + assert response.message is not None + requests = [p.tool_request for p in response.message.content if p.tool_request is not None] + assert [(r.ref, r.name, r.input) for r in requests] == [('call_a', 'get_weather', {'city': 'Paris'})] From 158434a1e3aab440ea5968256c63fab3cb2e546e Mon Sep 17 00:00:00 2001 From: Alex Date: Sun, 29 Nov 2026 09:11:13 -0400 Subject: [PATCH 2/2] fix(py/openai): reassemble interleaved tool calls without an index --- .../src/genkit_openai/_models/_model.py | 16 ++++++++----- .../genkit-openai/tests/openai_model_test.py | 24 +++++++++++++++---- 2 files changed, 29 insertions(+), 11 deletions(-) diff --git a/packages/genkit-openai/src/genkit_openai/_models/_model.py b/packages/genkit-openai/src/genkit_openai/_models/_model.py index c467406e5..36738e066 100644 --- a/packages/genkit-openai/src/genkit_openai/_models/_model.py +++ b/packages/genkit-openai/src/genkit_openai/_models/_model.py @@ -185,8 +185,9 @@ def _tool_call_key(tool_call: Any, accumulated: dict[int, Any]) -> int: # noqa: """The slot a streamed tool call fragment accumulates into. OpenAI sends an ``index`` on every fragment. Some OpenAI-compatible endpoints - (Gemini) omit it: a fragment with a new ``id`` (or, lacking an id, a function name) - then starts a new call, and any other fragment continues the latest one. + (Gemini) omit it. Match fragments with an id to their existing slot or + start a new call. Without an id, a function name starts a new call and + other fragments continue the latest one. """ if tool_call.index is not None: return tool_call.index @@ -194,10 +195,13 @@ def _tool_call_key(tool_call: Any, accumulated: dict[int, Any]) -> int: # noqa: return 0 latest = max(accumulated) if tool_call.id: - starts_new_call = tool_call.id != accumulated[latest].id - else: - starts_new_call = bool(tool_call.function and tool_call.function.name) - return latest + 1 if starts_new_call else latest + for key, call in accumulated.items(): + if call.id == tool_call.id: + return key + return latest + 1 + if tool_call.function and tool_call.function.name: + return latest + 1 + return latest def _failure_message(extras: dict[str, Any] | None) -> str | None: diff --git a/packages/genkit-openai/tests/openai_model_test.py b/packages/genkit-openai/tests/openai_model_test.py index 8f7e4e336..25ccbc75e 100644 --- a/packages/genkit-openai/tests/openai_model_test.py +++ b/packages/genkit-openai/tests/openai_model_test.py @@ -1887,12 +1887,13 @@ async def test__generate_stream_keeps_parallel_tool_calls_apart_without_an_index @pytest.mark.asyncio +@pytest.mark.parametrize('interleaved', [False, True], ids=['consecutive', 'interleaved']) async def test__generate_stream_treats_a_repeated_id_without_an_index_as_the_same_call( - sample_request: ModelRequest, make_chunk: Callable[..., ChatCompletionChunk] + sample_request: ModelRequest, make_chunk: Callable[..., ChatCompletionChunk], interleaved: bool ) -> None: - """A fragment that repeats the current call's id continues it.""" + """A fragment that repeats a call id continues that call.""" mock_client = MagicMock() - mock_client.chat.completions.create = _mock_stream([ + chunks = [ _delta_chunk( make_chunk, tool_calls=[ @@ -1903,7 +1904,20 @@ async def test__generate_stream_treats_a_repeated_id_without_an_index_as_the_sam make_chunk, tool_calls=[{'id': 'call_a', 'type': 'function', 'function': {'arguments': '"Paris"}'}}], ), - ]) + ] + expected = [('call_a', 'get_weather', {'city': 'Paris'})] + if interleaved: + chunks.insert( + 1, + _delta_chunk( + make_chunk, + tool_calls=[ + {'id': 'call_b', 'type': 'function', 'function': {'name': 'get_time', 'arguments': '{"tz": "UTC"}'}} + ], + ), + ) + expected.append(('call_b', 'get_time', {'tz': 'UTC'})) + mock_client.chat.completions.create = _mock_stream(chunks) model = OpenAIModel(model='gemini-2.5-flash', client=mock_client) @@ -1911,4 +1925,4 @@ async def test__generate_stream_treats_a_repeated_id_without_an_index_as_the_sam assert response.message is not None requests = [p.tool_request for p in response.message.content if p.tool_request is not None] - assert [(r.ref, r.name, r.input) for r in requests] == [('call_a', 'get_weather', {'city': 'Paris'})] + assert [(r.ref, r.name, r.input) for r in requests] == expected