26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
# File 'lib/chat_cli.rb', line 26
def chat(question)
Dotenv.load(File.expand_path("../.env", __dir__))
token = ENV['OPENAI_ACCESS_TOKEN']
if token.nil?
say "The following command must be executed to set the secret API key.\n" \
"> $sudo chat_cli init", :yellow
return
end
client = OpenAI::Client.new(access_token: ENV['OPENAI_ACCESS_TOKEN'])
response = nil
thread = Thread.new {
response = client.chat(
parameters: {
model: "gpt-3.5-turbo-0301",
messages: [{ role: "user", "content": question }],
})
}
1.upto(1200) do |i|
say "\r[#{LOADING_CHAR[i % 4]}]", nil, false
sleep 0.2
break unless thread.alive?
end
if response&.has_key? "error"
say("\r[ERROR] Invalid Secret API Key.\n" \
"Please set the correct secret API key again from the following command.\n" \
"> $sudo chat_cli init", :red); return if response&.dig("error", "code") == "invalid_api_key"
say "\r[ERROR] Unknown Error", :red
return
end
say "\rYou: #{question}"
say "GPT: #{response&.dig("choices", 0, "message", "content")}"
end
|