From ecffa2dcc912ca3275dabd997f44eb6bccd2e873 Mon Sep 17 00:00:00 2001 From: Alex Castillo Date: Wed, 21 Oct 2026 00:53:18 -0400 Subject: [PATCH 1/4] fix(streaming): join tool-call fragments that have no index merge_lists only merged tool-call chunks by their int `index`. Servers that omit it left every argument fragment as its own tool call, and an indexed chunk after an unindexed element raised KeyError. Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 1 + chatlas/_merge.py | 17 +++++++++++++++- tests/test_utils_merge.py | 41 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 58 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6c7c6110..0f39243c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Bug fixes +* Streaming tool calls from OpenAI-compatible servers that omit `index` on each chunk (so far, argument fragments were stored as separate tool calls) are now joined into the call they continue, and a chunk with an `index` after one without no longer raises `KeyError`. * `content_image_url()` with a `data:` URL no longer silently drops the `detail` argument: the setting is now carried by inline image content and forwarded to OpenAI's Responses and Chat Completions APIs (regular image URLs already forwarded it). Other providers continue to ignore `detail`. (#467) * `ChatBedrockAnthropic()` now uses native structured outputs for `data_model` on Claude 4.5 and later, as `ChatAnthropic()` does. Its Bedrock model IDs (`anthropic.claude-...`, `us.anthropic.claude-...`) weren't recognized, so it fell back to forcing a tool call, which Claude Opus 5.5 and Sonnet 5.5 reject with a 400. * A tool written as a generator (see "Progressive results" in the tool-calling docs) now reports each yielded value in `.chat_async()` and `.stream_async()`, as it does in `.chat()`. A synchronous generator tool used to send the generator object itself (``) as its result. An `async def` generator tool now counts as an async tool, so `.chat()` raises the usual "Cannot use async tools in a synchronous chat" error instead of sending `` as the result. diff --git a/chatlas/_merge.py b/chatlas/_merge.py index b5a4976a..49d81e2a 100644 --- a/chatlas/_merge.py +++ b/chatlas/_merge.py @@ -86,7 +86,8 @@ def merge_lists( to_merge = [ i for i, e_left in enumerate(merged) - if e_left["index"] == e["index"] + if isinstance(e_left, dict) + and e_left.get("index") == e["index"] ] if to_merge: # TODO: Remove this once merge_dict is updated with special @@ -98,6 +99,20 @@ def merge_lists( merged[to_merge[0]] = merge_dicts(merged[to_merge[0]], e) else: merged.append(e) + elif merged and _is_tool_call_fragment(e) and _is_tool_call(merged[-1]): + # Some OpenAI-compatible servers omit `index` on streamed tool + # calls; a fragment without an id or name continues the previous call. + merged[-1] = merge_dicts(merged[-1], e) else: merged.append(e) return merged + + +def _is_tool_call(x: Any) -> bool: + return ( + isinstance(x, dict) and "index" not in x and isinstance(x.get("function"), dict) + ) + + +def _is_tool_call_fragment(x: Any) -> bool: + return _is_tool_call(x) and not x.get("id") and not x["function"].get("name") diff --git a/tests/test_utils_merge.py b/tests/test_utils_merge.py index eabe262d..0c29341a 100644 --- a/tests/test_utils_merge.py +++ b/tests/test_utils_merge.py @@ -48,3 +48,44 @@ def test_respects_index_when_merging_lists(): assert merge_dicts( {"a": [{"index": 0, "b": "a"}]}, {"a": [{"index": 1, "b": "b"}]} ) == {"a": [{"index": 0, "b": "a"}, {"index": 1, "b": "b"}]} + + +def _tool_call_chunk(**fields): + return {"tool_calls": [fields]} + + +def test_tool_call_fragments_without_index_are_joined(): + # Some OpenAI-compatible servers omit `index` on streamed tool calls; the + # argument fragments that follow the first chunk carry no id either. + chunks = [ + _tool_call_chunk(id="call_1", function={"name": "f", "arguments": ""}), + _tool_call_chunk(function={"arguments": '{"x":'}), + _tool_call_chunk(function={"arguments": " 1}"}), + ] + merged = merge_dicts({}, *chunks) + assert merged["tool_calls"] == [ + {"id": "call_1", "function": {"name": "f", "arguments": '{"x": 1}'}} + ] + + +def test_tool_calls_without_index_and_different_ids_stay_separate(): + chunks = [ + _tool_call_chunk(id="call_1", function={"name": "f", "arguments": "{}"}), + _tool_call_chunk(id="call_2", function={"name": "g", "arguments": "{}"}), + ] + merged = merge_dicts({}, *chunks) + assert [c["id"] for c in merged["tool_calls"]] == ["call_1", "call_2"] + + +def test_indexed_chunk_after_unindexed_element_does_not_raise(): + merged = merge_dicts( + {"tool_calls": [{"id": "call_1", "function": {"arguments": "{}"}}]}, + _tool_call_chunk(index=0, function={"arguments": ""}), + ) + assert len(merged["tool_calls"]) == 2 + + +def test_tool_call_fragment_with_empty_left_list_is_appended(): + fragment = {"function": {"arguments": "{"}} + merged = merge_dicts({"tool_calls": []}, {"tool_calls": [fragment]}) + assert merged == {"tool_calls": [fragment]} From 521f0aef9e8b0755d4e82896ca8fa45b85aa18b1 Mon Sep 17 00:00:00 2001 From: Carson Date: Mon, 9 Nov 2026 18:21:03 -0600 Subject: [PATCH 2/4] fix(streaming): route anonymous tool-call fragments by argument completeness --- chatlas/_merge.py | 35 ++++++++++++++++++++++++++++++++--- tests/test_utils_merge.py | 21 +++++++++++++++++++++ 2 files changed, 53 insertions(+), 3 deletions(-) diff --git a/chatlas/_merge.py b/chatlas/_merge.py index 49d81e2a..f37d21b8 100644 --- a/chatlas/_merge.py +++ b/chatlas/_merge.py @@ -3,6 +3,7 @@ from __future__ import annotations +import json from typing import Any, Optional @@ -99,10 +100,27 @@ def merge_lists( merged[to_merge[0]] = merge_dicts(merged[to_merge[0]], e) else: merged.append(e) - elif merged and _is_tool_call_fragment(e) and _is_tool_call(merged[-1]): + elif merged and _is_tool_call_fragment(e): # Some OpenAI-compatible servers omit `index` on streamed tool - # calls; a fragment without an id or name continues the previous call. - merged[-1] = merge_dicts(merged[-1], e) + # calls; a fragment without an id or name continues a previous + # call. With several unindexed calls in flight, it belongs to + # the first whose arguments don't parse as complete JSON yet + # (a JSON object has no proper prefix that parses), falling + # back to the most recent call. + target = next( + ( + i + for i, c in enumerate(merged) + if _is_tool_call(c) and not _arguments_complete(c) + ), + None, + ) + if target is None and _is_tool_call(merged[-1]): + target = len(merged) - 1 + if target is None: + merged.append(e) + else: + merged[target] = merge_dicts(merged[target], e) else: merged.append(e) return merged @@ -116,3 +134,14 @@ def _is_tool_call(x: Any) -> bool: def _is_tool_call_fragment(x: Any) -> bool: return _is_tool_call(x) and not x.get("id") and not x["function"].get("name") + + +def _arguments_complete(tool_call: dict[str, Any]) -> bool: + arguments = tool_call.get("function", {}).get("arguments") + if not isinstance(arguments, str): + return True + try: + json.loads(arguments) + except ValueError: + return False + return True diff --git a/tests/test_utils_merge.py b/tests/test_utils_merge.py index 0c29341a..1bc9e4b8 100644 --- a/tests/test_utils_merge.py +++ b/tests/test_utils_merge.py @@ -77,6 +77,27 @@ def test_tool_calls_without_index_and_different_ids_stay_separate(): assert [c["id"] for c in merged["tool_calls"]] == ["call_1", "call_2"] +def test_fragments_route_to_parallel_unindexed_calls_by_completeness(): + # When parallel calls are announced together, an anonymous fragment + # continues the first call whose arguments aren't complete yet; merging + # every fragment into the last call would corrupt its JSON. + chunks = [ + _tool_call_chunk( + id="call_1", function={"name": "f", "arguments": ""} + ), + _tool_call_chunk( + id="call_2", function={"name": "g", "arguments": ""} + ), + _tool_call_chunk(function={"arguments": '{"x":1}'}), + _tool_call_chunk(function={"arguments": '{"y":2}'}), + ] + merged = merge_dicts({}, *chunks) + assert [c["function"]["arguments"] for c in merged["tool_calls"]] == [ + '{"x":1}', + '{"y":2}', + ] + + def test_indexed_chunk_after_unindexed_element_does_not_raise(): merged = merge_dicts( {"tool_calls": [{"id": "call_1", "function": {"arguments": "{}"}}]}, From 9df39cbfa8fbadafd9c253290d1210e043969886 Mon Sep 17 00:00:00 2001 From: Carson Date: Mon, 9 Nov 2026 18:28:29 -0600 Subject: [PATCH 3/4] fix(streaming): broaden anonymous fragment targets to indexed and argument-less calls --- chatlas/_merge.py | 23 +++++++++++++++++------ tests/test_utils_merge.py | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 6 deletions(-) diff --git a/chatlas/_merge.py b/chatlas/_merge.py index f37d21b8..7aef6f84 100644 --- a/chatlas/_merge.py +++ b/chatlas/_merge.py @@ -103,19 +103,21 @@ def merge_lists( elif merged and _is_tool_call_fragment(e): # Some OpenAI-compatible servers omit `index` on streamed tool # calls; a fragment without an id or name continues a previous - # call. With several unindexed calls in flight, it belongs to - # the first whose arguments don't parse as complete JSON yet - # (a JSON object has no proper prefix that parses), falling - # back to the most recent call. + # call. With several calls in flight, it belongs to the first + # whose arguments don't parse as complete JSON yet (a JSON + # object has no proper prefix that parses), falling back to + # the most recent call. Fragments interleaved across parallel + # calls carry no routing signal at all, so that ordering + # can't be recovered by any strategy. target = next( ( i for i, c in enumerate(merged) - if _is_tool_call(c) and not _arguments_complete(c) + if _is_tool_call_target(c) and not _arguments_complete(c) ), None, ) - if target is None and _is_tool_call(merged[-1]): + if target is None and _is_tool_call_target(merged[-1]): target = len(merged) - 1 if target is None: merged.append(e) @@ -136,8 +138,17 @@ def _is_tool_call_fragment(x: Any) -> bool: return _is_tool_call(x) and not x.get("id") and not x["function"].get("name") +def _is_tool_call_target(x: Any) -> bool: + # Unlike `_is_tool_call`, an `index` doesn't disqualify a merge target: + # some servers index only the first chunk of a call + return isinstance(x, dict) and isinstance(x.get("function"), dict) + + def _arguments_complete(tool_call: dict[str, Any]) -> bool: arguments = tool_call.get("function", {}).get("arguments") + if arguments is None: + # Announced with only an id/name; still awaiting its arguments + return False if not isinstance(arguments, str): return True try: diff --git a/tests/test_utils_merge.py b/tests/test_utils_merge.py index 1bc9e4b8..372241e0 100644 --- a/tests/test_utils_merge.py +++ b/tests/test_utils_merge.py @@ -98,6 +98,39 @@ def test_fragments_route_to_parallel_unindexed_calls_by_completeness(): ] +def test_unindexed_fragments_continue_an_indexed_call(): + # Some servers send `index` on the first chunk of a tool call but omit it + # on the argument fragments that follow + chunks = [ + _tool_call_chunk( + index=0, id="call_1", function={"name": "f", "arguments": '{"x":'} + ), + _tool_call_chunk(function={"arguments": " 1}"}), + ] + merged = merge_dicts({}, *chunks) + assert merged["tool_calls"] == [ + { + "index": 0, + "id": "call_1", + "function": {"name": "f", "arguments": '{"x": 1}'}, + } + ] + + +def test_fragments_route_to_calls_announced_without_arguments(): + chunks = [ + _tool_call_chunk(id="call_1", function={"name": "f"}), + _tool_call_chunk(id="call_2", function={"name": "g"}), + _tool_call_chunk(function={"arguments": '{"x":1}'}), + _tool_call_chunk(function={"arguments": '{"y":2}'}), + ] + merged = merge_dicts({}, *chunks) + assert [c["function"]["arguments"] for c in merged["tool_calls"]] == [ + '{"x":1}', + '{"y":2}', + ] + + def test_indexed_chunk_after_unindexed_element_does_not_raise(): merged = merge_dicts( {"tool_calls": [{"id": "call_1", "function": {"arguments": "{}"}}]}, From 0eec326e658141140aba40666477506e155d7256 Mon Sep 17 00:00:00 2001 From: Carson Date: Mon, 9 Nov 2026 18:35:13 -0600 Subject: [PATCH 4/4] fix(streaming): treat empty arguments as complete and skip parsing for a single target --- chatlas/_merge.py | 34 +++++++++++++++++-------------- tests/test_utils_merge.py | 43 +++++++++++++++++++-------------------- 2 files changed, 40 insertions(+), 37 deletions(-) diff --git a/chatlas/_merge.py b/chatlas/_merge.py index 7aef6f84..d356c89e 100644 --- a/chatlas/_merge.py +++ b/chatlas/_merge.py @@ -104,25 +104,25 @@ def merge_lists( # Some OpenAI-compatible servers omit `index` on streamed tool # calls; a fragment without an id or name continues a previous # call. With several calls in flight, it belongs to the first - # whose arguments don't parse as complete JSON yet (a JSON - # object has no proper prefix that parses), falling back to - # the most recent call. Fragments interleaved across parallel + # whose arguments aren't complete yet, falling back to the + # most recent call. Fragments interleaved across parallel # calls carry no routing signal at all, so that ordering # can't be recovered by any strategy. - target = next( - ( - i - for i, c in enumerate(merged) - if _is_tool_call_target(c) and not _arguments_complete(c) - ), - None, - ) - if target is None and _is_tool_call_target(merged[-1]): - target = len(merged) - 1 - if target is None: + targets = [ + i for i, c in enumerate(merged) if _is_tool_call_target(c) + ] + if not targets: merged.append(e) + continue + if len(targets) == 1: + # No routing decision to make; skip the JSON parse + target = targets[0] else: - merged[target] = merge_dicts(merged[target], e) + target = next( + (i for i in targets if not _arguments_complete(merged[i])), + targets[-1], + ) + merged[target] = merge_dicts(merged[target], e) else: merged.append(e) return merged @@ -151,6 +151,10 @@ def _arguments_complete(tool_call: dict[str, Any]) -> bool: return False if not isinstance(arguments, str): return True + if arguments == "": + # An explicitly empty payload is complete (it parses as {} downstream), + # not a call still awaiting its arguments + return True try: json.loads(arguments) except ValueError: diff --git a/tests/test_utils_merge.py b/tests/test_utils_merge.py index 372241e0..b1d9ee8c 100644 --- a/tests/test_utils_merge.py +++ b/tests/test_utils_merge.py @@ -82,14 +82,12 @@ def test_fragments_route_to_parallel_unindexed_calls_by_completeness(): # continues the first call whose arguments aren't complete yet; merging # every fragment into the last call would corrupt its JSON. chunks = [ - _tool_call_chunk( - id="call_1", function={"name": "f", "arguments": ""} - ), - _tool_call_chunk( - id="call_2", function={"name": "g", "arguments": ""} - ), - _tool_call_chunk(function={"arguments": '{"x":1}'}), - _tool_call_chunk(function={"arguments": '{"y":2}'}), + _tool_call_chunk(id="call_1", function={"name": "f"}), + _tool_call_chunk(id="call_2", function={"name": "g"}), + _tool_call_chunk(function={"arguments": '{"x":'}), + _tool_call_chunk(function={"arguments": "1}"}), + _tool_call_chunk(function={"arguments": '{"y":'}), + _tool_call_chunk(function={"arguments": "2}"}), ] merged = merge_dicts({}, *chunks) assert [c["function"]["arguments"] for c in merged["tool_calls"]] == [ @@ -98,6 +96,21 @@ def test_fragments_route_to_parallel_unindexed_calls_by_completeness(): ] +def test_fragment_after_an_empty_arguments_call_routes_to_the_active_call(): + # A call announced with `""` arguments has a complete (empty) payload, so + # fragments from the call that follows it must not merge into it + chunks = [ + _tool_call_chunk(id="call_1", function={"name": "f", "arguments": ""}), + _tool_call_chunk(id="call_2", function={"name": "g", "arguments": '{"x":'}), + _tool_call_chunk(function={"arguments": "1}"}), + ] + merged = merge_dicts({}, *chunks) + assert [c["function"]["arguments"] for c in merged["tool_calls"]] == [ + "", + '{"x":1}', + ] + + def test_unindexed_fragments_continue_an_indexed_call(): # Some servers send `index` on the first chunk of a tool call but omit it # on the argument fragments that follow @@ -117,20 +130,6 @@ def test_unindexed_fragments_continue_an_indexed_call(): ] -def test_fragments_route_to_calls_announced_without_arguments(): - chunks = [ - _tool_call_chunk(id="call_1", function={"name": "f"}), - _tool_call_chunk(id="call_2", function={"name": "g"}), - _tool_call_chunk(function={"arguments": '{"x":1}'}), - _tool_call_chunk(function={"arguments": '{"y":2}'}), - ] - merged = merge_dicts({}, *chunks) - assert [c["function"]["arguments"] for c in merged["tool_calls"]] == [ - '{"x":1}', - '{"y":2}', - ] - - def test_indexed_chunk_after_unindexed_element_does_not_raise(): merged = merge_dicts( {"tool_calls": [{"id": "call_1", "function": {"arguments": "{}"}}]},