From 95ebe111d82b04ca14806db1721138b997ed7835 Mon Sep 17 00:00:00 2001 From: gjija Date: Sun, 8 Nov 2026 23:08:31 +0000 Subject: [PATCH] fix(oci): keep streamed parallel tool calls separate and in order The OCI streaming path keyed each tool call by its "index", falling back to its position in the chunk. OCI tool calls carry no "index" and each chunk holds one call, so every call landed in slot 0: a second call overwrote the first call's id and name and appended its arguments, json.loads failed, and the response held one call with empty args. The calls were also sorted by name instead of kept in arrival order. Group pieces by index when one is sent, else by id. A piece with a name but no id starts a new call, and a piece with neither continues the last call, the same rule ApigeeLlm uses. Calls now keep the order they arrived in, like the non-streaming path. --- .../adk/integrations/oci/_oci_genai_llm.py | 33 ++++++---- .../integrations/oci/test_oci_genai_llm.py | 65 +++++++++++++++++++ 2 files changed, 86 insertions(+), 12 deletions(-) diff --git a/src/google/adk/integrations/oci/_oci_genai_llm.py b/src/google/adk/integrations/oci/_oci_genai_llm.py index 5f2668a81d6..dcc0d826e4b 100644 --- a/src/google/adk/integrations/oci/_oci_genai_llm.py +++ b/src/google/adk/integrations/oci/_oci_genai_llm.py @@ -619,7 +619,7 @@ async def _generate_content_streaming( chunks = await asyncio.to_thread(self._call_oci_stream, llm_request) text_acc: str = "" - tool_acc: dict[int, dict[str, Any]] = {} + tool_acc: dict[int | str, dict[str, Any]] = {} input_tokens: int = 0 output_tokens: int = 0 reasoning_tokens: int = 0 @@ -651,25 +651,34 @@ async def _generate_content_streaming( partial=True, ) - # Tool calls: OCI emits the whole call in one chunk for Gemini, but - # accumulate name/arguments defensively in case other providers split - # them across events. - for tc_idx, tc in enumerate(message.get("toolCalls") or []): - idx = tc.get("index", tc_idx) - if idx not in tool_acc: - tool_acc[idx] = {"id": "", "name": "", "arguments": ""} + # Tool calls: OCI's tool calls carry no "index". Gemini sends each + # whole call in its own chunk; other providers may send the id and name + # first, then argument pieces that carry neither. Group pieces by index + # when one is sent, else by id. A piece with a name but no id starts a + # new call; a piece with neither continues the last call. + for tc in message.get("toolCalls") or []: + if tc.get("index") is not None: + key = tc["index"] + elif tc.get("id"): + key = tc["id"] + elif tc.get("name") or not tool_acc: + key = len(tool_acc) + else: + key = next(reversed(tool_acc)) + if key not in tool_acc: + tool_acc[key] = {"id": "", "name": "", "arguments": ""} if tc.get("id"): - tool_acc[idx]["id"] = tc["id"] + tool_acc[key]["id"] = tc["id"] if tc.get("name"): - tool_acc[idx]["name"] = tc["name"] + tool_acc[key]["name"] = tc["name"] if tc.get("arguments"): - tool_acc[idx]["arguments"] += tc["arguments"] + tool_acc[key]["arguments"] += tc["arguments"] # Build final aggregated response all_parts: list[types.Part] = [] if text_acc: all_parts.append(types.Part.from_text(text=text_acc)) - for tc in sorted(tool_acc.values(), key=lambda x: x.get("name", "")): + for tc in tool_acc.values(): args: dict[str, Any] = {} try: args = json.loads(tc["arguments"]) if tc["arguments"] else {} diff --git a/tests/unittests/integrations/oci/test_oci_genai_llm.py b/tests/unittests/integrations/oci/test_oci_genai_llm.py index f3ca88a5e40..4c163e8e580 100644 --- a/tests/unittests/integrations/oci/test_oci_genai_llm.py +++ b/tests/unittests/integrations/oci/test_oci_genai_llm.py @@ -666,6 +666,71 @@ async def test_streaming_tool_call(oci_llm): assert fc.id == "call_stream_1" +@pytest.mark.asyncio +@pytest.mark.parametrize("call_ids", [("call_1", "call_2"), ("", "")]) +async def test_streaming_parallel_tool_calls_in_separate_chunks( + oci_llm, llm_request, call_ids +): + """Calls sent in separate chunks without an index stay apart, in order.""" + chunks = _make_sse_chunks( + text_tokens=[], + tool_calls=[ + {"id": call_ids[0], "name": "get_weather", "args": {"city": "Paris"}}, + {"id": call_ids[1], "name": "get_time", "args": {"tz": "CET"}}, + ], + ) + + with patch.object(oci_llm, "_call_oci_stream", return_value=chunks): + responses = [ + r + async for r in oci_llm.generate_content_async(llm_request, stream=True) + ] + + final = responses[-1] + assert not final.partial + calls = [p.function_call for p in final.content.parts] + assert [(fc.id, fc.name, fc.args) for fc in calls] == [ + (call_ids[0], "get_weather", {"city": "Paris"}), + (call_ids[1], "get_time", {"tz": "CET"}), + ] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("shape", ["same_index", "same_id", "id_first_only"]) +async def test_streaming_tool_calls_split_across_chunks( + oci_llm, llm_request, shape +): + """Argument pieces are merged into the call they belong to.""" + pieces = [] + for i, (name, head, tail) in enumerate([ + ("get_weather", '{"city": ', '"Paris"}'), + ("get_time", '{"tz": ', '"CET"}'), + ]): + start = {"id": f"call_{i}", "name": name, "arguments": head} + more = {"arguments": tail} + if shape == "same_index": + start["index"] = more["index"] = i + elif shape == "same_id": + more["id"] = start["id"] + pieces += [start, more] + chunks = [ + {"index": 0, "message": {"role": "ASSISTANT", "toolCalls": [piece]}} + for piece in pieces + ] + + with patch.object(oci_llm, "_call_oci_stream", return_value=chunks): + responses = [ + r + async for r in oci_llm.generate_content_async(llm_request, stream=True) + ] + + calls = [p.function_call for p in responses[-1].content.parts] + assert [(fc.id, fc.name, fc.args) for fc in calls] == [ + ("call_0", "get_weather", {"city": "Paris"}), + ("call_1", "get_time", {"tz": "CET"}), + ] + + @pytest.mark.asyncio async def test_streaming_empty_chunks(oci_llm, llm_request): """Empty SSE chunk list yields a single empty final response."""