Class: RubyLLM::StreamAccumulator

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby_llm/stream_accumulator.rb

Overview

Assembles streaming responses from LLMs into complete messages.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeStreamAccumulator

Returns a new instance of StreamAccumulator.



8
9
10
11
12
13
14
15
16
# File 'lib/ruby_llm/stream_accumulator.rb', line 8

def initialize
  @content = +''
  @tool_calls = {}
  @input_tokens = nil
  @output_tokens = nil
  @cached_tokens = nil
  @cache_creation_tokens = nil
  @latest_tool_call_id = nil
end

Instance Attribute Details

#contentObject (readonly)

Returns the value of attribute content.



6
7
8
# File 'lib/ruby_llm/stream_accumulator.rb', line 6

def content
  @content
end

#model_idObject (readonly)

Returns the value of attribute model_id.



6
7
8
# File 'lib/ruby_llm/stream_accumulator.rb', line 6

def model_id
  @model_id
end

#tool_callsObject (readonly)

Returns the value of attribute tool_calls.



6
7
8
# File 'lib/ruby_llm/stream_accumulator.rb', line 6

def tool_calls
  @tool_calls
end

Instance Method Details

#add(chunk) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/ruby_llm/stream_accumulator.rb', line 18

def add(chunk)
  RubyLLM.logger.debug chunk.inspect if RubyLLM.config.log_stream_debug
  @model_id ||= chunk.model_id

  if chunk.tool_call?
    accumulate_tool_calls chunk.tool_calls
  else
    @content << (chunk.content || '')
  end

  count_tokens chunk
  RubyLLM.logger.debug inspect if RubyLLM.config.log_stream_debug
end

#to_message(response) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/ruby_llm/stream_accumulator.rb', line 32

def to_message(response)
  Message.new(
    role: :assistant,
    content: content.empty? ? nil : content,
    model_id: model_id,
    tool_calls: tool_calls_from_stream,
    input_tokens: @input_tokens,
    output_tokens: @output_tokens,
    cached_tokens: @cached_tokens,
    cache_creation_tokens: @cache_creation_tokens,
    raw: response
  )
end