Skip to content

Same agent Smaller bill. The tools and infrastructure to get more work from your AI. Fewer tokens. Less compute. Lower cost.

fix: track parallel Anthropic tool_use blocks by index instead of scalars (#1399)

Amir Fathi7119aacde396
diff --git a/sdk/python/src/openlit/instrumentation/anthropic/anthropic.py b/sdk/python/src/openlit/instrumentation/anthropic/anthropic.py
index 842d0bc5..6a4643c9 100644
--- a/sdk/python/src/openlit/instrumentation/anthropic/anthropic.py
+++ b/sdk/python/src/openlit/instrumentation/anthropic/anthropic.py
@@ -61,9 +61,7 @@ def messages(
self._output_tokens = 0
self._cache_read_input_tokens = 0
self._cache_creation_input_tokens = 0
- self._tool_arguments = ""
- self._tool_id = ""
- self._tool_name = ""
+ self._tool_calls_by_index = {}
self._tool_calls = None
self._response_role = ""
self._kwargs = kwargs
@@ -246,9 +244,7 @@ def messages_stream(
self._output_tokens = 0
self._cache_read_input_tokens = 0
self._cache_creation_input_tokens = 0
- self._tool_arguments = ""
- self._tool_id = ""
- self._tool_name = ""
+ self._tool_calls_by_index = {}
self._tool_calls = None
self._response_role = ""
self._kwargs = kwargs
diff --git a/sdk/python/src/openlit/instrumentation/anthropic/async_anthropic.py b/sdk/python/src/openlit/instrumentation/anthropic/async_anthropic.py
index 96c46014..c7bf7257 100644
--- a/sdk/python/src/openlit/instrumentation/anthropic/async_anthropic.py
+++ b/sdk/python/src/openlit/instrumentation/anthropic/async_anthropic.py
@@ -62,9 +62,7 @@ def async_messages(
self._output_tokens = 0
self._cache_read_input_tokens = 0
self._cache_creation_input_tokens = 0
- self._tool_arguments = ""
- self._tool_id = ""
- self._tool_name = ""
+ self._tool_calls_by_index = {}
self._tool_calls = None
self._response_role = ""
self._kwargs = kwargs
@@ -248,9 +246,7 @@ def async_messages_stream(
self._output_tokens = 0
self._cache_read_input_tokens = 0
self._cache_creation_input_tokens = 0
- self._tool_arguments = ""
- self._tool_id = ""
- self._tool_name = ""
+ self._tool_calls_by_index = {}
self._tool_calls = None
self._response_role = ""
self._kwargs = kwargs
diff --git a/sdk/python/src/openlit/instrumentation/anthropic/utils.py b/sdk/python/src/openlit/instrumentation/anthropic/utils.py
index ebb0a66d..7918f30e 100644
--- a/sdk/python/src/openlit/instrumentation/anthropic/utils.py
+++ b/sdk/python/src/openlit/instrumentation/anthropic/utils.py
@@ -192,15 +192,57 @@ def build_input_messages(messages, system=None):
return otel_messages
+def _normalize_tool_arguments(tool_args):
+ """
+ Normalize tool-call arguments to an object for gen_ai.*.messages parts.
+
+ OTel GenAI expects tool_call.arguments to be an object. Streaming Anthropic
+ accumulates partial_json as a string; deserialize when possible.
+ See: https://github.com/open-telemetry/semantic-conventions-genai
+ """
+ if isinstance(tool_args, str):
+ try:
+ return json.loads(tool_args) if tool_args else {}
+ except Exception:
+ return {"raw": tool_args}
+ if tool_args is None:
+ return {}
+ return tool_args
+
+
+def _format_tool_args_for_span(tool_args):
+ """Serialize one tool-call's arguments for flat span attributes."""
+ if isinstance(tool_args, str):
+ return tool_args
+ try:
+ return json.dumps(tool_args)
+ except (TypeError, ValueError):
+ return str(tool_args)
+
+
+def _join_tool_field(values):
+ """
+ Join one field across parallel tool calls, keeping positions aligned.
+
+ Every call contributes a slot, so the nth entry of gen_ai.tool.name,
+ gen_ai.tool.call.id, and gen_ai.tool.args always describes the same call
+ even when one field is empty. Filtering each field independently would
+ shift the columns out of step. A field that is empty for every call
+ collapses to "" rather than a run of separators.
+ """
+ values = [str(value) if value else "" for value in values]
+ return ", ".join(values) if any(values) else ""
+
+
def build_output_messages(response_text, finish_reason, tool_calls=None):
"""
Convert Anthropic response to OTel output message structure.
- Follows gen-ai-output-messages schema.
+ Follows gen-ai-output-messages schema (ToolCallRequestPart per tool_use).
Args:
response_text: Response text from model
finish_reason: Finish reason from Anthropic (end_turn, max_tokens, stop_sequence, tool_use)
- tool_calls: Optional tool calls dict from response
+ tool_calls: Optional list of tool calls from response (or a single dict)
Returns:
List with single OutputMessage
@@ -212,16 +254,23 @@ def build_output_messages(response_text, finish_reason, tool_calls=None):
if response_text:
parts.append({"type": "text", "content": response_text})
- # Add tool call if present
+ # Parallel tool_use blocks each become a tool_call part with object
+ # arguments (OTel ToolCallRequestPart).
if tool_calls:
- parts.append(
- {
- "type": "tool_call",
- "id": tool_calls.get("id", ""),
- "name": tool_calls.get("name", ""),
- "arguments": tool_calls.get("input", {}),
- }
- )
+ calls = tool_calls if isinstance(tool_calls, list) else [tool_calls]
+ for tool_call in calls:
+ if not isinstance(tool_call, dict) or not tool_call:
+ continue
+ parts.append(
+ {
+ "type": "tool_call",
+ "id": tool_call.get("id", ""),
+ "name": tool_call.get("name", ""),
+ "arguments": _normalize_tool_arguments(
+ tool_call.get("input", {})
+ ),
+ }
+ )
# Map Anthropic finish reasons to OTel standard
finish_reason_map = {
@@ -460,20 +509,33 @@ def process_chunk(scope, chunk):
scope._response_model = message.get("model")
scope._response_role = message.get("role")
+ if not hasattr(scope, "_tool_calls_by_index") or scope._tool_calls_by_index is None:
+ scope._tool_calls_by_index = {}
+
# Collect message IDs and aggregated response from events
if chunked.get("type") == "content_block_delta":
delta = chunked.get("delta") or {}
if delta.get("text"):
scope._llmresponse += delta.get("text", "")
elif delta.get("partial_json"):
- scope._tool_arguments += delta.get("partial_json", "")
+ # Key by content-block index so parallel tool_use JSON stays separate.
+ index = chunked.get("index", 0)
+ slot = scope._tool_calls_by_index.setdefault(
+ index, {"id": "", "name": "", "input": ""}
+ )
+ slot["input"] += delta.get("partial_json", "")
if chunked.get("type") == "content_block_start":
content_block = chunked.get("content_block") or {}
- if content_block.get("id"):
- scope._tool_id = content_block.get("id")
- if content_block.get("name"):
- scope._tool_name = content_block.get("name")
+ if content_block.get("type") == "tool_use":
+ index = chunked.get("index", 0)
+ slot = scope._tool_calls_by_index.setdefault(
+ index, {"id": "", "name": "", "input": ""}
+ )
+ slot["id"] = content_block.get("id", "") or slot.get("id", "")
+ slot["name"] = content_block.get("name", "") or slot.get("name", "")
+ if "input" not in slot or slot["input"] is None:
+ slot["input"] = ""
# Collect output tokens and stop reason from events (message_delta: top-level usage, delta)
if chunked.get("type") == "message_delta":
@@ -581,15 +643,45 @@ def common_chat_logic(
"text" if isinstance(scope._llmresponse, str) else "json",
)
- # Span Attributes for Tools
+ # Flat tool attrs on chat spans are OpenLIT house style (comma-joined,
+ # matching openai/utils.py). The OTel-canonical parallel representation is
+ # gen_ai.output.messages with one tool_call part per call (built below).
+ # gen_ai.tool.name / gen_ai.tool.call.id are OTel attribute names; args also
+ # set gen_ai.tool.call.arguments (OTel) alongside legacy gen_ai.tool.args.
if hasattr(scope, "_tool_calls") and scope._tool_calls:
- tool_name = scope._tool_calls.get("name", "")
- tool_id = scope._tool_calls.get("id", "")
- tool_args = scope._tool_calls.get("input", "")
+ calls = (
+ scope._tool_calls
+ if isinstance(scope._tool_calls, list)
+ else [scope._tool_calls]
+ )
+ calls = [c for c in calls if isinstance(c, dict) and c]
+ names = [c.get("name", "") or "" for c in calls]
+ ids = [c.get("id", "") or "" for c in calls]
+ args = [_format_tool_args_for_span(c.get("input", "")) for c in calls]
- scope._span.set_attribute(SemanticConvention.GEN_AI_TOOL_NAME, tool_name)
- scope._span.set_attribute(SemanticConvention.GEN_AI_TOOL_CALL_ID, tool_id)
- scope._span.set_attribute(SemanticConvention.GEN_AI_TOOL_ARGS, str(tool_args))
+ scope._span.set_attribute(
+ SemanticConvention.GEN_AI_TOOL_NAME,
+ _join_tool_field(names),
+ )
+ scope._span.set_attribute(
+ SemanticConvention.GEN_AI_TOOL_CALL_ID,
+ _join_tool_field(ids),
+ )
+ joined_args = _join_tool_field(args)
+ scope._span.set_attribute(SemanticConvention.GEN_AI_TOOL_ARGS, joined_args)
+ # OTel GenAI attribute for tool-call parameters (JSON string on spans).
+ if len(calls) == 1:
+ scope._span.set_attribute(
+ SemanticConvention.GEN_AI_TOOL_CALL_ARGUMENTS,
+ args[0] if args else "{}",
+ )
+ elif calls:
+ scope._span.set_attribute(
+ SemanticConvention.GEN_AI_TOOL_CALL_ARGUMENTS,
+ json.dumps(
+ [_normalize_tool_arguments(c.get("input", {})) for c in calls]
+ ),
+ )
# Span Attributes for Cost and Tokens
scope._span.set_attribute(
@@ -744,12 +836,13 @@ def process_streaming_chat_response(
Process streaming chat response and generate telemetry.
"""
- if scope._tool_id != "":
- scope._tool_calls = {
- "id": scope._tool_id,
- "name": scope._tool_name,
- "input": scope._tool_arguments,
- }
+ if scope._tool_calls_by_index:
+ scope._tool_calls = [
+ scope._tool_calls_by_index[index]
+ for index in sorted(scope._tool_calls_by_index)
+ if scope._tool_calls_by_index[index].get("id")
+ or scope._tool_calls_by_index[index].get("name")
+ ] or None
common_chat_logic(
scope,
@@ -793,7 +886,6 @@ def process_chat_response(
scope._start_time = start_time
scope._end_time = time.time()
scope._span = span
- scope._llmresponse = response_dict.get("content", [{}])[0].get("text", "")
scope._response_role = response_dict.get("role", "assistant")
# Handle token usage including reasoning tokens and cached tokens
@@ -811,17 +903,22 @@ def process_chat_response(
scope._server_address, scope._server_port = server_address, server_port
scope._kwargs = kwargs
- # Handle tool calls if present
- content_blocks = response_dict.get("content", [])
- scope._tool_calls = None
- for block in content_blocks:
- if block.get("type") == "tool_use":
- scope._tool_calls = {
- "id": block.get("id", ""),
- "name": block.get("name", ""),
- "input": block.get("input", ""),
- }
- break
+ # Collect text and every parallel tool_use block for OTel output messages.
+ content_blocks = response_dict.get("content", []) or []
+ scope._llmresponse = "".join(
+ block.get("text", "")
+ for block in content_blocks
+ if isinstance(block, dict) and block.get("type") == "text" and block.get("text")
+ )
+ scope._tool_calls = [
+ {
+ "id": block.get("id", ""),
+ "name": block.get("name", ""),
+ "input": block.get("input", {}),
+ }
+ for block in content_blocks
+ if isinstance(block, dict) and block.get("type") == "tool_use"
+ ] or None
common_chat_logic(
scope,
diff --git a/sdk/python/tests/test_anthropic_parallel_tool_calls.py b/sdk/python/tests/test_anthropic_parallel_tool_calls.py
new file mode 100644
index 00000000..791d8fa7
--- /dev/null
+++ b/sdk/python/tests/test_anthropic_parallel_tool_calls.py
@@ -0,0 +1,381 @@
+# pylint: disable=protected-access
+"""
+Regression tests: parallel `tool_use` blocks in an Anthropic turn must not
+corrupt the span.
+
+Before the fix, `process_chunk`/`process_chat_response` in
+`openlit.instrumentation.anthropic.utils` tracked at most one tool call:
+streaming kept `_tool_id`/`_tool_name` as scalars (overwritten by every
+`content_block_start`) and appended every block's `partial_json` delta into
+one `_tool_arguments` string (concatenating two calls' JSON into one invalid
+string), while the non-streaming path `break`-ed after the first `tool_use`
+block. A turn with two parallel tool calls therefore reported a single
+corrupted or truncated tool call. These tests drive the real
+`process_chunk`/`process_streaming_chat_response`/`process_chat_response`
+functions (the same ones the `anthropic.py` wrapper classes call) with
+synthetic API payloads carrying two parallel tool calls, and assert both
+survive intact.
+
+OTel GenAI expects parallel tool calls in `gen_ai.output.messages` as separate
+`tool_call` parts with object `arguments`
+(https://github.com/open-telemetry/semantic-conventions-genai). Flat
+`gen_ai.tool.*` attrs follow the OpenAI instrumentor's comma-join house style.
+"""
+
+import json
+import time
+from types import SimpleNamespace
+
+from opentelemetry.sdk.trace import TracerProvider
+from opentelemetry.sdk.trace.export import SimpleSpanProcessor
+from opentelemetry.sdk.trace.export.in_memory_span_exporter import (
+ InMemorySpanExporter,
+)
+
+from openlit._config import OpenlitConfig
+from openlit.instrumentation.anthropic import utils as anthropic_utils
+from openlit.semcov import SemanticConvention
+
+REQUEST_KWARGS = {
+ "model": "claude-3-5-sonnet-latest",
+ "messages": [{"role": "user", "content": "weather in nyc and sf?"}],
+}
+
+STREAM_CHUNKS = [
+ {
+ "type": "message_start",
+ "message": {
+ "id": "msg_01",
+ "model": "claude-3-5-sonnet-latest",
+ "role": "assistant",
+ "usage": {"input_tokens": 10},
+ },
+ },
+ {
+ "type": "content_block_start",
+ "index": 0,
+ "content_block": {"type": "tool_use", "id": "toolu_01", "name": "get_weather"},
+ },
+ {
+ "type": "content_block_delta",
+ "index": 0,
+ "delta": {"type": "input_json_delta", "partial_json": '{"city": '},
+ },
+ {
+ "type": "content_block_delta",
+ "index": 0,
+ "delta": {"type": "input_json_delta", "partial_json": '"nyc"}'},
+ },
+ {"type": "content_block_stop", "index": 0},
+ {
+ "type": "content_block_start",
+ "index": 1,
+ "content_block": {"type": "tool_use", "id": "toolu_02", "name": "get_weather"},
+ },
+ {
+ "type": "content_block_delta",
+ "index": 1,
+ "delta": {"type": "input_json_delta", "partial_json": '{"city": "sf"}'},
+ },
+ {"type": "content_block_stop", "index": 1},
+ {
+ "type": "message_delta",
+ "delta": {"stop_reason": "tool_use"},
+ "usage": {"output_tokens": 20},
+ },
+ {"type": "message_stop"},
+]
+
+STREAM_CHUNKS_WITH_TEXT = [
+ {
+ "type": "message_start",
+ "message": {
+ "id": "msg_03",
+ "model": "claude-3-5-sonnet-latest",
+ "role": "assistant",
+ "usage": {"input_tokens": 10},
+ },
+ },
+ {
+ "type": "content_block_start",
+ "index": 0,
+ "content_block": {"type": "text", "text": ""},
+ },
+ {
+ "type": "content_block_delta",
+ "index": 0,
+ "delta": {"type": "text_delta", "text": "checking both"},
+ },
+ {"type": "content_block_stop", "index": 0},
+ {
+ "type": "content_block_start",
+ "index": 1,
+ "content_block": {"type": "tool_use", "id": "toolu_21", "name": "get_weather"},
+ },
+ {
+ "type": "content_block_delta",
+ "index": 1,
+ "delta": {"type": "input_json_delta", "partial_json": '{"city": "nyc"}'},
+ },
+ {"type": "content_block_stop", "index": 1},
+ {
+ "type": "message_delta",
+ "delta": {"stop_reason": "tool_use"},
+ "usage": {"output_tokens": 15},
+ },
+ {"type": "message_stop"},
+]
+
+NON_STREAM_RESPONSE = {
+ "id": "msg_02",
+ "model": "claude-3-5-sonnet-latest",
+ "role": "assistant",
+ "stop_reason": "tool_use",
+ "usage": {"input_tokens": 10, "output_tokens": 20},
+ "content": [
+ {"type": "text", "text": "checking both"},
+ {
+ "type": "tool_use",
+ "id": "toolu_11",
+ "name": "get_weather",
+ "input": {"city": "nyc"},
+ },
+ {
+ "type": "tool_use",
+ "id": "toolu_12",
+ "name": "get_weather",
+ "input": {"city": "sf"},
+ },
+ ],
+}
+
+
+def _tracer_with_exporter():
+ OpenlitConfig.reset_to_defaults()
+ exporter = InMemorySpanExporter()
+ provider = TracerProvider()
+ provider.add_span_processor(SimpleSpanProcessor(exporter))
+ return provider.get_tracer(__name__), exporter
+
+
+def _stream_scope(span):
+ """Mirrors TracedSyncStream.__init__'s scope state in anthropic.py."""
+ return SimpleNamespace(
+ _span=span,
+ _llmresponse="",
+ _response_id="",
+ _response_model="",
+ _finish_reason="",
+ _input_tokens=0,
+ _output_tokens=0,
+ _cache_read_input_tokens=0,
+ _cache_creation_input_tokens=0,
+ _tool_calls_by_index={},
+ _tool_calls=None,
+ _response_role="",
+ _kwargs=REQUEST_KWARGS,
+ _start_time=time.time(),
+ _end_time=None,
+ _timestamps=[],
+ _ttft=0,
+ _tbt=0,
+ _server_address="api.anthropic.com",
+ _server_port=443,
+ )
+
+
+def _run_stream(chunks):
+ tracer, exporter = _tracer_with_exporter()
+ with tracer.start_as_current_span("anthropic.chat") as span:
+ scope = _stream_scope(span)
+ for chunk in chunks:
+ anthropic_utils.process_chunk(scope, chunk)
+ anthropic_utils.process_streaming_chat_response(
+ scope,
+ pricing_info={},
+ environment="test",
+ application_name="test",
+ metrics=None,
+ capture_message_content=True,
+ disable_metrics=True,
+ version="1.0.0",
+ )
+ return exporter.get_finished_spans()[0]
+
+
+def _run_non_stream(response):
+ tracer, exporter = _tracer_with_exporter()
+ with tracer.start_as_current_span("anthropic.chat") as span:
+ anthropic_utils.process_chat_response(
+ response=response,
+ request_model="claude-3-5-sonnet-latest",
+ pricing_info={},
+ server_port=443,
+ server_address="api.anthropic.com",
+ environment="test",
+ application_name="test",
+ metrics=None,
+ start_time=time.time(),
+ span=span,
+ capture_message_content=True,
+ disable_metrics=True,
+ **REQUEST_KWARGS,
+ )
+ return exporter.get_finished_spans()[0]
+
+
+def _tool_call_parts(attrs):
+ output_messages = json.loads(attrs[SemanticConvention.GEN_AI_OUTPUT_MESSAGES])
+ return [p for p in output_messages[0]["parts"] if p["type"] == "tool_call"]
+
+
+def test_streaming_parallel_tool_calls_are_not_corrupted():
+ """Two parallel tool_use blocks in a stream must both survive, uncorrupted."""
+ attrs = _run_stream(STREAM_CHUNKS).attributes
+
+ # Flat attrs join all parallel calls (OpenAI instrumentor house style).
+ assert attrs[SemanticConvention.GEN_AI_TOOL_CALL_ID] == "toolu_01, toolu_02"
+ assert attrs[SemanticConvention.GEN_AI_TOOL_NAME] == "get_weather, get_weather"
+ assert attrs[SemanticConvention.GEN_AI_TOOL_ARGS] == (
+ '{"city": "nyc"}, {"city": "sf"}'
+ )
+ assert json.loads(attrs[SemanticConvention.GEN_AI_TOOL_CALL_ARGUMENTS]) == [
+ {"city": "nyc"},
+ {"city": "sf"},
+ ]
+
+ # OTel output messages: one tool_call part per call, arguments as objects.
+ tool_call_parts = _tool_call_parts(attrs)
+ assert len(tool_call_parts) == 2
+ assert tool_call_parts[0]["id"] == "toolu_01"
+ assert tool_call_parts[0]["arguments"] == {"city": "nyc"}
+ assert tool_call_parts[1]["id"] == "toolu_02"
+ assert tool_call_parts[1]["arguments"] == {"city": "sf"}
+
+ output = json.loads(attrs[SemanticConvention.GEN_AI_OUTPUT_MESSAGES])
+ assert output[0]["finish_reason"] == "tool_call"
+
+
+def test_streaming_text_block_does_not_create_tool_calls():
+ """Text content blocks must not pollute the tool-call index map."""
+ attrs = _run_stream(STREAM_CHUNKS_WITH_TEXT).attributes
+
+ output = json.loads(attrs[SemanticConvention.GEN_AI_OUTPUT_MESSAGES])
+ parts = output[0]["parts"]
+ assert parts[0] == {"type": "text", "content": "checking both"}
+ assert [p["id"] for p in parts if p["type"] == "tool_call"] == ["toolu_21"]
+ assert attrs[SemanticConvention.GEN_AI_TOOL_CALL_ID] == "toolu_21"
+
+
+def test_non_streaming_parallel_tool_calls_are_not_dropped():
+ """Two parallel tool_use blocks in a response must both be captured."""
+ attrs = _run_non_stream(NON_STREAM_RESPONSE).attributes
+
+ assert attrs[SemanticConvention.GEN_AI_TOOL_CALL_ID] == "toolu_11, toolu_12"
+ assert attrs[SemanticConvention.GEN_AI_TOOL_NAME] == "get_weather, get_weather"
+ assert attrs[SemanticConvention.GEN_AI_TOOL_ARGS] == (
+ '{"city": "nyc"}, {"city": "sf"}'
+ )
+ assert json.loads(attrs[SemanticConvention.GEN_AI_TOOL_CALL_ARGUMENTS]) == [
+ {"city": "nyc"},
+ {"city": "sf"},
+ ]
+
+ tool_call_parts = _tool_call_parts(attrs)
+ assert len(tool_call_parts) == 2
+ assert [p["id"] for p in tool_call_parts] == ["toolu_11", "toolu_12"]
+ assert tool_call_parts[0]["arguments"] == {"city": "nyc"}
+ assert tool_call_parts[1]["arguments"] == {"city": "sf"}
+
+ output = json.loads(attrs[SemanticConvention.GEN_AI_OUTPUT_MESSAGES])
+ assert output[0]["parts"][0] == {"type": "text", "content": "checking both"}
+ assert output[0]["finish_reason"] == "tool_call"
+
+
+def test_non_streaming_single_tool_call_attributes_are_unchanged_shape():
+ """One tool call must keep a single (non-joined) flat attribute value."""
+ response = {
+ **NON_STREAM_RESPONSE,
+ "content": [
+ {
+ "type": "tool_use",
+ "id": "toolu_01",
+ "name": "get_weather",
+ "input": {"city": "nyc"},
+ }
+ ],
+ }
+ attrs = _run_non_stream(response).attributes
+
+ assert attrs[SemanticConvention.GEN_AI_TOOL_CALL_ID] == "toolu_01"
+ assert attrs[SemanticConvention.GEN_AI_TOOL_NAME] == "get_weather"
+ assert attrs[SemanticConvention.GEN_AI_TOOL_ARGS] == '{"city": "nyc"}'
+ assert attrs[SemanticConvention.GEN_AI_TOOL_CALL_ARGUMENTS] == '{"city": "nyc"}'
+
+
+def test_build_output_messages_parses_streamed_json_strings():
+ """Streamed argument strings become objects in OTel tool_call parts."""
+ parts = anthropic_utils.build_output_messages(
+ "",
+ "tool_use",
+ [{"id": "t1", "name": "f", "input": '{"a": 1}'}],
+ )[0]["parts"]
+
+ assert parts[0]["arguments"] == {"a": 1}
+
+
+def test_build_output_messages_accepts_legacy_single_dict():
+ """A single tool-call dict (pre-list shape) must still emit one tool_call part."""
+ parts = anthropic_utils.build_output_messages(
+ "hi", "tool_use", {"id": "t1", "name": "n", "input": {"a": 1}}
+ )[0]["parts"]
+
+ assert [p["type"] for p in parts] == ["text", "tool_call"]
+ assert parts[1]["id"] == "t1"
+
+
+def test_build_output_messages_skips_empty_entries():
+ """Empty or None entries in a tool_calls list must not become tool_call parts."""
+ parts = anthropic_utils.build_output_messages(
+ "", "tool_use", [{}, {"id": "t1", "name": "n", "input": {}}, None]
+ )[0]["parts"]
+
+ assert len(parts) == 1
+ assert parts[0]["id"] == "t1"
+
+
+def test_join_tool_field_keeps_columns_aligned():
+ """Empty slots must still occupy a position so name/id/args columns stay aligned."""
+ assert anthropic_utils._join_tool_field(["a", "", "c"]) == "a, , c"
+ assert anthropic_utils._join_tool_field(["", ""]) == ""
+ assert anthropic_utils._join_tool_field([]) == ""
+
+
+def test_streaming_accumulates_split_argument_deltas():
+ """Direct accumulator check: one tool_use split across many partial_json deltas."""
+ scope = SimpleNamespace(
+ _timestamps=[],
+ _start_time=0,
+ _llmresponse="",
+ _tool_calls_by_index={},
+ )
+ for chunk in [
+ {
+ "type": "content_block_start",
+ "index": 0,
+ "content_block": {"type": "tool_use", "id": "t1", "name": "f"},
+ },
+ {
+ "type": "content_block_delta",
+ "index": 0,
+ "delta": {"partial_json": '{"a"'},
+ },
+ {
+ "type": "content_block_delta",
+ "index": 0,
+ "delta": {"partial_json": ": 1}"},
+ },
+ ]:
+ anthropic_utils.process_chunk(scope, chunk)
+
+ assert json.loads(scope._tool_calls_by_index[0]["input"]) == {"a": 1}