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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
|
# frozen_string_literal: true
require 'openai'
require_relative 'base'
require_relative '../crypto'
require_relative '../../logic/providers/openai/tools'
require_relative '../../controllers/interfaces/tools'
require_relative 'openai/tools'
module NanoBot
module Components
module Providers
class OpenAI < Base
DEFAULT_ADDRESS = 'https://api.openai.com'
CHAT_SETTINGS = %i[
model stream temperature top_p n stop max_tokens
presence_penalty frequency_penalty logit_bias
].freeze
attr_reader :settings
def initialize(settings, credentials, environment: {})
@settings = settings
@credentials = credentials
@environment = environment
uri_base = if @credentials[:address].nil? || @credentials[:address].to_s.strip.empty?
"#{DEFAULT_ADDRESS}/"
else
"#{@credentials[:address].to_s.sub(%r{/$}, '')}/"
end
@client = ::OpenAI::Client.new(uri_base:, access_token: @credentials[:'access-token'])
end
def evaluate(input, streaming, cartridge, &feedback)
messages = input[:history].map do |event|
if event[:message].nil? && event[:meta] && event[:meta][:tool_calls]
{ role: 'assistant', content: nil, tool_calls: event[:meta][:tool_calls] }
elsif event[:who] == 'tool'
{ role: event[:who], content: event[:message].to_s,
tool_call_id: event[:meta][:id], name: event[:meta][:name] }
else
{ role: event[:who] == 'user' ? 'user' : 'assistant', content: event[:message] }
end
end
%i[instruction backdrop directive].each do |key|
next unless input[:behavior][key]
messages.prepend(
{ role: key == :directive ? 'system' : 'user',
content: input[:behavior][key] }
)
end
payload = { user: OpenAI.end_user(@settings, @environment), messages: }
CHAT_SETTINGS.each do |key|
payload[key] = @settings[key] if @settings.key?(key)
end
payload.delete(:logit_bias) if payload.key?(:logit_bias) && payload[:logit_bias].nil?
payload[:tools] = input[:tools].map { |raw| NanoBot::Logic::OpenAI::Tools.adapt(raw) } if input[:tools]
if streaming
content = ''
tools = []
payload[:stream] = proc do |chunk, _bytesize|
partial_content = chunk.dig('choices', 0, 'delta', 'content')
partial_tools = chunk.dig('choices', 0, 'delta', 'tool_calls')
if partial_tools
partial_tools.each do |partial_tool|
tools[partial_tool['index']] = {} if tools[partial_tool['index']].nil?
partial_tool.keys.reject { |key| ['index'].include?(key) }.each do |key|
target = tools[partial_tool['index']]
if partial_tool[key].is_a?(Hash)
target[key] = {} if target[key].nil?
partial_tool[key].each_key do |sub_key|
target[key][sub_key] = '' if target[key][sub_key].nil?
target[key][sub_key] += partial_tool[key][sub_key]
end
else
target[key] = '' if target[key].nil?
target[key] += partial_tool[key]
end
end
end
end
if partial_content
content += partial_content
feedback.call(
{ should_be_stored: false,
interaction: { who: 'AI', message: partial_content } }
)
end
if chunk.dig('choices', 0, 'finish_reason')
if tools&.size&.positive?
feedback.call(
{ should_be_stored: true,
needs_another_round: true,
interaction: { who: 'AI', message: nil, meta: { tool_calls: tools } } }
)
Tools.apply(cartridge, input[:tools], tools, feedback).each do |interaction|
feedback.call({ should_be_stored: true, needs_another_round: true, interaction: })
end
end
feedback.call(
{ should_be_stored: !(content.nil? || content == ''),
interaction: content.nil? || content == '' ? nil : { who: 'AI', message: content },
finished: true }
)
end
end
begin
@client.chat(parameters: payload)
rescue StandardError => e
raise e.class, e.response[:body] if e.response && e.response[:body]
raise e
end
else
begin
result = @client.chat(parameters: payload)
rescue StandardError => e
raise e.class, e.response[:body] if e.response && e.response[:body]
raise e
end
raise StandardError, result['error'] if result['error']
tools = result.dig('choices', 0, 'message', 'tool_calls')
if tools&.size&.positive?
feedback.call(
{ should_be_stored: true,
needs_another_round: true,
interaction: { who: 'AI', message: nil, meta: { tool_calls: tools } } }
)
Tools.apply(cartridge, input[:tools], tools, feedback).each do |interaction|
feedback.call({ should_be_stored: true, needs_another_round: true, interaction: })
end
end
content = result.dig('choices', 0, 'message', 'content')
feedback.call(
{ should_be_stored: !(content.nil? || content == ''),
interaction: content.nil? || content == '' ? nil : { who: 'AI', message: content },
finished: true }
)
end
end
def self.end_user(settings, environment)
user = ENV.fetch('NANO_BOTS_END_USER', nil)
user = settings[:user] if !settings[:user].nil? && !settings[:user].to_s.strip.empty?
candidate = environment && (
environment['NANO_BOTS_END_USER'] ||
environment[:NANO_BOTS_END_USER]
)
user = candidate if !candidate.nil? && !candidate.to_s.strip.empty?
user = if user.nil? || user.to_s.strip.empty?
'unknown'
else
user.to_s.strip
end
Crypto.encrypt(user, soft: true)
end
end
end
end
end
|