summaryrefslogtreecommitdiff
path: root/logic/providers/openai/tools.rb
blob: f00176cea9bff1b187f60157052b0f3c34c54540 (about) (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
# frozen_string_literal: true

require 'json'
require 'babosa'

require_relative '../../helpers/hash'

module NanoBot
  module Logic
    module OpenAI
      module Tools
        def self.prepare(cartridge, tools)
          applies = []

          tools = Marshal.load(Marshal.dump(tools))

          tools.each do |tool|
            tool = Helpers::Hash.symbolize_keys(tool)

            cartridge.each do |candidate|
              candidate_key = candidate[:name].to_slug.normalize.gsub('-', '_')
              tool_key = tool[:function][:name].to_slug.normalize.gsub('-', '_')

              next unless candidate_key == tool_key

              source = {}

              source[:clojure] = candidate[:clojure] if candidate[:clojure]
              source[:fennel] = candidate[:fennel] if candidate[:fennel]
              source[:lua] = candidate[:lua] if candidate[:lua]

              applies << {
                id: tool[:id],
                label: candidate[:name],
                name: tool[:function][:name],
                type: 'function',
                parameters: JSON.parse(tool[:function][:arguments]),
                source:
              }
            end
          end

          raise 'missing tool' if applies.size != tools.size

          applies
        end

        def self.adapt(cartridge)
          output = {
            type: 'function',
            function: {
              name: cartridge[:name], description: cartridge[:description]
            }
          }

          output[:function][:parameters] = (cartridge[:parameters] || { type: 'object', properties: {} })

          output
        end
      end
    end
  end
end