Class: OpenaiSingleChat::Client

Inherits:
Object
  • Object
show all
Includes:
HTTParty
Defined in:
lib/openai_single_chat.rb

Instance Method Summary collapse

Constructor Details

#initialize(model = 'gpt-4o-mini') ⇒ Client

Returns a new instance of Client.



15
16
17
18
19
20
21
22
23
# File 'lib/openai_single_chat.rb', line 15

def initialize(model = 'gpt-4o-mini')
  @model = model
  @options = {
    headers: {
      'Content-Type' => 'application/json',
      'Authorization' => "Bearer #{ENV['OPENAI_API']}"
    }
  }
end

Instance Method Details

#chat(message, system_message = nil) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/openai_single_chat.rb', line 25

def chat(message, system_message = nil)
  messages = []
  messages << { role: 'system', content: system_message } if system_message
  messages << { role: 'user', content: message }

  body = {
    model: @model,
    messages: messages
  }.to_json

  response = self.class.post('/chat/completions', body: body, headers: @options[:headers])
  
  if response.success?
    response.parsed_response['choices'][0]['message']['content']
  else
    handle_error_response(response)
  end
end