Class: ActiveIntelligence::ChatREPLService

Inherits:
ApplicationService show all
Defined in:
app/services/active_intelligence/chat_repl_service.rb

Instance Method Summary collapse

Methods inherited from ApplicationService

call

Constructor Details

#initialize(chat) ⇒ ChatREPLService

rubocop:disable Rails/Output



7
8
9
10
11
12
# File 'app/services/active_intelligence/chat_repl_service.rb', line 7

def initialize(chat)
  super

  @chat = chat
  @counter = 1
end

Instance Method Details

#callObject



14
15
16
17
18
19
# File 'app/services/active_intelligence/chat_repl_service.rb', line 14

def call
  header
  help
  history
  loop { cycle || break }
end

#cycleObject



21
22
23
24
25
26
27
28
29
30
31
32
# File 'app/services/active_intelligence/chat_repl_service.rb', line 21

def cycle
  print prefix(:user)
  input = $stdin.gets.chomp
  case input
    when 'h' then help
    when 'p' then prompt
    when 'q' then return false
    else reply(input)
  end

  return true
end

#headerObject



34
35
36
# File 'app/services/active_intelligence/chat_repl_service.rb', line 34

def header
  puts "Chat #{@chat.id}\n"
end

#helpObject



38
39
40
41
42
43
44
45
# File 'app/services/active_intelligence/chat_repl_service.rb', line 38

def help
  puts <<~HELP

    h - help
    p - prompt
    q - quit
  HELP
end

#historyObject



47
48
49
50
51
52
# File 'app/services/active_intelligence/chat_repl_service.rb', line 47

def history
  @chat.messages.order(:id).each do |message|
    @counter += 1
    puts [prefix(message.role), message.content].join
  end
end

#prefix(name) ⇒ Object



54
55
56
# File 'app/services/active_intelligence/chat_repl_service.rb', line 54

def prefix(name)
  "\n(#{name}:#{@counter})> "
end

#promptObject



58
59
60
# File 'app/services/active_intelligence/chat_repl_service.rb', line 58

def prompt
  puts ["\n", @chat.to_prompt].join
end

#reply(input) ⇒ Object



62
63
64
65
66
67
68
69
# File 'app/services/active_intelligence/chat_repl_service.rb', line 62

def reply(input)
  @chat.messages.create!(role: 'user', content: input)

  @counter += 1
  print prefix(:assistant)
  puts @chat.reply.content
  @counter += 1
end