π Bug Report: Bedrock invoke_model_with_response_stream records streamed tool-call arguments as {} (input_json_delta appended to the dict placeholder, error swallowed)
Which component is this bug for?
Bedrock Instrumentation
π Description
For Anthropic models on invoke_model_with_response_stream, a streamed tool call is recorded in gen_ai.output.messages with empty arguments {}, although the application received the full arguments. The same tool call via invoke_model is recorded correctly.
Cause, in StreamingWrapper._process_event (streaming_wrapper.py):
content_block_startappends the content block as sent by Bedrock, which for a tool call is{"type": "tool_use", ..., "input": {}};inputis a dict.- For each
input_json_delta, the code does:
current.setdefault("input", "")
current["input"] += partial_json
setdefault does not replace the existing {}, so this is dict += str β TypeError.
_process_eventis decorated with@dont_throw, so the error is swallowed on every fragment and the placeholder{}remains as the final tool arguments.
The trace therefore looks complete (tool name, id, finish reason tool_call) but the arguments are silently lost.
π Reproduction steps
Self-contained: a botocore before-send hook answers the requests with real AWS event-stream framing (no AWS account or network needed). The same tool call is returned once by invoke_model and once by invoke_model_with_response_stream.
import base64, json, logging, os, struct, zlib
logging.disable(logging.WARNING)
os.environ["TRACELOOP_TRACE_CONTENT"] = "true"
import boto3
from botocore.awsrequest import AWSResponse
from botocore.config import Config
from opentelemetry.sdk.trace import SpanProcessor, TracerProvider
from opentelemetry.instrumentation.bedrock import BedrockInstrumentor
MODEL = "anthropic.claude-3-haiku-20240307-v1:0"
def frame(event_type, payload):
def h(n, v):
n, v = n.encode(), v.encode()
return struct.pack("B", len(n)) + n + b"\x07" + struct.pack(">H", len(v)) + v
headers = h(":event-type", event_type) + h(":content-type", "application/json") + h(":message-type", "event")
body = json.dumps(payload).encode()
prelude = struct.pack(">II", 12 + len(headers) + len(body) + 4, len(headers))
prelude += struct.pack(">I", zlib.crc32(prelude))
msg = prelude + headers + body
return msg + struct.pack(">I", zlib.crc32(msg))
TOOL_EVENTS = [
{"type": "message_start", "message": {"id": "m", "type": "message", "role": "assistant", "model": "m",
"content": [], "usage": {"input_tokens": 3, "output_tokens": 0}}},
{"type": "content_block_start", "index": 0,
"content_block": {"type": "tool_use", "id": "toolu_1", "name": "get_weather", "input": {}}},
{"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": '"Paris"}'}},
{"type": "content_block_stop", "index": 0},
{"type": "message_delta", "delta": {"stop_reason": "tool_use"}, "usage": {"output_tokens": 5}},
{"type": "message_stop", "amazon-bedrock-invocationMetrics": {"inputTokenCount": 3, "outputTokenCount": 5,
"invocationLatency": 1, "firstByteLatency": 1}},
]
TOOL_MESSAGE = {"id": "m", "type": "message", "role": "assistant", "model": "m", "stop_reason": "tool_use",
"content": [{"type": "tool_use", "id": "toolu_1", "name": "get_weather", "input": {"city": "Paris"}}],
"usage": {"input_tokens": 3, "output_tokens": 5}}
class Raw:
def __init__(self, frames): self.frames = frames
def stream(self, *a, **k): yield from self.frames
def read(self, amt=None): return b"".join(self.frames)
def close(self): pass
release_conn = close
def before_send(request, **_):
if request.url.endswith("/invoke"):
data = json.dumps(TOOL_MESSAGE).encode()
return AWSResponse(request.url, 200, {"content-type": "application/json", "content-length": str(len(data))},
Raw([data]))
frames = [frame("chunk", {"bytes": base64.b64encode(json.dumps(e).encode()).decode()}) for e in TOOL_EVENTS]
return AWSResponse(request.url, 200, {"content-type": "application/vnd.amazon.eventstream"}, Raw(frames))
class Rec(SpanProcessor):
def __init__(self): self.ended = []
def on_end(self, span): self.ended.append(span)
rec = Rec()
provider = TracerProvider(); provider.add_span_processor(rec)
BedrockInstrumentor().instrument(tracer_provider=provider)
client = boto3.client("bedrock-runtime", region_name="us-east-1", aws_access_key_id="x",
aws_secret_access_key="x", config=Config(retries={"total_max_attempts": 1}))
client.meta.events.register("before-send.bedrock-runtime.*", before_send)
BODY = json.dumps({"anthropic_version": "bedrock-2023-05-31", "max_tokens": 50,
"messages": [{"role": "user", "content": [{"type": "text", "text": "weather in Paris?"}]}],
"tools": [{"name": "get_weather", "input_schema": {"type": "object",
"properties": {"city": {"type": "string"}}}}]})
def show(label):
attrs = rec.ended[-1].attributes
out = {k: v for k, v in attrs.items() if "output" in k or "completion" in k or "finish" in k}
print(f"--- {label}")
print(" span output attributes:", out if out else "NONE")
rec.ended.clear()
r = client.invoke_model(modelId=MODEL, body=BODY)
print("invoke_model: app received", json.loads(r["body"].read())["content"][0]["input"])
show("invoke_model (tool call)")
rec.ended.clear()
r = client.invoke_model_with_response_stream(modelId=MODEL, body=BODY)
args = "".join(json.loads(e["chunk"]["bytes"]).get("delta", {}).get("partial_json", "") for e in r["body"])
print("invoke_model_with_response_stream: app received", args)
show("invoke_model_with_response_stream (tool call)")
Output:
boto3 1.43.108 | opentelemetry-instrumentation-bedrock 0.62.4
invoke_model: app received {'city': 'Paris'}
--- invoke_model (tool call)
span output attributes: {'gen_ai.usage.output_tokens': 5, 'gen_ai.response.finish_reasons': ('tool_call',), 'gen_ai.output.messages': '[{"role": "assistant", "parts": [{"type": "tool_call", "name": "get_weather", "id": "toolu_1", "arguments": {"city": "Paris"}}], "finish_reason": "tool_call"}]'}
invoke_model_with_response_stream: app received {"city": "Paris"}
--- invoke_model_with_response_stream (tool call)
span output attributes: {'gen_ai.usage.output_tokens': 5, 'gen_ai.response.finish_reasons': ('tool_call',), 'gen_ai.output.messages': '[{"role": "assistant", "parts": [{"type": "tool_call", "name": "get_weather", "id": "toolu_1", "arguments": {}}], "finish_reason": "tool_call"}]'}
π Expected behavior
The streamed tool call is recorded with the arguments the application received, {"city": "Paris"}, the same as for invoke_model.
π Actual Behavior with Screenshots
gen_ai.output.messages records the tool call with "arguments": {} for invoke_model_with_response_stream.
π€ Python Version
3.12
π Provide any additional context for the Bug.
opentelemetry-instrumentation-bedrock 0.62.4, boto3 / botocore 1.43.108, Linux. Possible fix: when a tool_use block starts with a dict input, replace it with "" before accumulating input_json_delta (e.g. if not isinstance(current.get("input"), str): current["input"] = ""), then json.loads the accumulated string at content_block_stop.
π Have you spent some time to check if this bug has been raised before?
- [x] I checked and didn't find similar issue
Are you willing to submit PR?
Yes I am willing to submit a PR!
Hi @armanunix, Iβd be interested in working on this issue if you havenβt started implementing it yet. I can reproduce the streaming tool-call argument loss and work on a fix with a regression test. Would it be okay for me to take this one?
Hi @armanunix, Iβd be interested in working on this issue if you havenβt started implementing it yet. I can reproduce the streaming tool-call argument loss and work on a fix with a regression test. Would it be okay for me to take this one?
Hi @sanjana658, thanks! I haven't started a fix, so please go ahead.