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

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

Instance Attribute Summary

Attributes included from Internal::Type::BaseStream

#headers, #last_response, #status

Instance Method Summary collapse

Methods included from Internal::Type::BaseStream

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

Constructor Details

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

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



89
90
91
92
93
94
95
96
97
98
99
# File 'sig/openai/helpers/streaming/response_stream.rbs', line 89

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,
    starting_after: starting_after
  )
end

Instance Method Details

#get_final_responseOpenAI::Responses::Response

Returns:

  • (OpenAI::Responses::Response)


45
46
47
48
49
50
# File 'lib/openai/helpers/streaming/response_stream.rb', line 45

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

#get_output_textString

Returns:

  • (String)


52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/openai/helpers/streaming/response_stream.rb', line 52

def get_output_text
  response = get_final_response
  text_parts = []

  response.output.each do |output|
    next unless output.is_a?(OpenAI::Models::Responses::ResponseOutputMessage)

    output.content.each do |content|
      next unless content.is_a?(OpenAI::Models::Responses::ResponseOutputText)

      text_parts << content.text
    end
  end

  text_parts.join
end

#textEnumerator[String]

Returns:

  • (Enumerator[String])


26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/openai/helpers/streaming/response_stream.rb', line 26

def text
  OpenAI::Internal::Util.chain_fused(@iterator) do |yielder|
    @text_only = true
    @iterator.each do |event|
      # Restore normal event snapshots while caller code is running.
      @text_only = false
      case event
      when OpenAI::Models::Responses::ResponseTextDeltaEvent
        yielder << event.delta
      end

      @text_only = true
    end

  ensure
    @text_only = false
  end
end

#until_doneself

Returns:

  • (self)


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

def until_done
  text.each { |_delta| nil }
  self
end