diff --git a/packages/genkit-openai/src/genkit_openai/_models/_model.py b/packages/genkit-openai/src/genkit_openai/_models/_model.py index ec00050c..36738e06 100644 --- a/packages/genkit-openai/src/genkit_openai/_models/_model.py +++ b/packages/genkit-openai/src/genkit_openai/_models/_model.py @@ -181,6 +181,29 @@ 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. 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 + if not accumulated: + return 0 + latest = max(accumulated) + if tool_call.id: + 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: """The message of an error object a provider attached to a choice. @@ -708,14 +731,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 4340bc1d..25ccbc75 100644 --- a/packages/genkit-openai/tests/openai_model_test.py +++ b/packages/genkit-openai/tests/openai_model_test.py @@ -1850,3 +1850,79 @@ 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 +@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], interleaved: bool +) -> None: + """A fragment that repeats a call id continues that call.""" + mock_client = MagicMock() + chunks = [ + _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"}'}}], + ), + ] + 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) + + 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] == expected