Skip to content

Instantly share code, notes, and snippets.

@Duartemartins
Last active May 27, 2023 16:49
Show Gist options
  • Save Duartemartins/b7573b7f48b41c0edd8ec785a593bc25 to your computer and use it in GitHub Desktop.
Save Duartemartins/b7573b7f48b41c0edd8ec785a593bc25 to your computer and use it in GitHub Desktop.
This Ruby script enables interactive editing of files using the OpenAI GPT-4 language model. The user provides instructions or prompts, either standalone or related to a specific file. If a file is specified, the script reads its contents and passes them, along with the user's instruction, to the GPT-4 model. The script also uses the tree comman…
#!/Users/duarte/.asdf/shims/ruby
require 'openai'
require 'json'
require 'tempfile'
require 'open3'
OpenAI.configure do |config|
config.access_token = ENV['OPENAI_API_KEY']
config.organization_id = 'ABC' # Optional, if you belong to multiple organizations
end
@client = OpenAI::Client.new
@system_prompt = 'You are an AI language model trained to provide expert-level X. You are especially skilled at Y.'
@project_directory = 'Z'
def project_tree(start_dir)
tree_command = "tree -I 'node_modules|_site' #{start_dir}"
output, status = Open3.capture2(tree_command)
status.success? ? output : nil
end
def handle_file_and_instruction(file_name, instruction)
file_contents = File.read(file_name)
chat_with_gpt("#{file_contents}\n#{instruction}")
end
def chat_with_gpt(user_prompt)
puts 'ChatGPT is thinking...'
response = @client.chat(
parameters: {
model: 'gpt-4', # The model to use
messages: [
{ role: 'system',
content: "#{@system_prompt}\nProject structure: #{project_tree(@project_directory)}" },
{ role: 'user', content: user_prompt }
], # The system message and user prompt
temperature: 0.7,
stream: proc do |chunk, _bytesize|
print chunk.dig('choices', 0, 'delta', 'content')
end
}
)
end
while true
puts 'Enter your prompt or file name and instruction (format: "file:<filename> instruction:<instruction>"):'
input = gets.chomp
if input.start_with?('file:')
file_part, instruction_part = input.split('instruction:')
file_name = file_part.strip[5..]
instruction = instruction_part.strip
response = handle_file_and_instruction(file_name, instruction)
else
response = chat_with_gpt(input)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment