Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 21 additions & 12 deletions src/google/adk/integrations/oci/_oci_genai_llm.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 {}
Expand Down
65 changes: 65 additions & 0 deletions tests/unittests/integrations/oci/test_oci_genai_llm.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down
Loading