Module: GPTCLI

Defined in:
lib/gpt-cli.rb,
lib/gpt-cli/version.rb

Defined Under Namespace

Classes: Error

Constant Summary collapse

VERSION =
"0.1.5"

Class Method Summary collapse

Class Method Details

.exeObject



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/gpt-cli.rb', line 65

def self.exe
  options = {}
  chatgpt = ChatGPT.new
  parser = OptionParser.new do |opts|
    opts.on('-c', '--context CONTEXT_KEY', 'Context key from contexts.json') do |context_input|
      options[:context] = chatgpt.contexts.key?(context_input.to_sym) ? chatgpt.contexts[context_input.to_sym] : context_input
    end
    opts.on('-p', '--prompt PROMPT_TEXT', 'Prompt text to be passed to GPT-3') do |prompt_text|
      options[:prompt] = prompt_text
    end
    opts.on('-h', '--history', 'Print the message history') do
      options[:history] = true
    end
    opts.on('--clear', 'Clear the message history') do
      options[:clear] = true
    end
    opts.on('-d', '--dalle', 'Use DALL-E instead of GPT. Prompt should be no more than 1000 characters.') do
      options[:dalle] = true
    end
  end

  remaining_args = parser.parse!(ARGV)

  if options[:history]
    puts chatgpt.messages
  elsif options[:clear]
    File.delete(ChatGPT::MESSAGES_FILE) if File.exist?(ChatGPT::MESSAGES_FILE)
    puts "Message history cleared."
  else
    input_from_pipe = $stdin.read if $stdin.stat.pipe?
    input_from_remaining_args = remaining_args.join(" ") if remaining_args.any?

    prompt = options[:prompt] || input_from_remaining_args || ""
    full_prompt = [prompt, input_from_pipe].compact.join("\n\n")
    full_prompt.strip!

    if options[:dalle]
      if full_prompt.length > 1000
        puts "Prompt is too long. Truncating to 1000 characters."
        full_prompt = full_prompt[0...1000]
      end
      full_prompt.dalle2.then { |tempfile|
        current_working_directory = Dir.pwd
        filename = Digest::MD5.hexdigest(full_prompt)
        output_file_path = File.join(current_working_directory, "#{filename}.png")
        File.write(output_file_path, tempfile.read)
        puts "Image saved in current directory to #{filename}.png"
      }
    else
      puts chatgpt.gpt3(full_prompt, options)
      chatgpt.save_messages
    end
  end
rescue QuickOpenAI::Error => e
  warn e.message
  exit 1
end