class StreamingParser
Parses streaming HTTP responses for Ollama, buffering and extracting JSON lines.
Definitions
def initialize(...)
Signature
-
parameter
args
Array
Arguments for the parent initializer.
Implementation
def initialize(...)
super
@buffer = String.new.b
@offset = 0
@value = {}
end
def read
Reads the next JSON object from the stream.
Signature
-
returns
Hash | nil
The next parsed object, or nil if the stream is empty.
Implementation
def read
return if @buffer.nil?
while true
if index = @buffer.index("\n", @offset)
line = @buffer.byteslice(@offset, index - @offset)
@buffer = @buffer.byteslice(index + 1, @buffer.bytesize - index - 1)
@offset = 0
return ::JSON.parse(line, symbolize_names: true)
end
if chunk = super
@buffer << chunk
else
return nil if @buffer.empty?
line = @buffer
@buffer = nil
@offset = 0
return ::JSON.parse(line, symbolize_names: true)
end
end
end
def join
Joins the stream, reading all objects and returning the final value.
Signature
-
returns
Hash
The final parsed value.
Implementation
def join
self.each{}
return @value
end