Class: OpenAI::Helpers::Streaming::ResponseStream

Inherits:
Object
  • Object
show all
Includes:
Internal::Type::BaseStream
Defined in:
lib/openai/helpers/streaming/response_stream.rb

Instance Attribute Summary

Attributes included from Internal::Type::BaseStream

#headers, #last_response, #status

Instance Method Summary collapse

Methods included from Internal::Type::BaseStream

#close, #each, #inspect, #observe, #to_enum

Constructor Details

#initialize(raw_stream:, text_format: nil, starting_after: nil) ⇒ ResponseStream

Returns a new instance of ResponseStream.



9
10
11
12
13
14
15
16
17
18
# File 'lib/openai/helpers/streaming/response_stream.rb', line 9

def initialize(raw_stream:, text_format: nil, starting_after: nil)
  @text_format = text_format
  @starting_after = starting_after
  @raw_stream = raw_stream
  @last_response = raw_stream.last_response
  @iterator = iterator
  @state = ResponseStreamState.new(
    text_format: text_format
  )
end

Instance Method Details

#get_final_responseObject



36
37
38
39
40
41
# File 'lib/openai/helpers/streaming/response_stream.rb', line 36

def get_final_response
  until_done
  response = @state.completed_response
  raise "Didn't receive a 'response.completed' event" unless response
  response
end

#get_output_textObject



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/openai/helpers/streaming/response_stream.rb', line 43

def get_output_text
  response = get_final_response
  text_parts = []

  response.output.each do |output|
    next unless output.type == :message

    output.content.each do |content|
      next unless content.type == :output_text
      text_parts << content.text
    end
  end

  text_parts.join
end

#textObject



25
26
27
28
29
30
31
32
33
34
# File 'lib/openai/helpers/streaming/response_stream.rb', line 25

def text
  OpenAI::Internal::Util.chain_fused(@iterator) do |yielder|
    @iterator.each do |event|
      case event
      when OpenAI::Streaming::ResponseTextDeltaEvent
        yielder << event.delta
      end
    end
  end
end

#until_doneObject



20
21
22
23
# File 'lib/openai/helpers/streaming/response_stream.rb', line 20

def until_done
  each { |_event| next }
  self
end