Class: Openai::Chat

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

Constant Summary collapse

BASE_URL =
'https://api.openai.com'.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Chat

Returns a new instance of Chat.



9
10
11
12
13
14
15
# File 'lib/openai/chat.rb', line 9

def initialize(options = {})
  @conn = Faraday.new(
    url: BASE_URL,
    headers: { 'Content-Type' => 'application/json', 'Authorization' => "Bearer #{options[:api_key]}" }
  )
  @model, @temperature, @stream = options.values_at(:model, :temperature, :stream)
end

Instance Attribute Details

#connObject (readonly)

Returns the value of attribute conn.



7
8
9
# File 'lib/openai/chat.rb', line 7

def conn
  @conn
end

#modelObject (readonly)

Returns the value of attribute model.



7
8
9
# File 'lib/openai/chat.rb', line 7

def model
  @model
end

#streamObject (readonly)

Returns the value of attribute stream.



7
8
9
# File 'lib/openai/chat.rb', line 7

def stream
  @stream
end

#temperatureObject (readonly)

Returns the value of attribute temperature.



7
8
9
# File 'lib/openai/chat.rb', line 7

def temperature
  @temperature
end

Instance Method Details

#call(messages) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/openai/chat.rb', line 17

def call(messages)
  res = conn.post('/v1/chat/completions') do |req|
    req.body = {
      model: model,
      temperature: temperature,
      messages: messages,
      stream: stream
    }.to_json

    if stream
      req.options.on_data = Proc.new do |chunk, overall_received_bytes, env|
        chunk_text = get_chunk_text(chunk)
        yield chunk_text unless chunk_text.nil?
      end
    end
  end

  JSON.parse(res.body).dig("choices", 0, "message", "content") unless stream
end