diff --git a/docs/_core_features/streaming.md b/docs/_core_features/streaming.md
index d9351b9701..124679b1d4 100644
--- a/docs/_core_features/streaming.md
+++ b/docs/_core_features/streaming.md
@@ -20,6 +20,7 @@ After reading this guide, you will know:
* How the final accumulated message is handled.
* How to integrate streaming with web frameworks like Rails and Sinatra.
* How streaming interacts with Tools.
+* How to observe stream events RubyLLM could not parse.
* Performance considerations for streaming.
## Basic Streaming
@@ -170,6 +171,52 @@ end
Refer to the [Error Handling Guide]({% link _advanced/error-handling.md %}) for details on specific error types.
+## Skipped Stream Events
+
+A provider occasionally sends a stream event that cannot be decoded: truncated JSON, a payload that is not a JSON object, or a Bedrock delta that does not parse. RubyLLM drops the event, keeps streaming, and logs a warning with the event's fields. The payload itself is never logged, only its size.
+
+```
+RubyLLM skipped a stream event it could not parse: provider=bedrock model=us.anthropic.claude-opus-5-5 site=event_payload event_type=chunk byte_size=412 error_class=JSON::ParserError
+```
+
+To record these events yourself, set `on_stream_parse_error`. The callable receives a frozen `RubyLLM::SkippedStreamEvent` for every dropped event:
+
+```ruby
+RubyLLM.configure do |config|
+ config.on_stream_parse_error = ->(event) { Rails.logger.info(event.to_h) }
+end
+```
+
+An exception raised by the hook is logged at warn and never ends the stream.
+
+The final message counts how many events were dropped while it streamed. The count is `0` when nothing was dropped and for replies that were not streamed:
+
+```ruby
+response = chat.ask("Tell me a story") { |chunk| print chunk.content }
+response.skipped_stream_events # => 0
+```
+
+A `SkippedStreamEvent` has these fields:
+
+| Field | Description |
+| --- | --- |
+| `provider` | Provider slug, such as `"bedrock"` |
+| `model` | Model id |
+| `site` | Where the event was dropped, one of the sites below |
+| `event_type` | The SSE `event:` name or the Bedrock `:event-type` header, or `nil` |
+| `byte_size` | Size of the dropped payload in bytes |
+| `error_class` | Class name of the decoding error, or `nil` when the payload decoded but was not a JSON object |
+
+The `site` is one of `RubyLLM::SkippedStreamEvent::SITES`:
+
+| Site | Dropped |
+| --- | --- |
+| `:sse_data` | An SSE `data:` payload that is not a JSON object. The `[DONE]` sentinel is never reported. |
+| `:event_payload` | A Bedrock eventstream payload, or its base64 `bytes`, that is not a JSON object |
+| `:event_type_header` | Kept in `SITES` for compatibility with 1.16. Not reported on 2.0. |
+| `:exception_type_header` | Kept in `SITES` for compatibility with 1.16. Not reported on 2.0. |
+| `:content_block_delta` | A Bedrock Converse delta sent as a JSON string that is not a JSON object. Each bad delta is reported once. |
+
## Streaming with Tools
Your streaming block can keep displaying text while RubyLLM runs tools between model responses. Use a callback to show tool activity:
diff --git a/docs/_getting_started/configuration-connection.md b/docs/_getting_started/configuration-connection.md
index c21aaebaf0..b02975e4c1 100644
--- a/docs/_getting_started/configuration-connection.md
+++ b/docs/_getting_started/configuration-connection.md
@@ -148,6 +148,14 @@ end
- On Ruby `<3.2`, RubyLLM warns if set and continues without timeout
- Helps bound regex execution time when debug logs contain very large payloads
+Stream events RubyLLM cannot parse are dropped and logged at warn. To record them, set `on_stream_parse_error` to a callable that receives each `RubyLLM::SkippedStreamEvent`. See [Skipped Stream Events]({% link _core_features/streaming.md %}#skipped-stream-events).
+
+```ruby
+RubyLLM.configure do |config|
+ config.on_stream_parse_error = ->(event) { Rails.logger.info(event.to_h) }
+end
+```
+
Built-in debug log redaction:
- Large base64-like blobs are redacted as `[BASE64 DATA]`
- Large embedding arrays are redacted as `[EMBEDDINGS ARRAY]`
diff --git a/docs/_getting_started/configuration.md b/docs/_getting_started/configuration.md
index 03c408c6c4..3788c269ee 100644
--- a/docs/_getting_started/configuration.md
+++ b/docs/_getting_started/configuration.md
@@ -225,6 +225,7 @@ RubyLLM.configure do |config|
config.log_level = Symbol
config.log_stream_debug = Boolean
config.log_regexp_timeout = Numeric # Ruby 3.2+ support
+ config.on_stream_parse_error = Proc # receives each RubyLLM::SkippedStreamEvent
end
```
diff --git a/lib/ruby_llm/configuration.rb b/lib/ruby_llm/configuration.rb
index e211fc4897..c88ca3f35a 100644
--- a/lib/ruby_llm/configuration.rb
+++ b/lib/ruby_llm/configuration.rb
@@ -299,6 +299,14 @@ def use_new_acts_as=(_value) # :nodoc:
# setting a value logs a warning.
option :log_regexp_timeout, -> { Regexp.respond_to?(:timeout) ? (Regexp.timeout || 1.0) : nil }
+ ##
+ # :attr_accessor: on_stream_parse_error
+ #
+ # Callable that receives a RubyLLM::SkippedStreamEvent for each stream
+ # event a parser could not decode and dropped. An exception it raises
+ # is logged and never ends the stream. Default: +nil+.
+ option :on_stream_parse_error, nil
+
def initialize # :nodoc:
self.class.send(:defaults).each do |key, default|
value = default.respond_to?(:call) ? instance_exec(&default) : default
diff --git a/lib/ruby_llm/message.rb b/lib/ruby_llm/message.rb
index d57b8f55a7..04277a8839 100644
--- a/lib/ruby_llm/message.rb
+++ b/lib/ruby_llm/message.rb
@@ -67,6 +67,10 @@ class Message
# Chat#with_provider_tools and the model used one.
attr_reader :server_tool_calls
+ # The number of stream events dropped because they could not be parsed,
+ # 0 when nothing was dropped or the reply was not streamed.
+ attr_reader :skipped_stream_events
+
# The provider-shaped content blocks of this assistant message, kept
# verbatim when the response used server tools so later requests can
# replay the turn exactly. +nil+ otherwise.
@@ -110,6 +114,7 @@ def initialize(options = {}) # :nodoc:
@raw_reasoning = options[:raw_reasoning]
@provider_data = options[:provider_data]
@finish_reason = options[:finish_reason]&.to_sym
+ @skipped_stream_events = options.fetch(:skipped_stream_events, 0)
self.ruby_llm_usage_entries = options[:usage_entries] if options[:usage_entries]
@cache_until_here = options.fetch(:cache_until_here, false)
diff --git a/lib/ruby_llm/protocol/stream_accumulator.rb b/lib/ruby_llm/protocol/stream_accumulator.rb
index 055a7561ce..dc3b9d4f0b 100644
--- a/lib/ruby_llm/protocol/stream_accumulator.rb
+++ b/lib/ruby_llm/protocol/stream_accumulator.rb
@@ -6,7 +6,7 @@
module RubyLLM
class Protocol
class StreamAccumulator # :nodoc:
- attr_reader :content, :model, :tool_calls
+ attr_reader :content, :model, :tool_calls, :skipped_events
def initialize
@content = +''
@@ -27,6 +27,7 @@ def initialize
@finish_reason = nil
@latest_tool_call_id = nil
@tool_call_ids_by_index = {}
+ @skipped_events = 0
end
def add(chunk)
@@ -44,6 +45,10 @@ def add(chunk)
RubyLLM.logger.debug { inspect } if RubyLLM.config.log_stream_debug
end
+ def skip_event
+ @skipped_events += 1
+ end
+
def to_message(response)
Message.new(
role: :assistant,
@@ -68,6 +73,7 @@ def to_message(response)
finish_reason: @finish_reason,
model: model,
tool_calls: tool_calls_from_stream(response),
+ skipped_stream_events: skipped_events,
raw: response
)
end
diff --git a/lib/ruby_llm/protocol/streaming.rb b/lib/ruby_llm/protocol/streaming.rb
index cf83814c16..8dca89182e 100644
--- a/lib/ruby_llm/protocol/streaming.rb
+++ b/lib/ruby_llm/protocol/streaming.rb
@@ -13,10 +13,12 @@ def initialize
end
end
+ include SkippedStreamEvent::Reporting
+
module_function
def stream_response(payload, additional_headers = {}, &block)
- accumulator = StreamAccumulator.new
+ accumulator = @stream_accumulator = StreamAccumulator.new
response = stream_events(stream_url, payload, additional_headers) do |data|
chunk = build_chunk(data)
@@ -27,6 +29,8 @@ def stream_response(payload, additional_headers = {}, &block)
message = accumulator.to_message(response)
RubyLLM.logger.debug { "Stream completed: #{message.content}" }
message
+ ensure
+ @stream_accumulator = nil
end
# Posts +payload+ to +url+ as a server-sent event stream, yielding each
@@ -135,20 +139,21 @@ def handle_sse(chunk, parser, env, progress)
else
next if data == '[DONE]'
- parsed = handle_data(data, env)
+ parsed = handle_data(data, env, event_type: type.empty? ? nil : type)
progress[:started] = true
yield parsed
end
end
end
- def handle_data(data, env)
+ def handle_data(data, env, event_type: nil)
parsed = JSON.parse(data)
- return parsed unless parsed.is_a?(Hash) && parsed.key?('error')
+ return skip_stream_event(:sse_data, data, event_type:) unless parsed.is_a?(Hash)
+ return parsed unless parsed.key?('error')
raise_stream_error(data, parsed, env)
rescue JSON::ParserError => e
- RubyLLM.logger.debug { "Failed to parse data chunk: #{e.message}" }
+ skip_stream_event(:sse_data, data, event_type:, error: e)
end
def handle_error_event(data, env)
diff --git a/lib/ruby_llm/protocols/anthropic.rb b/lib/ruby_llm/protocols/anthropic.rb
index 83d66c05fb..737bcad6c0 100644
--- a/lib/ruby_llm/protocols/anthropic.rb
+++ b/lib/ruby_llm/protocols/anthropic.rb
@@ -82,6 +82,7 @@ def merge_turn_segments(segments)
tokens: Tokens.aggregate(segments.map(&:tokens)),
finish_reason: final.finish_reason,
model: final.model,
+ skipped_stream_events: segments.sum(&:skipped_stream_events),
raw: final.raw
)
end
diff --git a/lib/ruby_llm/protocols/bedrock/event_stream.rb b/lib/ruby_llm/protocols/bedrock/event_stream.rb
index ee636af8cf..d351afbd97 100644
--- a/lib/ruby_llm/protocols/bedrock/event_stream.rb
+++ b/lib/ruby_llm/protocols/bedrock/event_stream.rb
@@ -12,12 +12,14 @@ module Bedrock
# +stream_url+ and +build_chunk+, which turns one decoded event into a
# Chunk.
module EventStream
+ include SkippedStreamEvent::Reporting
+
ErrorResponse = Struct.new(:body, :status)
private
def eventstream_response(payload, additional_headers = {}, &block)
- accumulator = RubyLLM::Protocol::StreamAccumulator.new
+ accumulator = @stream_accumulator = RubyLLM::Protocol::StreamAccumulator.new
decoder = event_stream_decoder
body = JSON.generate(payload)
progress = {}
@@ -45,6 +47,8 @@ def eventstream_response(payload, additional_headers = {}, &block)
message = accumulator.to_message(response)
RubyLLM.logger.debug { "Stream completed: #{message.content}" }
message
+ ensure
+ @stream_accumulator = nil
end
def event_stream_decoder
@@ -136,10 +140,14 @@ def decode_event(message)
exception_type = stream_exception_type(message)
payload = message.payload.read
- event = decode_event_payload(payload)
- return event unless exception_type
+ unless exception_type
+ return decode_event_payload(payload, event_type: event_header(message.headers, ':event-type'))
+ end
- { exception_type => event || { 'message' => payload.to_s } }
+ event = parse_event_payload(payload)
+ { exception_type => event.is_a?(Hash) ? event : { 'message' => payload.to_s } }
+ rescue JSON::ParserError
+ { exception_type => { 'message' => payload.to_s } }
end
# Failures the API does not model arrive as an error frame instead,
@@ -167,17 +175,20 @@ def event_header(headers, name)
header.respond_to?(:value) ? header.value : header
end
- def decode_event_payload(payload)
- outer = JSON.parse(payload)
+ def decode_event_payload(payload, event_type: nil)
+ event = parse_event_payload(payload)
+ return event if event.is_a?(Hash)
- if outer['bytes'].is_a?(String)
- JSON.parse(Base64.decode64(outer['bytes']))
- else
- outer
- end
+ skip_stream_event(:event_payload, payload, event_type:)
rescue JSON::ParserError => e
- RubyLLM.logger.debug { "Failed to decode Bedrock stream event payload: #{e.message}" }
- nil
+ skip_stream_event(:event_payload, payload, event_type:, error: e)
+ end
+
+ def parse_event_payload(payload)
+ outer = JSON.parse(payload)
+ return outer unless outer.is_a?(Hash) && outer['bytes'].is_a?(String)
+
+ JSON.parse(Base64.decode64(outer['bytes']))
end
def stream_error_event?(event)
diff --git a/lib/ruby_llm/protocols/converse/streaming.rb b/lib/ruby_llm/protocols/converse/streaming.rb
index e38d968d3a..d1d2089652 100644
--- a/lib/ruby_llm/protocols/converse/streaming.rb
+++ b/lib/ruby_llm/protocols/converse/streaming.rb
@@ -155,7 +155,7 @@ def tool_call_start_event?(event)
end
def tool_call_delta_event?(event)
- event['contentBlockDelta'] || event.dig('delta', 'toolUse')
+ event['contentBlockDelta'] || normalized_delta(event)['toolUse']
end
def extract_tool_call_start(event)
@@ -225,16 +225,30 @@ def event_block_index(event)
event.dig('contentBlockDelta', 'contentBlockIndex')
end
+ # Several extractors read the delta of the same event, so it is
+ # decoded once per event and a bad one is reported once.
def normalized_delta(event)
+ return @normalized_delta if @normalized_delta_event.equal?(event)
+
+ @normalized_delta_event = event
+ @normalized_delta = decode_delta(event)
+ end
+
+ def decode_delta(event)
delta = event.dig('contentBlockDelta', 'delta') || event['delta'] || {}
return delta if delta.is_a?(Hash)
+ return {} unless delta.is_a?(String) && !delta.empty?
- if delta.is_a?(String) && !delta.empty?
- JSON.parse(delta)
- else
- {}
- end
- rescue JSON::ParserError
+ parsed = JSON.parse(delta)
+ return parsed if parsed.is_a?(Hash)
+
+ skip_delta(delta)
+ rescue JSON::ParserError => e
+ skip_delta(delta, error: e)
+ end
+
+ def skip_delta(delta, error: nil)
+ skip_stream_event(:content_block_delta, delta, event_type: 'contentBlockDelta', error:)
{}
end
end
diff --git a/lib/ruby_llm/protocols/converse/thinking_stream.rb b/lib/ruby_llm/protocols/converse/thinking_stream.rb
index 166a0090ee..de2eb60023 100644
--- a/lib/ruby_llm/protocols/converse/thinking_stream.rb
+++ b/lib/ruby_llm/protocols/converse/thinking_stream.rb
@@ -18,7 +18,7 @@ def add(event)
start = part.dig('start', 'reasoningContent')
@blocks[index] = Support::Utils.deep_dup(start) if start
- delta = part.dig('delta', 'reasoningContent')
+ delta = part['delta']['reasoningContent'] if part['delta'].is_a?(Hash)
append_delta(index, delta) if delta
end
diff --git a/lib/ruby_llm/skipped_stream_event.rb b/lib/ruby_llm/skipped_stream_event.rb
new file mode 100644
index 0000000000..245c9802fe
--- /dev/null
+++ b/lib/ruby_llm/skipped_stream_event.rb
@@ -0,0 +1,61 @@
+# frozen_string_literal: true
+
+module RubyLLM
+ SkippedStreamEvent = Struct.new(:provider, :model, :site, :event_type, :byte_size, :error_class,
+ keyword_init: true) do
+ # Returns the event's fields as key=value pairs joined by
+ # spaces, with +nil+ written as -.
+ def log_fields
+ to_h.map { |key, value| "#{key}=#{value.nil? ? '-' : value}" }.join(' ')
+ end
+ end
+
+ # A stream event a parser could not decode and dropped. Each one is logged
+ # at warn and passed to +config.on_stream_parse_error+. The payload itself
+ # is never kept, only its size.
+ #
+ # RubyLLM.configure do |config|
+ # config.on_stream_parse_error = ->(event) { Rails.logger.info(event.to_h) }
+ # end
+ #
+ # Fields: +provider+ (provider slug), +model+ (model id), +site+ (one of
+ # SITES), +event_type+ (the SSE +event:+ name or Bedrock +:event-type+
+ # header, or +nil+), +byte_size+ (size of the dropped payload), and
+ # +error_class+ (the decoding error's class name, or +nil+ when the payload
+ # decoded but was not a JSON object).
+ class SkippedStreamEvent
+ SITES = %i[sse_data event_payload event_type_header exception_type_header content_block_delta].freeze
+
+ # Logs +event+ at warn and passes it to config.on_stream_parse_error.
+ # An exception from the hook is logged and never ends the stream.
+ def self.report(event, config)
+ RubyLLM.logger.warn("RubyLLM skipped a stream event it could not parse: #{event.log_fields}")
+ hook = config&.on_stream_parse_error
+ return unless hook
+
+ begin
+ hook.call(event)
+ rescue StandardError => e
+ RubyLLM.logger.warn("RubyLLM on_stream_parse_error hook raised #{e.class}: #{e.message}")
+ end
+ end
+
+ module Reporting # :nodoc:
+ private
+
+ def skip_stream_event(site, payload, event_type: nil, error: nil)
+ event = SkippedStreamEvent.new(
+ provider: @provider&.slug,
+ model: @model&.id,
+ site: site,
+ event_type: event_type,
+ byte_size: payload.to_s.bytesize,
+ error_class: error&.class&.name
+ ).freeze
+ @stream_accumulator&.skip_event
+ SkippedStreamEvent.report(event, @config || RubyLLM.config)
+ nil
+ end
+ end
+ end
+end
diff --git a/spec/ruby_llm/protocol/streaming_spec.rb b/spec/ruby_llm/protocol/streaming_spec.rb
index 283327e255..c8c4d9979b 100644
--- a/spec/ruby_llm/protocol/streaming_spec.rb
+++ b/spec/ruby_llm/protocol/streaming_spec.rb
@@ -194,11 +194,70 @@
end
it 'ignores a data chunk that is not valid JSON' do
- allow(RubyLLM.logger).to receive(:debug)
+ allow(RubyLLM.logger).to receive(:warn)
handler = test_obj.send(:handle_stream) { |_chunk| nil }
expect { handler.call("data: {broken\n\n", 0, env) }.not_to raise_error
- expect(RubyLLM.logger).to have_received(:debug)
+ expect(RubyLLM.logger).to have_received(:warn).with(/site=sse_data/)
+ end
+
+ describe 'skipped events' do
+ let(:reported) { [] }
+ let(:accumulator) { RubyLLM::Protocol::StreamAccumulator.new }
+
+ def feed(body)
+ yielded = []
+ test_obj.send(:handle_stream) { |chunk| yielded << chunk }.call(body, 0, env)
+ yielded
+ end
+
+ before do
+ allow(RubyLLM.logger).to receive(:warn)
+ config = RubyLLM::Configuration.new
+ config.on_stream_parse_error = ->(event) { reported << event }
+ test_obj.instance_variable_set(:@config, config)
+ test_obj.instance_variable_set(:@provider, instance_double(RubyLLM::Provider, slug: 'openai'))
+ test_obj.instance_variable_set(:@model, instance_double(RubyLLM::Model, id: 'gpt-6.2-sol'))
+ test_obj.instance_variable_set(:@stream_accumulator, accumulator)
+ end
+
+ it 'reports a data payload that is not valid JSON' do
+ feed("event: response.output_text.delta\ndata: {broken\n\n")
+
+ expect(reported.size).to eq(1)
+ expect(reported.first).to be_frozen
+ expect(reported.first.to_h).to eq(provider: 'openai', model: 'gpt-6.2-sol', site: :sse_data,
+ event_type: 'response.output_text.delta', byte_size: 7,
+ error_class: 'JSON::ParserError')
+ end
+
+ it 'reports a data payload that is not a JSON object, without an event name or error' do
+ feed("data: true\n\n")
+
+ expect(reported.map(&:to_h)).to eq([{ provider: 'openai', model: 'gpt-6.2-sol', site: :sse_data,
+ event_type: nil, byte_size: 4, error_class: nil }])
+ end
+
+ it 'does not report the DONE sentinel' do
+ feed("data: [DONE]\n\n")
+
+ expect(reported).to be_empty
+ expect(accumulator.skipped_events).to eq(0)
+ end
+
+ it 'counts two bad events and keeps every good chunk' do
+ yielded = feed("data: {\"x\":\"a\"}\n\ndata: {broken\n\ndata: {\"x\":\"b\"}\n\ndata: [1]\n\n")
+
+ expect(yielded).to eq(['chunk:a', 'chunk:b'])
+ expect(accumulator.skipped_events).to eq(2)
+ expect(accumulator.to_message(nil).skipped_stream_events).to eq(2)
+ end
+
+ it 'keeps streaming when the hook raises' do
+ test_obj.instance_variable_get(:@config).on_stream_parse_error = ->(_event) { raise 'boom' }
+
+ expect(feed("data: {broken\n\ndata: {\"x\":\"a\"}\n\n")).to eq(['chunk:a'])
+ end
end
it 'stops at the DONE sentinel without yielding' do
diff --git a/spec/ruby_llm/protocols/converse/streaming_spec.rb b/spec/ruby_llm/protocols/converse/streaming_spec.rb
index aaba748168..8b0fa39ddf 100644
--- a/spec/ruby_llm/protocols/converse/streaming_spec.rb
+++ b/spec/ruby_llm/protocols/converse/streaming_spec.rb
@@ -338,12 +338,88 @@ def encoded_frame(headers, payload)
end
it 'returns nil for an undecodable payload' do
- allow(RubyLLM.logger).to receive(:debug)
+ allow(RubyLLM.logger).to receive(:warn)
expect(streaming.send(:decode_event_payload, 'not json')).to be_nil
end
end
+ describe 'skipped events' do
+ let(:reported) { [] }
+ let(:accumulator) { RubyLLM::Protocol::StreamAccumulator.new }
+
+ def frame_decoder(payload, headers: {})
+ frame = Struct.new(:headers, :payload).new(headers, StringIO.new(payload))
+ frames = [[frame, true]]
+ decoder = Object.new
+ decoder.define_singleton_method(:decode_chunk) { |_chunk = nil| frames.shift }
+ decoder
+ end
+
+ before do
+ allow(RubyLLM.logger).to receive(:warn)
+ config = RubyLLM::Configuration.new
+ config.on_stream_parse_error = ->(event) { reported << event }
+ streaming.instance_variable_set(:@config, config)
+ streaming.instance_variable_set(:@provider, instance_double(RubyLLM::Provider, slug: 'bedrock'))
+ streaming.instance_variable_set(:@stream_accumulator, accumulator)
+ end
+
+ it 'reports an event payload that is not valid JSON with its event type header' do
+ decoder = frame_decoder('not json', headers: { ':message-type' => 'event', ':event-type' => 'contentBlockDelta' })
+
+ expect(streaming.send(:decode_events, decoder, 'frame')).to eq([])
+ expect(reported.map(&:to_h)).to eq([{ provider: 'bedrock', model: 'bedrock-test-model', site: :event_payload,
+ event_type: 'contentBlockDelta', byte_size: 8,
+ error_class: 'JSON::ParserError' }])
+ expect(accumulator.skipped_events).to eq(1)
+ end
+
+ it 'reports base64 bytes that do not decode to JSON' do
+ payload = { 'bytes' => Base64.strict_encode64('{broken') }.to_json
+
+ expect(streaming.send(:decode_event_payload, payload, event_type: 'chunk')).to be_nil
+ expect(reported.first.to_h).to include(site: :event_payload, event_type: 'chunk',
+ byte_size: payload.bytesize, error_class: 'JSON::ParserError')
+ end
+
+ it 'reports a payload that decodes to something other than a JSON object' do
+ expect(streaming.send(:decode_event_payload, '[1,2]')).to be_nil
+ expect(reported.first.to_h).to include(site: :event_payload, event_type: nil, byte_size: 5, error_class: nil)
+ end
+
+ it 'does not report an exception frame whose message is not JSON' do
+ decoder = frame_decoder('Too many requests',
+ headers: { ':message-type' => 'exception', ':exception-type' => 'throttlingException' })
+
+ expect(streaming.send(:decode_events, decoder, 'frame'))
+ .to eq([{ 'throttlingException' => { 'message' => 'Too many requests' } }])
+ expect(reported).to be_empty
+ end
+
+ it 'reports one bad delta once' do
+ chunk = streaming.send(:build_chunk, { 'contentBlockIndex' => 0, 'delta' => '{broken' })
+
+ expect(chunk.content).to be_nil
+ expect(reported.map(&:to_h)).to eq([{ provider: 'bedrock', model: 'bedrock-test-model',
+ site: :content_block_delta, event_type: 'contentBlockDelta',
+ byte_size: 7, error_class: 'JSON::ParserError' }])
+ expect(accumulator.skipped_events).to eq(1)
+ end
+
+ it 'reports a bad delta inside a contentBlockDelta with a block index once' do
+ streaming.send(:build_chunk, { 'contentBlockDelta' => { 'contentBlockIndex' => 1, 'delta' => '{broken' } })
+
+ expect(reported.size).to eq(1)
+ end
+
+ it 'reports a delta string that is not a JSON object' do
+ streaming.send(:build_chunk, { 'contentBlockDelta' => { 'delta' => '"hi"' } })
+
+ expect(reported.first.to_h).to include(site: :content_block_delta, byte_size: 4, error_class: nil)
+ end
+ end
+
describe '#decode_events' do
def frame_decoder(payload, headers: {})
frame = Struct.new(:headers, :payload).new(headers, StringIO.new(payload))
diff --git a/spec/ruby_llm/protocols/invoke_anthropic_spec.rb b/spec/ruby_llm/protocols/invoke_anthropic_spec.rb
index 93140c4bca..192d91d9c5 100644
--- a/spec/ruby_llm/protocols/invoke_anthropic_spec.rb
+++ b/spec/ruby_llm/protocols/invoke_anthropic_spec.rb
@@ -324,6 +324,66 @@ def stream(messages = [user_message], **options)
end
end
+ describe 'skipped stream events' do
+ let(:reported) { [] }
+
+ def bad_bytes_frame(bytes)
+ frame({ ':message-type' => 'event', ':event-type' => 'chunk', ':content-type' => 'application/json' },
+ JSON.generate('bytes' => Base64.strict_encode64(bytes)))
+ end
+
+ before do
+ allow(RubyLLM.logger).to receive(:warn)
+ RubyLLM.config.on_stream_parse_error = ->(event) { reported << event }
+ end
+
+ after { RubyLLM.config.on_stream_parse_error = nil }
+
+ it 'reports two bad events, counts them on the message and keeps every good chunk' do
+ stub_invoke_stream([message_start, bad_bytes_frame('{broken'), *text_block(0, 'Hello'),
+ bad_bytes_frame('"just a string"'), *message_end])
+
+ message, chunks = stream
+
+ expect(chunks.filter_map(&:content).join).to eq('Hello')
+ expect(message.content).to eq('Hello')
+ expect(message.skipped_stream_events).to eq(2)
+ expect(reported).to all(be_frozen)
+ expect(reported.map(&:to_h)).to eq(
+ [{ provider: 'bedrock', model: model_id, site: :event_payload, event_type: 'chunk',
+ byte_size: JSON.generate('bytes' => Base64.strict_encode64('{broken')).bytesize,
+ error_class: 'JSON::ParserError' },
+ { provider: 'bedrock', model: model_id, site: :event_payload, event_type: 'chunk',
+ byte_size: JSON.generate('bytes' => Base64.strict_encode64('"just a string"')).bytesize,
+ error_class: nil }]
+ )
+ end
+
+ it 'finishes the stream when the hook raises' do
+ RubyLLM.config.on_stream_parse_error = ->(_event) { raise 'boom' }
+ stub_invoke_stream([message_start, bad_bytes_frame('{broken'), *text_block(0, 'Hello'), *message_end])
+
+ message, = stream
+
+ expect(message.content).to eq('Hello')
+ expect(message.skipped_stream_events).to eq(1)
+ expect(RubyLLM.logger)
+ .to have_received(:warn).with('RubyLLM on_stream_parse_error hook raised RuntimeError: boom')
+ end
+
+ it 'counts zero on a clean stream and on a reply that was not streamed' do
+ stub_invoke_stream([message_start, *text_block(0, 'Hello'), *message_end])
+ stub_invoke
+
+ streamed, = stream
+ synced = protocol.complete([user_message], tools: {}, temperature: nil)
+
+ expect(streamed.skipped_stream_events).to eq(0)
+ expect(synced.skipped_stream_events).to eq(0)
+ expect(reported).to be_empty
+ end
+ end
+
describe 'streaming' do
it 'streams a text reply' do
stub_invoke_stream([message_start, *text_block(0, 'Hello'), *message_end(usage: { 'input_tokens' => 42,
@@ -561,5 +621,20 @@ def stream_reply(events)
'input_transformations' => [{ 'type' => 'thinking_dropped' }, { 'type' => 'thinking_flagged' }]
)
end
+
+ it 'sums the skipped stream events of every segment of a streamed turn' do
+ allow(RubyLLM.logger).to receive(:warn)
+ bad_frame = frame({ ':message-type' => 'event', ':event-type' => 'chunk', ':content-type' => 'application/json' },
+ JSON.generate('bytes' => Base64.strict_encode64('{broken')))
+ first = [message_start, bad_frame, *text_block(0, 'Part one. '), *message_end(stop_reason: 'pause_turn')]
+ second = [message_start, *text_block(0, 'Part two.'), bad_frame, *message_end]
+ stub_request(:post, "#{runtime}/invoke-with-response-stream")
+ .to_return(stream_reply(first)).then.to_return(stream_reply(second))
+
+ message, = stream
+
+ expect(message.content).to eq('Part one. Part two.')
+ expect(message.skipped_stream_events).to eq(2)
+ end
end
end
diff --git a/spec/ruby_llm/skipped_stream_event_spec.rb b/spec/ruby_llm/skipped_stream_event_spec.rb
new file mode 100644
index 0000000000..30fecaadf5
--- /dev/null
+++ b/spec/ruby_llm/skipped_stream_event_spec.rb
@@ -0,0 +1,58 @@
+# frozen_string_literal: true
+
+require 'spec_helper'
+
+RSpec.describe RubyLLM::SkippedStreamEvent do
+ let(:event) do
+ described_class.new(provider: 'bedrock', model: 'us.anthropic.claude-opus-5-5', site: :event_payload,
+ event_type: 'chunk', byte_size: 12, error_class: nil).freeze
+ end
+ let(:config) { RubyLLM::Configuration.new }
+
+ before { allow(RubyLLM.logger).to receive(:warn) }
+
+ it 'is configured through on_stream_parse_error, nil by default' do
+ expect(config.on_stream_parse_error).to be_nil
+
+ hook = ->(_event) {}
+ RubyLLM.configure { |c| c.on_stream_parse_error = hook }
+
+ expect(RubyLLM.config.on_stream_parse_error).to be(hook)
+ ensure
+ RubyLLM.configure { |c| c.on_stream_parse_error = nil }
+ end
+
+ it 'lists the sites a parser reports from' do
+ expect(described_class::SITES)
+ .to eq(%i[sse_data event_payload event_type_header exception_type_header content_block_delta])
+ end
+
+ it 'logs the fields at warn, writing nil as a dash' do
+ described_class.report(event, config)
+
+ expect(RubyLLM.logger).to have_received(:warn).with(
+ 'RubyLLM skipped a stream event it could not parse: provider=bedrock ' \
+ 'model=us.anthropic.claude-opus-5-5 site=event_payload event_type=chunk byte_size=12 error_class=-'
+ )
+ end
+
+ it 'passes the event to the hook' do
+ received = []
+ config.on_stream_parse_error = ->(skipped) { received << skipped }
+
+ described_class.report(event, config)
+
+ expect(received).to eq([event])
+ end
+
+ it 'logs an exception the hook raises instead of raising it' do
+ config.on_stream_parse_error = ->(_event) { raise ArgumentError, 'boom' }
+
+ expect { described_class.report(event, config) }.not_to raise_error
+ expect(RubyLLM.logger).to have_received(:warn).with('RubyLLM on_stream_parse_error hook raised ArgumentError: boom')
+ end
+
+ it 'counts zero skipped events on a message by default' do
+ expect(RubyLLM::Message.new(role: :assistant, content: 'Hi').skipped_stream_events).to eq(0)
+ end
+end