Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions docs/_core_features/streaming.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
8 changes: 8 additions & 0 deletions docs/_getting_started/configuration-connection.md
Original file line number Diff line number Diff line change
Expand Up @@ -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]`
Expand Down
1 change: 1 addition & 0 deletions docs/_getting_started/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
```

Expand Down
8 changes: 8 additions & 0 deletions lib/ruby_llm/configuration.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 5 additions & 0 deletions lib/ruby_llm/message.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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)

Expand Down
8 changes: 7 additions & 1 deletion lib/ruby_llm/protocol/stream_accumulator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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 = +''
Expand All @@ -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)
Expand All @@ -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,
Expand All @@ -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
Expand Down
15 changes: 10 additions & 5 deletions lib/ruby_llm/protocol/streaming.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
Expand Down Expand Up @@ -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)
Expand Down
1 change: 1 addition & 0 deletions lib/ruby_llm/protocols/anthropic.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
37 changes: 24 additions & 13 deletions lib/ruby_llm/protocols/bedrock/event_stream.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {}
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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)
Expand Down
28 changes: 21 additions & 7 deletions lib/ruby_llm/protocols/converse/streaming.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion lib/ruby_llm/protocols/converse/thinking_stream.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ThinkingStream now skips string-encoded deltas, while the chunk extractors decode them. That means reasoning text and signatures sent this way get dropped from raw_reasoning.

Converse::Streaming#normalized_delta JSON-decodes a string delta, so extract_thinking_delta and extract_signature_from_delta still put that reasoning into the chunk's thinking. This line only reads part['delta'] when it is already a Hash. For a valid string delta like '{"reasoningContent":{"reasoningText":{"text":"…","signature":"…"}}}', the text and signature never reach @blocks. The final raw_reasoning then loses that block or its signature. That is the data used to replay the turn verbatim, and Bedrock rejects a thinking block that is missing its signature on the next request.

Before this PR the same input raised TypeError. Now it fails silently, which is harder to notice. Decode the delta the same way the extractors do, for example by passing the already-normalized delta into ThinkingStream#add, or by having it parse a string delta itself, so both paths see the same reasoning.

append_delta(index, delta) if delta
end

Expand Down
Loading