ValueError
aws_bedrock_runtime.InvokeModelWithResponseStream parse error (ValueError)
Stack trace
Traceback (most recent call last):
File "app.py", line 42, in <module>
response = client.invoke_model_with_response_stream(...)
File "aws_bedrock_runtime/client.py", line 128, in invoke_model_with_response_stream
for event in parse_response_stream(response):
File "aws_bedrock_runtime/parsing.py", line 56, in parse_response_stream
data = json.loads(event.data)
ValueError: Expecting value: line 1 column 1 (char 0) Why it happens
The AWS Bedrock streaming response contains event stream messages that must be parsed as JSON objects. If the stream includes unexpected empty messages, malformed JSON, or non-JSON control events, the JSON parser raises a ValueError. This often happens when the client code does not properly handle or filter event stream control frames or incomplete chunks.
Detection
Monitor logs for ValueError exceptions during InvokeModelWithResponseStream calls and log raw event stream data to identify malformed or unexpected messages before parsing.
Causes & fixes
The response stream includes empty or heartbeat events with no JSON payload.
Filter out empty or control events before calling json.loads() on event data.
Partial or truncated JSON data chunks are passed to the JSON parser.
Buffer and concatenate stream chunks until a complete JSON object is received before parsing.
The client code assumes all events contain JSON data, but some events are metadata or control frames.
Implement event type checking and parse only events with JSON payloads.
Code: broken vs fixed
from aws_bedrock_runtime import BedrockClient
client = BedrockClient()
response = client.invoke_model_with_response_stream(modelId="my-model", input={"prompt": "Hello"})
for event in response:
data = json.loads(event.data) # ValueError here if event.data is empty or invalid
print(data) import os
import json
from aws_bedrock_runtime import BedrockClient
client = BedrockClient()
response = client.invoke_model_with_response_stream(modelId="my-model", input={"prompt": "Hello"})
for event in response:
if event.data and event.data.strip(): # Skip empty events
try:
data = json.loads(event.data)
print(data)
except json.JSONDecodeError:
# Log and skip malformed JSON event
print(f"Skipping malformed event data: {event.data}") Workaround
Wrap the JSON parsing in try/except blocks and skip or log events that fail parsing to avoid crashing the stream processing.
Prevention
Use the AWS Bedrock SDK's built-in event stream parsers or utilities that correctly handle control frames and partial messages to ensure only valid JSON events are parsed.