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

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

Instance Method Summary collapse

Methods included from Internal::Type::BaseStream

#close, defer_closing, #each, #inspect, #to_enum

Constructor Details

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

Returns a new instance of ResponseStream.



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

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

Instance Method Details

#get_final_responsevoid

Raises:

  • (RuntimeError)


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

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

#get_output_textvoid



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

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

#textvoid



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

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_donevoid



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

def until_done
  each {} # rubocop:disable Lint/EmptyBlock
  self
end