2024-11-14 06:58:24 +11:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module DiscourseAi
|
|
|
|
module Completions
|
2025-05-06 10:09:39 -03:00
|
|
|
class JsonStreamingTracker
|
|
|
|
attr_reader :current_key, :current_value, :stream_consumer
|
2024-11-14 06:58:24 +11:00
|
|
|
|
2025-05-06 10:09:39 -03:00
|
|
|
def initialize(stream_consumer)
|
|
|
|
@stream_consumer = stream_consumer
|
2024-11-14 06:58:24 +11:00
|
|
|
@current_key = nil
|
|
|
|
@current_value = nil
|
|
|
|
@parser = DiscourseAi::Completions::JsonStreamingParser.new
|
|
|
|
|
|
|
|
@parser.key do |k|
|
|
|
|
@current_key = k
|
|
|
|
@current_value = nil
|
|
|
|
end
|
|
|
|
|
2024-11-19 09:22:39 +11:00
|
|
|
@parser.value do |v|
|
|
|
|
if @current_key
|
2025-05-06 10:09:39 -03:00
|
|
|
stream_consumer.notify_progress(@current_key, v)
|
2024-11-19 09:22:39 +11:00
|
|
|
@current_key = nil
|
|
|
|
end
|
|
|
|
end
|
2024-11-14 06:58:24 +11:00
|
|
|
end
|
|
|
|
|
2025-05-15 11:32:10 -03:00
|
|
|
def broken?
|
|
|
|
@broken
|
|
|
|
end
|
|
|
|
|
2024-11-14 06:58:24 +11:00
|
|
|
def <<(json)
|
|
|
|
# llm could send broken json
|
|
|
|
# in that case just deal with it later
|
|
|
|
# don't stream
|
|
|
|
return if @broken
|
|
|
|
|
|
|
|
begin
|
|
|
|
@parser << json
|
|
|
|
rescue DiscourseAi::Completions::ParserError
|
|
|
|
@broken = true
|
|
|
|
return
|
|
|
|
end
|
|
|
|
|
|
|
|
if @parser.state == :start_string && @current_key
|
|
|
|
# this is is worth notifying
|
2025-05-06 10:09:39 -03:00
|
|
|
stream_consumer.notify_progress(@current_key, @parser.buf)
|
2024-11-14 06:58:24 +11:00
|
|
|
end
|
|
|
|
|
|
|
|
@current_key = nil if @parser.state == :end_value
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|