Class: ChatgptAssistant::Chatter

Inherits:
Object
  • Object
show all
Defined in:
lib/chatgpt_assistant/chatter.rb

Overview

This is the Chat Ai class

Instance Method Summary collapse

Constructor Details

#initialize(openai_api_key) ⇒ Chatter

Returns a new instance of Chatter.



9
10
11
# File 'lib/chatgpt_assistant/chatter.rb', line 9

def initialize(openai_api_key)
  @openai_api_key = openai_api_key
end

Instance Method Details

#chat(message, chat_id, error_message) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/chatgpt_assistant/chatter.rb', line 13

def chat(message, chat_id, error_message)
  @error_message = error_message
  @chat_id = chat_id
  @message = message
  @response = request(message)
  @json = JSON.parse(response.body)

  return no_response_error if json["choices"] && json["choices"].empty?
  return bot_offline_error if response.status != 200

  text = json["choices"][0]["message"]["content"]

  Message.create(content: text, role: "assistant", chat_id: chat_id)
  text
rescue StandardError => e
  Error.create(message: e.message, backtrace: e.backtrace)
  error_message
end