Module: LLM::Backend::ClassMethods
- Defined in:
- lib/scout/llm/backends/default.rb
Instance Method Summary collapse
- #ask(question, options = {}, &block) ⇒ Object
- #chain_tools(messages, output, tools, options = {}, &block) ⇒ Object
-
#client(options) ⇒ Object
{{{ CLIENT.
- #client_options(options) ⇒ Object
- #embed(text, options = {}) ⇒ Object
- #embed_query(client, text, parameters = {}) ⇒ Object
-
#encode_image(path) ⇒ Object
{{{ MEDIA.
- #encode_pdf(path) ⇒ Object
- #extra_options(options, messages = nil) ⇒ Object
- #extract_tools(messages, tools = []) ⇒ Object
- #format_messages(messages) ⇒ Object
- #format_other(message) ⇒ Object
- #format_tool_call(message) ⇒ Object
-
#format_tool_definitions(tools) ⇒ Object
{{{ TOOLS.
- #format_tool_output(message, last_id = nil) ⇒ Object
- #gather_response(server, id) ⇒ Object
- #image(question, options = {}, &block) ⇒ Object
-
#messages(question, options) ⇒ Object
{{{ Processing.
- #parse_tool_call(info) ⇒ Object
- #prepare_client(options, messages = nil) ⇒ Object
-
#process_format(format) ⇒ Object
{{{ FORMAT.
- #process_response(messages, response, tools, options, &block) ⇒ Object
- #query(client, messages, tools = [], parameters = {}) ⇒ Object
- #reasoning(response, current_meta = nil) ⇒ Object
- #tools(messages, options) ⇒ Object
- #update_meta(response, current_meta = nil) ⇒ Object
- #upload_messages(server, messages, options) ⇒ Object
Instance Method Details
#ask(question, options = {}, &block) ⇒ Object
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 |
# File 'lib/scout/llm/backends/default.rb', line 476 def ask(question, = {}, &block) = .dup , log_response, , relay, process = IndiferentHash. , :return_messages, :log_response, :current_meta, :relay, :process, return_messages: false, log_response: true = self. question, if relay id = (relay, , ) response = gather_response(relay, id) IndiferentHash.setup(response) client = prepare_client , = () tools = tools(, ) else client = prepare_client , = () tools = tools(, ) response = begin Log.medium "Calling #{self}: #{Log.fingerprint(.except(:tools))}}" query(client, , tools, ) rescue Exception Log.debug 'Asking error. Options: ' + "\n" + JSON.pretty_generate(.except(:tools)) raise $! end end if process Scout.var.query.response[process].set_extension(:json).write response.to_json return response end Log.debug "Response: #{Log.fingerprint response}" raise 'No response' if response.nil? reasoning = reasoning response output = process_response , response, tools, , &block if log_response = self. response, ['reas'] = reasoning if reasoning end output = chain_tools , output, tools, .merge(client: client, tools: tools, log_response: log_response, current_meta: , relay: relay) output.unshift({role: :meta, content: Chat.()}) if log_response && && .any? if output.last[:role] != :previous_response_id && [:previous_response_id] output << { role: :previous_response_id, content: [:previous_response_id] } end if Chat.setup output else output = Chat.clean(output) return '' if output.nil? || output.empty? Chat.purge(output).last['content'] end end |
#chain_tools(messages, output, tools, options = {}, &block) ⇒ Object
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 |
# File 'lib/scout/llm/backends/default.rb', line 330 def chain_tools(, output, tools, = {}, &block) previous_response_id = [:previous_response_id] return output if output === [] raise "Output format unknown #{output}" unless (Hash === output.last) && output.last.include?(:role) if output.last[:role] == 'function_call_output' begin case previous_response_id when String output + ask(output, .except(:tool_choice).merge(return_messages: true, previous_response_id: previous_response_id), &block) else output + ask( + output, .except(:tool_choice).merge(return_messages: true), &block) end rescue Exception raise $! end else output end end |
#client(options) ⇒ Object
{{{ CLIENT
29 30 31 32 33 34 35 |
# File 'lib/scout/llm/backends/default.rb', line 29 def client() url, key, model, api_version, log_errors, request_timeout = IndiferentHash. , :url, :key, :model, :api_version, :log_errors, :request_timeout, log_errors: true, request_timeout: 1200, api_version: 'v1' Object::OpenAI::Client.new(api_version: api_version, access_token: key, log_errors: log_errors, uri_base: url, request_timeout: request_timeout) end |
#client_options(options) ⇒ Object
37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/scout/llm/backends/default.rb', line 37 def () url, key, model, api_version, tag, default_model, log_errors, request_timeout = IndiferentHash. , :url, :key, :model, :api_version, :tag, :default_model, :log_errors, :request_timeout, tag: self::TAG, default_model: self::DEFAULT_MODEL, log_errors: true, request_timeout: 1200 url ||= Scout::Config.get(:url, "#{tag}_ask", :ask, tag, env: "#{tag.upcase}_URL") key ||= LLM.get_url_config(:key, url, "#{tag}_ask", :ask, tag, env: "#{tag.upcase}_KEY") model ||= LLM.get_url_config(:model, url, :openai_ask, :ask, :openai, env: "#{tag.upcase}_MODEL,MODEL", default: default_model) { url: url, key: key, model: model, api_version: api_version }.reject { |_k, v| v.nil? } end |
#embed(text, options = {}) ⇒ Object
583 584 585 586 |
# File 'lib/scout/llm/backends/default.rb', line 583 def (text, = {}) client = prepare_client client, text, end |
#embed_query(client, text, parameters = {}) ⇒ Object
576 577 578 579 580 581 |
# File 'lib/scout/llm/backends/default.rb', line 576 def (client, text, parameters = {}) parameters[:text] = text response = client.(parameters: parameters) raise response['error']['message'] if response.include? 'error' response.dig('data', 0, 'embedding') end |
#encode_image(path) ⇒ Object
{{{ MEDIA
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 |
# File 'lib/scout/llm/backends/default.rb', line 150 def encode_image(path) path = path.find if Path === path file_content = File.binread(path) case extension = path.split('.').last.downcase when 'jpg', 'jpeg' mime = 'image/jpeg' when 'png' mime = 'image/png' else mime = 'image/extension' end base64_string = Base64.strict_encode64(file_content) "data:#{mime};base64,#{base64_string}" end |
#encode_pdf(path) ⇒ Object
168 169 170 171 172 173 |
# File 'lib/scout/llm/backends/default.rb', line 168 def encode_pdf(path) file_content = File.binread(path) base64_string = Base64.strict_encode64(file_content) "data:application/pdf;base64,#{base64_string}" end |
#extra_options(options, messages = nil) ⇒ Object
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
# File 'lib/scout/llm/backends/default.rb', line 49 def (, = nil) format = IndiferentHash. , :format = IndiferentHash.pull_keys , :reasoning = [:reasoning] if .include?(:reasoning) [:reasoning] = if .any? = IndiferentHash.pull_keys , :text = [:text] if .include?(:text) = [:text] if && .include?(:text) [:text] = if .any? [:text] = process_format format if format end |
#extract_tools(messages, tools = []) ⇒ Object
283 284 285 286 287 288 289 290 291 292 |
# File 'lib/scout/llm/backends/default.rb', line 283 def extract_tools(, tools = []) .collect do || if [:role].to_s == 'tool' tools << [:content] nil else end end.compact end |
#format_messages(messages) ⇒ Object
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 |
# File 'lib/scout/llm/backends/default.rb', line 266 def () = IndiferentHash.setup() last_id = nil = .collect do || if [:role] == 'function_call' format_tool_call() elsif [:role] == 'function_call_output' m = format_tool_output(, last_id) last_id = m[:call_id] m else format_other() end end.flatten.compact end |
#format_other(message) ⇒ Object
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 |
# File 'lib/scout/llm/backends/default.rb', line 175 def format_other() role = [:role] case role.to_s when 'image' path = [:content] path = Chat.find_file path if Open.remote?(path) { role: :user, content: { type: :input_image, image_url: path } } elsif Open.exists?(path) path = encode_image(path) { role: :user, content: [{ type: :input_image, image_url: path }] } else raise "Image does not exist in #{path}" end when 'pdf' path = original_path = [:content] if Open.remote?(path) { role: :user, content: { type: :input_file, file_url: path } } elsif Open.exists?(path) data = encode_pdf(path) { role: :user, content: [{ type: :input_file, file_data: data, filename: File.basename(path) }] } else raise "PDF does not exist in #{path}" end when 'websearch' { role: :tool, content: { type: 'web_search_preview' } } when 'previous_response_id' nil else end end |
#format_tool_call(message) ⇒ Object
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 |
# File 'lib/scout/llm/backends/default.rb', line 233 def format_tool_call() info = JSON.parse([:content]) IndiferentHash.setup info name = info[:name] || IndiferentHash.dig(info, :function, :name) IndiferentHash.setup info id = last_id = info[:id] || "fc_#{rand(1000).to_s}" id = id.sub(/^fc_/, '') arguments_json = (info[:arguments] || {}.to_json) arguments_json = arguments_json.to_json unless String === arguments_json IndiferentHash.setup({ 'type' => 'function_call', 'status' => 'completed', 'name' => name, 'arguments' => arguments_json, 'call_id' => id }) end |
#format_tool_definitions(tools) ⇒ Object
{{{ TOOLS
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 |
# File 'lib/scout/llm/backends/default.rb', line 211 def format_tool_definitions(tools) return [] if tools.nil? tools.values.collect do |obj, definition| definition = obj if Hash === obj definition definition = case definition[:function] when Hash definition.merge(definition.delete :function) else definition end definition = IndiferentHash.add_defaults definition, type: :function definition[:parameters].delete :defaults if definition[:parameters] definition end end |
#format_tool_output(message, last_id = nil) ⇒ Object
252 253 254 255 256 257 258 259 260 261 262 263 264 |
# File 'lib/scout/llm/backends/default.rb', line 252 def format_tool_output(, last_id = nil) info = JSON.parse([:content]) info = IndiferentHash.setup info id = info[:id] || last_id raise "No id #{Log.fingerprint }" if id.nil? id = id.sub(/^fc_/, '') { 'type' => 'function_call_output', 'output' => info[:content], 'call_id' => id } end |
#gather_response(server, id) ⇒ Object
464 465 466 467 468 469 470 471 472 473 474 |
# File 'lib/scout/llm/backends/default.rb', line 464 def gather_response(server, id) TmpFile.with_file do |file| begin CMD.cmd("scp #{server}:.scout/var/query/response/#{ id }.json #{ file }") JSON.parse(Open.read(file)) rescue sleep 1 retry end end end |
#image(question, options = {}, &block) ⇒ Object
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 |
# File 'lib/scout/llm/backends/default.rb', line 542 def image(question, = {}, &block) = LLM.chat(question) = .merge LLM. tools = LLM.tools associations = LLM.associations client, url, key, model, log_errors, , format = IndiferentHash. , :client, :url, :key, :model, :log_errors, :return_messages, :format, log_errors: true if client.nil? url ||= Scout::Config.get(:url, :openai_ask, :ask, :openai, env: 'OPENAI_URL') key ||= LLM.get_url_config(:key, url, :openai_ask, :ask, :openai, env: 'OPENAI_KEY') client = LLM::OpenAI.client url, key, log_errors end if model.nil? url ||= Scout::Config.get(:url, :openai_ask, :ask, :openai, env: 'OPENAI_URL') model ||= LLM.get_url_config(:model, url, :openai_ask, :ask, :openai, env: 'OPENAI_MODEL', default: 'gpt-image-1') end = process_input input = [] parameters = {} .each do || input << end parameters[:prompt] = LLM.print(input) response = client.images.generate(parameters: parameters) response end |
#messages(question, options) ⇒ Object
{{{ Processing
318 319 320 321 322 323 324 325 326 327 328 |
# File 'lib/scout/llm/backends/default.rb', line 318 def (question, ) = LLM.chat(question) .merge! LLM. if .delete :websearch << { role: 'websearch', content: true } end end |
#parse_tool_call(info) ⇒ Object
353 354 355 356 357 358 359 360 361 |
# File 'lib/scout/llm/backends/default.rb', line 353 def parse_tool_call(info) arguments, call_id, id, name = IndiferentHash. info.dup, :arguments, :call_id, :id, :name arguments = begin JSON.parse arguments rescue Log.debug 'Parsing call error. Tool call:' + "\n" + JSON.pretty_generate(info) end if String === arguments { name: name, arguments: arguments, id: call_id || id } end |
#prepare_client(options, messages = nil) ⇒ Object
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
# File 'lib/scout/llm/backends/default.rb', line 66 def prepare_client(, = nil) = () client = IndiferentHash. , :client if client.nil? Log.debug "Client options: #{.inspect}" client = self.client(.merge()) else Log.debug "Reusing client: #{Log.fingerprint client}" end [:model] ||= [:model] (, ) client end |
#process_format(format) ⇒ Object
{{{ FORMAT
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 |
# File 'lib/scout/llm/backends/default.rb', line 101 def process_format(format) case format when :json, :json_object, 'json', 'json_object' { format: { type: 'json_object' } } when String, Symbol { format: { type: format } } when Hash IndiferentHash.setup format if format.include?('format') format elsif format['type'] == 'json_schema' { format: format } else if !format.include?('properties') format = IndiferentHash.setup({ properties: format }) end properties = format['properties'] new_properties = {} properties.each do |name, info| case info when Symbol, String new_properties[name] = { type: info } when Array new_properties[name] = { type: info[0], description: info[1], default: info[2] } else new_properties[name] = info end end format['properties'] = new_properties required = format['properties'].reject { |_p, i| i[:default] }.collect { |p, _i| p } name = format.include?('name') ? format.delete('name') : 'response' format['type'] ||= 'object' format[:additionalProperties] = required.empty? ? { type: :string } : false format[:required] = required { format: { name: name, type: 'json_schema', schema: format } } end end end |
#process_response(messages, response, tools, options, &block) ⇒ Object
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 |
# File 'lib/scout/llm/backends/default.rb', line 363 def process_response(, response, tools, , &block) tool_calls = response['output'].collect do |output| case output['type'] when 'function_call', 'mcp_call' self.parse_tool_call(output.dup) end end.compact tool_call_outputs = LLM.process_calls(tools, tool_calls, &block) output = response['output'].collect do |output| case output['type'] when 'message' output['content'].collect do |content| case content['type'] when 'output_text' IndiferentHash.setup({ role: 'assistant', content: content['text'] }) end end when 'reasoning' next when 'function_call', 'mcp_call' [tool_call_outputs.shift, tool_call_outputs.shift] when 'web_search_call' next else eee response eee output raise end end.compact.flatten.collect { |o| IndiferentHash.setup o } [:previous_response_id] = response['id'] unless [:previous_response].to_s == 'false' || FalseClass === [:previous_response_id] output end |
#query(client, messages, tools = [], parameters = {}) ⇒ Object
86 87 88 89 90 91 92 93 94 95 96 97 |
# File 'lib/scout/llm/backends/default.rb', line 86 def query(client, , tools = [], parameters = {}) formatted_tools = self.format_tool_definitions tools = extract_tools(, formatted_tools) parameters[:tools] = formatted_tools if formatted_tools.any? parameters[:input] = parameters = parameters.except(:previous_response_id) if FalseClass === parameters[:previous_response_id] parameters = parameters.except(:previous_response_id) if parameters[:previous_response] == 'false' client.responses.create(parameters: parameters.except(:previous_response)) end |
#reasoning(response, current_meta = nil) ⇒ Object
447 448 449 450 451 452 |
# File 'lib/scout/llm/backends/default.rb', line 447 def reasoning(response, = nil) reasoning_content = response.dig('choices', 0, 'message', 'reasoning_content') reasoning_content = reasoning_content.gsub("\n", ' ') if String === reasoning_content Log.medium "Reasoning:\n" + Log.color(:cyan, reasoning_content) if reasoning_content reasoning_content end |
#tools(messages, options) ⇒ Object
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 |
# File 'lib/scout/llm/backends/default.rb', line 294 def tools(, ) tools = .delete :tools case tools when Array tools = tools.inject({}) do |acc, definition| IndiferentHash.setup definition name = definition.dig('name') || definition.dig('function', 'name') acc.merge(name => definition) end when nil tools = {} end tools.merge!(LLM.tools ) tools.merge!(LLM.associations ) Log.high "Tools: #{Log.fingerprint tools.keys}" if tools tools end |
#update_meta(response, current_meta = nil) ⇒ Object
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 |
# File 'lib/scout/llm/backends/default.rb', line 400 def (response, = nil) = {} if .nil? pattern = { 'pt+': [['usage','prompt_tokens']], 'ct+': [['usage','completion_tokens']], 'tt+': [['usage','total_tokens']], } = {} pattern.each do |name,key_list| name = name.to_s key_list.each do |keys| value = response.dig *keys next unless value if name.end_with?('+') name = name[0..-2] [name] = value session_name = name + '_s' [session_name] ||= Thread.current[session_name] || 0 [session_name] += value Thread.current[session_name] = [session_name] .delete name if [name] == [session_name] else value = value.gsub(/\s+/,' ') if String === value [name] = value end end end new = {} .each do |name,value| if name.end_with?('_s') chat_name = name.sub(/_s$/,'_c') current_value = [chat_name] || [name] || 0 new[chat_name] = current_value + value end end .merge! new end |
#upload_messages(server, messages, options) ⇒ Object
455 456 457 458 459 460 461 462 |
# File 'lib/scout/llm/backends/default.rb', line 455 def (server, , ) id = Misc.digest() .unshift({role: 'backend', content: self::TAG}) TmpFile.with_file [, .except(:client)].to_json do |file| CMD.cmd("scp #{file} #{server}:.scout/var/query/#{ id }.json") end id end |