Class: OpenAI::Stream

Inherits:
Object
  • Object
show all
Defined in:
lib/openai/stream.rb

Instance Method Summary collapse

Constructor Details

#initialize(user_proc:, parser: EventStreamParser::Parser.new) ⇒ Stream

Returns a new instance of Stream.



6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/openai/stream.rb', line 6

def initialize(user_proc:, parser: EventStreamParser::Parser.new)
  @user_proc = user_proc
  @parser = parser

  # To be backwards compatible, we need to check how many arguments the user_proc takes.
  @user_proc_arity =
    case user_proc
    when Proc
      user_proc.arity.abs
    else
      user_proc.method(:call).arity.abs
    end
end

Instance Method Details

#call(chunk, _bytes, env = nil) ⇒ Object



20
21
22
23
24
25
26
27
28
29
# File 'lib/openai/stream.rb', line 20

def call(chunk, _bytes, env = nil)
  handle_http_error(chunk: chunk, env: env) if env && env.status != 200

  parser.feed(chunk) do |event, data|
    next if data == DONE

    args = [JSON.parse(data), event].first(user_proc_arity)
    user_proc.call(*args)
  end
end

#to_procObject



31
32
33
# File 'lib/openai/stream.rb', line 31

def to_proc
  method(:call).to_proc
end