Class: ChatCli::CLI

Inherits:
Thor
  • Object
show all
Defined in:
lib/chat_cli.rb

Constant Summary collapse

LOADING_CHAR =
['\\', '-', '/', '|']

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.exit_on_failure?Boolean

Returns:

  • (Boolean)


77
78
79
# File 'lib/chat_cli.rb', line 77

def self.exit_on_failure?
    true
end

Instance Method Details

#chat(question) ⇒ Object



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

#initObject



61
62
63
64
65
66
67
68
69
# File 'lib/chat_cli.rb', line 61

def init()
    token = ask "Please enter your Secret API Key.\n" \
    "If it has not been issued yet, please go to the following site to issue a new API key.\n" \
    "  https://platform.openai.com/account/api-keys\n" \
    "API Key:"
    File.open(File.expand_path("../.env", __dir__), "w") do |file|
        file.write("OPENAI_ACCESS_TOKEN = #{token}")
    end
end

#usageObject



72
73
74
75
# File 'lib/chat_cli.rb', line 72

def usage()
    say "Please check bellow Web Site.\n" \
    "  https://platform.openai.com/account/usage"
end