diff --git a/CHANGELOG.md b/CHANGELOG.md index 52062f31..d00a4b3b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -36,6 +36,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 * `ChatGoogle()` now reports `finish_reason == "content_filter"` for Gemini's `IMAGE_SAFETY`, `IMAGE_PROHIBITED_CONTENT`, `IMAGE_RECITATION` and `LANGUAGE` finish reasons, instead of passing the raw Gemini string through, and reports `"tool_use"` (rather than `"success"`) when a turn ends with a tool request, as `ChatOpenAI()` does. (#473) * The error raised for a tool request with invalid JSON arguments from `ChatOpenAI()` and `ChatOpenAICompletions()` (and the providers built on them) now shows the offending arguments, instead of the literal text `{args}`. * When streaming with server tools such as web search, `ChatAnthropic()` (and `ChatBedrockAnthropic()`) no longer under-reports the turn's token usage and cost. Streamed turns previously kept the input and cache token counts from the start of the response, missing tokens consumed mid-turn (e.g. cache writes made while searching); they now report the same totals as the equivalent non-streamed request. (#466) +* 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) * `ChatBedrock()` on a Converse model no longer drops redacted reasoning blocks when streaming. They were discarded as they arrived, so a streamed turn lost them, while a non-streamed one kept them. (#468) * `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. diff --git a/chatlas/_merge.py b/chatlas/_merge.py index b5a4976a..d356c89e 100644 --- a/chatlas/_merge.py +++ b/chatlas/_merge.py @@ -3,6 +3,7 @@ from __future__ import annotations +import json from typing import Any, Optional @@ -86,7 +87,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 +100,63 @@ 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): + # 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 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. + 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: + 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 + + +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") + + +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 + 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: + return False + return True diff --git a/tests/test_utils_merge.py b/tests/test_utils_merge.py index eabe262d..b1d9ee8c 100644 --- a/tests/test_utils_merge.py +++ b/tests/test_utils_merge.py @@ -48,3 +48,97 @@ 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_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"}), + _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"]] == [ + '{"x":1}', + '{"y":2}', + ] + + +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 + 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_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]}