Class: ChatGptService

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(api_key, model = 'gpt-3.5-turbo') ⇒ ChatGptService

Returns a new instance of ChatGptService.



6
7
8
9
10
11
12
13
14
15
# File 'lib/chat_gpt_service.rb', line 6

def initialize(api_key, model = 'gpt-3.5-turbo')
  @options = {
    headers: {
      'Content-Type': 'application/json',
      'Authorization': "Bearer #{api_key}"
    },
    api_url: 'https://api.openai.com/v1/chat/completions',
    model: model
  }
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



4
5
6
# File 'lib/chat_gpt_service.rb', line 4

def options
  @options
end

Instance Method Details

#translate(message, languages) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/chat_gpt_service.rb', line 17

def translate(message, languages)
  message = set_messsage_for_translation(message, languages)
  body = {
    model: options[:model],
    messages: [{ role: 'user', content: message }]
  }
  begin
    response = HTTParty.post(options[:api_url], body: body.to_json, headers: options[:headers], timeout: 10)
    response['choices'][0]['message']['content']
  rescue Exception => e
    "Chat gpt sent an invalid response #{e.message}"
  end
end