Class: Llm::CLI

Inherits:
Object
  • Object
show all
Defined in:
lib/llm/cli.rb

Instance Method Summary collapse

Instance Method Details

#find_file(filename) ⇒ Object

Find the closest .llm-cli-config.yml file in the current directory, any parent directory or the users home directory



65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/llm/cli.rb', line 65

def find_file(filename)
  paths = []
  path_pieces = Dir.pwd.split(File::SEPARATOR)
  while path_pieces.any?
    path = path_pieces.join(File::SEPARATOR)
    path_pieces.pop
    paths << [path, filename].join(File::SEPARATOR)
  end
  paths << [ENV["HOME"], filename].join(File::SEPARATOR) if ENV["HOME"]
  result = paths.detect { |path| File.exist?(path) }
  result
end

#os_infoObject



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/llm/cli.rb', line 12

def os_info
  host_os = RbConfig::CONFIG['host_os']
  
  case host_os
  when /linux/
    os_name = "Linux"
  when /darwin/
    os_name = "Mac"
  when /mswin|msys|mingw|cygwin|bccwin|wince|emc/
    os_name = "Windows"
  else
    os_name = "Unknown"
  end

  version = RbConfig::CONFIG['host_os']

  { os_name: os_name, version: version }
end

#run(argv = nil) ⇒ Object



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
59
60
61
62
# File 'lib/llm/cli.rb', line 31

def run(argv=nil)
  os = os_info
  prompt = "You are a systems engineer working on #{os[:os_name]} (version #{os[:version]}). Your job is to write a shell commands. Please return your best guess as a single command that can be directly executed. If you must, you may include a short note, but please use comments so the results are directly executable. Please write a command that will:\n"

  config = { 
    "model" => "gpt-4o",
    "temperature" => 0.7, 
    "prompt" => prompt,
    "openai_api_key" => ENV["OPENAI_API_KEY"],
    "openai_organization_id" => ENV["OPENAI_ORGANIZATION_ID"]
  }
  config_filename = find_file(".llm-cli-config.yml")
  config_file = YAML.load_file(".llm-cli-config.yml") if config_filename
  config.merge!(config_file) if config_file

  if config["openai_api_key"].nil?
    puts "Please set OPENAI_API_KEY environment variable"
    exit 1
  end

  prompt = config["prompt"] + (argv || []).join(" ")

  client = OpenAI::Client.new(access_token: config["openai_api_key"], organization_id: config["openai_organization_id"])
  response = client.chat(
    parameters: {
      model: config["model"],
      temperature: config["temperature"],
      messages: [{ role: "user", content: prompt }]
    }
  )
  puts response.dig("choices", 0, "message", "content")
end