Class: Layered::Assistant::ChunkService

Inherits:
Object
  • Object
show all
Defined in:
app/services/layered/assistant/chunk_service.rb

Constant Summary collapse

STOP_CHECK_INTERVAL =
25
BROADCAST_INTERVAL_MS =
25

Instance Method Summary collapse

Constructor Details

#initialize(message, provider:, started_at: nil) ⇒ ChunkService

Returns a new instance of ChunkService.



7
8
9
10
11
12
13
14
15
16
17
18
# File 'app/services/layered/assistant/chunk_service.rb', line 7

def initialize(message, provider:, started_at: nil)
  @message = message
  @parser = ChunkParser.new(provider.protocol)
  @timer = ResponseTimer.new
  @timer.start! if started_at
  @input_tokens = 0
  @output_tokens = 0
  @chunk_count = 0
  @stopped = false
  @last_broadcast_at = 0
  @broadcast_pending = false
end

Instance Method Details

#call(chunk) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'app/services/layered/assistant/chunk_service.rb', line 24

def call(chunk)
  return if @stopped

  @chunk_count += 1
  if @chunk_count % STOP_CHECK_INTERVAL == 0
    @stopped = @message.reload.stopped?
    if @stopped
      attrs = @timer.timing_attrs
      unless attrs.empty?
        @message.update!(attrs)
        @message.broadcast_updated
      end
      return
    end
  end

  Rails.logger.debug { "[ChunkService] #{chunk.inspect}" }
  text = @parser.text(chunk)
  @input_tokens  = @parser.input_tokens(chunk)  || @input_tokens
  @output_tokens = @parser.output_tokens(chunk) || @output_tokens

  if text
    @timer.record_first_token!
    @message.update!(content: (@message.content || "") + text)
    broadcast_throttled
  end

  if @parser.finished?(chunk) || @parser.usage_ready?(chunk)
    save_token_usage
    @message.broadcast_streaming_content if @broadcast_pending
    @message.broadcast_updated
  end
end

#mark_started!Object



20
21
22
# File 'app/services/layered/assistant/chunk_service.rb', line 20

def mark_started!
  @timer.start!
end