Skip to content

Instantly share code, notes, and snippets.

@amkisko
Created March 30, 2023 09:15
Show Gist options
  • Save amkisko/74fec1275d5ecdd5331a303c0e3069e1 to your computer and use it in GitHub Desktop.
Save amkisko/74fec1275d5ecdd5331a303c0e3069e1 to your computer and use it in GitHub Desktop.
gpt-cli wrapper for safer credentials and config support
#!/usr/bin/env ruby
require 'bundler/inline'
gemfile do
source 'https://rubygems.org'
gem 'gpt-cli'
gem 'rbnacl'
end
require 'yaml'
require 'gpt-cli'
require 'rbnacl'
require 'fileutils'
require 'base64'
nonce_file = File.join(Dir.home, '.gpt-cli-nonce')
FileUtils.touch(nonce_file)
# config_file = ARGV.find { |arg| ['-c', '--config'].include?(arg) }&.then { |arg| ARGV[ARGV.index(arg) + 1] }
config_file = File.join(Dir.home, '.gpt-cli.config.yaml')
FileUtils.touch(config_file)
default_config = {
'access_token' => nil,
'model' => 'gpt-3.5-turbo',
'contexts_path' => nil,
'default_context' => 'default'
}
config = YAML.load_file(config_file) || default_config
if config['access_token'].nil?
puts "Please enter your OpenAI access token:"
access_token = gets.chomp
key = RbNaCl::Random.random_bytes(RbNaCl::SecretBox.key_bytes)
nonce = RbNaCl::Random.random_bytes(RbNaCl::SecretBox.nonce_bytes)
encrypted_access_token = RbNaCl::SecretBox.new(key).encrypt(nonce, access_token)
config['access_token'] = Base64.strict_encode64(encrypted_access_token)
File.write(config_file, config.to_yaml)
File.write(nonce_file, "#{Base64.strict_encode64(key)}:#{Base64.strict_encode64(nonce)}")
end
config = YAML.load_file(config_file)
key,nonce = File.read(nonce_file).split(":").map{Base64.strict_decode64(_1)}
encrypted_access_token = Base64::strict_decode64(config['access_token'])
ENV['OPENAI_ACCESS_TOKEN'] = RbNaCl::SecretBox.new(key).decrypt(nonce, encrypted_access_token)
ENV['OPENAI_MODEL'] = config['model']
contexts_file = File.join(Dir.home, '.gpt-cli.contexts.json')
if !config['contexts_path'] && !File.exists?(contexts_file)
File.write(contexts_file, { default: "" }.to_json)
end
ENV['OPENAI_CONTEXTS_PATH'] = config['contexts_path'] || contexts_file
ENV['OPENAI_DEFAULT_CONTEXT'] = config['default_context']
GPTCLI.exe
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment