summaryrefslogtreecommitdiff
path: root/logic/providers/openai/tools.rb
blob: 1aa902974439083fac9f0deda18db5c9b4a7298f (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
64
65
66
67
68
69
70
71
72
# frozen_string_literal: true

require 'json'

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|
              next unless (
                            candidate[:type].nil? ||
                            (candidate[:type] == 'function' && tool[:type] == candidate[:type])
                          ) && tool[:function][:name] == candidate[:name]

              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],
                name: tool[:function][:name],
                type: candidate[:type] || 'function',
                parameters: JSON.parse(tool[:function][:arguments]),
                source:
              }
            end
          end

          applies
        end

        def self.adapt(cartridge)
          raise 'unsupported tool' if cartridge[:type] != 'function' && !cartridge[:type].nil?

          adapted = {
            type: cartridge[:type] || 'function',
            function: {
              name: cartridge[:name], description: cartridge[:description],
              parameters: { type: 'object', properties: {} }
            }
          }

          properties = adapted[:function][:parameters][:properties]

          adapted[:function][:parameters][:required] = cartridge[:required] if cartridge[:required]

          cartridge[:parameters]&.each do |parameter|
            key = parameter[:name].to_sym
            properties[key] = {}
            properties[key][:type] = parameter[:type] || 'string'
            properties[key][:description] = parameter[:description] if parameter[:description]
            properties[key][:items] = parameter[:items].slice(:type) if parameter[:items]
          end

          adapted
        end
      end
    end
  end
end