summaryrefslogtreecommitdiff
path: root/main.rb
blob: 4f38317c75dee941b6c8dd4ead595a2434edb383 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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
59
60
61
62
63
64
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
#!/usr/bin/env ruby

require "json"
require "net/http"
require "reline"
require "uri"

API_KEY = ENV["OPENAI_API_KEY"] or abort("Set OPENAI_API_KEY")
MODEL = ENV["MODEL"] || "gpt-5"
TOOLS = [
  {
    type: "function",
    function: {
      name: "read_file",
      description: "Read contents of a file",
      parameters: {
        type: "object",
        properties: { path: { type: "string" } },
        required: ["path"]
      }
    }
  },
  {
    type: "function",
    function: {
      name: "write_file",
      description: "Write contents to a file",
      parameters: {
        type: "object",
        properties: { path: { type: "string" }, content: { type: "string" } },
        required: ["path","content"]
      }
    }
  },
  {
    type: "function",
    function: {
      name: "run_command",
      description: "Run a shell command and return output",
      parameters: {
        type: "object",
        properties: { command: { type: "string" } },
        required: ["command"]
      }
    }
  }
]

def run_tool(name, args)
  case name
  when "read_file"
    { content: File.read(args["path"]) }
  when "write_file"
    { bytes_written: File.write(args["path"], args["content"]) }
  when "run_command"
    { output: `#{args["command"]}`.strip }
  else
    { error: "unknown tool #{name}" }
  end
rescue => e
  { error: e.message }
end

def openai_chat(messages, tools, timeout: 60)
  uri = URI("https://api.openai.com/v1/chat/completions")
  req = Net::HTTP::Post.new(uri)
  req["Authorization"] = "Bearer #{API_KEY}"
  req["Content-Type"] = "application/json"
  req.body = {
    model: MODEL,
    messages: messages,
    tools: tools,
    tool_choice: "auto"
  }.to_json

  http = Net::HTTP.new(uri.hostname, uri.port)
  http.use_ssl = true
  http.open_timeout = timeout
  http.read_timeout = timeout
  http.write_timeout = timeout if http.respond_to?(:write_timeout=)

  res = http.start { |h| h.request(req) }
  code = res.code.to_i

  raise "HTTP #{res.code}: #{res.body}" unless res.is_a?(Net::HTTPSuccess)

  JSON.parse(res.body)
end

messages = [{ role: "system", content: "You are a reasoning coding and system agent." }]
puts ">> Type instructions (or 'exit')"

loop do
  input = Reline.readline("User> ", true)&.strip
  break if input.nil? || input.downcase == "exit"
  messages << { role: "user", content: input }

  loop do
    message = openai_chat(messages, TOOLS).dig("choices", 0, "message")
    messages << message

    if message["content"] && !message["content"].empty?
      puts "\nAssistant> #{message['content']}"
    end

    if message["tool_calls"]
      message["tool_calls"].each do |call|
        name = call.dig("function","name")
        args = JSON.parse(call.dig("function","arguments"))
        puts "Tool> ▶ #{name}(#{args})"
        result = run_tool(name, args)
        messages << { role: "tool", tool_call_id: call["id"], content: JSON.dump(result) }
      end
      next # continue reasoning on tool results
    end

    break # no tool calls left, turn is done
  end
end