Class: Charai::OpenaiChat

Inherits:
Object
  • Object
show all
Defined in:
lib/charai/openai_chat.rb

Instance Method Summary collapse

Constructor Details

#initialize(configuration, introduction: nil, callback: nil) ⇒ OpenaiChat

callback

- on_chat_start(introduction)
- on_chat_question(content: Array|String)
- on_chat_answer(answer_text)
- on_chat_conversation(content, answer_text)


13
14
15
16
17
18
19
# File 'lib/charai/openai_chat.rb', line 13

def initialize(configuration, introduction: nil, callback: nil)
  @configuration = configuration
  @introduction = introduction
  @callback = callback
  @mutex = Mutex.new
  clear
end

Instance Method Details

#clearObject



21
22
23
24
25
26
27
28
# File 'lib/charai/openai_chat.rb', line 21

def clear
  trigger_callback(:on_chat_start, @introduction)

  @messages = []
  if @introduction
    @messages << { role: 'system', content: @introduction }
  end
end

#popObject



51
52
53
54
55
56
# File 'lib/charai/openai_chat.rb', line 51

def pop
  @mutex.synchronize do
    @messages.pop
    @messages.pop[:content]
  end
end

#push(question, images: []) ⇒ Object

.push(‘How are you?’) .push(‘How many people is here?’, images: [ { jpg: ‘xXxXxxxxxxxxx’ }, { png: ‘xXxXxxxxxxxxx’ } ])



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/charai/openai_chat.rb', line 32

def push(question, images: [])
  content = build_question(question, images)
  message = {
    role: 'user',
    content: content,
  }

  @mutex.synchronize do
    trigger_callback(:on_chat_question, content)
    fetch_openai(message).tap do |answer|
      trigger_callback(:on_chat_answer, answer)
      trigger_callback(:on_chat_conversation, content, answer)

      @messages << message
      @messages << { role: 'assistant', content: answer }
    end
  end
end