Module: LLM::Backend::ClassMethods

Included in:
Anthropic, Huggingface, OLlama, OpenAI, OpenWebUI, Responses, VLLM
Defined in:
lib/scout/llm/backends/default.rb

Instance Method Summary collapse

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, options = {}, &block)
  original_options = options.dup

  return_messages, log_response, current_meta, relay, process = IndiferentHash.process_options options, 
    :return_messages, :log_response, :current_meta, :relay, :process,
    return_messages: false, log_response: true

  messages = self.messages question, options
  
  if relay
    id = upload_messages(relay,  messages, options)
    response = gather_response(relay, id)
    IndiferentHash.setup(response)
    client = prepare_client options, messages
    formatted_messages = format_messages(messages)
    tools = tools(formatted_messages, options)
  else

    client = prepare_client options, messages
    formatted_messages = format_messages(messages)
    tools = tools(formatted_messages, options)

    response = begin
                 Log.medium "Calling #{self}: #{Log.fingerprint(options.except(:tools))}}"
                 query(client, formatted_messages, tools, options)
               rescue Exception
                 Log.debug 'Asking error. Options: ' + "\n" + JSON.pretty_generate(options.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 messages, response, tools, options, &block

  if log_response
    meta = self.update_meta response, current_meta
    meta['reas'] = reasoning if reasoning
  end

  output = chain_tools messages, output, tools, options.merge(client: client, tools: tools, log_response: log_response, current_meta: meta, relay: relay)

  output.unshift({role: :meta, content: Chat.serialize_meta(meta)}) if log_response && meta && meta.any?

  if output.last[:role] != :previous_response_id && options[:previous_response_id]
    output << { role: :previous_response_id, content: options[:previous_response_id] }
  end

  if return_messages
    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(messages, output, tools, options = {}, &block)
  previous_response_id = options[: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, options.except(:tool_choice).merge(return_messages: true, previous_response_id: previous_response_id), &block)
      else
        output + ask(messages + output, options.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(options)
  url, key, model, api_version, log_errors, request_timeout = IndiferentHash.process_options options,
    :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 client_options(options)
  url, key, model, api_version, tag, default_model, log_errors, request_timeout = IndiferentHash.process_options options,
    :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 embed(text, options = {})
  client = prepare_client options
  embed_query client, text, options
end

#embed_query(client, text, parameters = {}) ⇒ Object



576
577
578
579
580
581
# File 'lib/scout/llm/backends/default.rb', line 576

def embed_query(client, text, parameters = {})
  parameters[:text] = text
  response = client.embeddings(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 extra_options(options, messages = nil)
  format = IndiferentHash.process_options options, :format

  reasoning_options = IndiferentHash.pull_keys options, :reasoning
  reasoning_options = reasoning_options[:reasoning] if reasoning_options.include?(:reasoning)
  options[:reasoning] = reasoning_options if reasoning_options.any?

  text_options = IndiferentHash.pull_keys options, :text
  text_options = reasoning_options[:text] if reasoning_options.include?(:text)
  text_options = text_options[:text] if text_options && text_options.include?(:text)
  options[:text] = text_options if text_options.any?

  options[:text] = process_format format if format

  options
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(messages, tools = [])
  messages.collect do |message|
    if message[:role].to_s == 'tool'
      tools << message[:content]
      nil
    else
      message
    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 format_messages(messages)
  messages = IndiferentHash.setup(messages)

  last_id = nil
  messages = messages.collect do |message|
    if message[:role] == 'function_call'
      format_tool_call(message)
    elsif message[:role] == 'function_call_output'
      m = format_tool_output(message, last_id)
      last_id = m[:call_id]
      m
    else
      format_other(message)
    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(message)
  role = message[:role]

  case role.to_s
  when 'image'
    path = message[: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 = message[: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
    message
  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(message)
  info = JSON.parse(message[: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(message, last_id = nil)
  info = JSON.parse(message[:content])
  info = IndiferentHash.setup info
  id = info[:id] || last_id
  raise "No id #{Log.fingerprint message}" 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, options = {}, &block)
  messages = LLM.chat(question)
  options = options.merge LLM.options messages
  tools = LLM.tools messages
  associations = LLM.associations messages

  client, url, key, model, log_errors, return_messages, format = IndiferentHash.process_options options,
    :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

  messages = process_input messages
  input = []
  parameters = {}
  messages.each do |message|
    input << message
  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 messages(question, options)
  messages = LLM.chat(question)

  options.merge! LLM.options messages

  if options.delete :websearch
    messages << { role: 'websearch', content: true }
  end

  messages
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.process_options 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(options, messages = nil)
  client_options = client_options(options)

  client = IndiferentHash.process_options options, :client

  if client.nil?
    Log.debug "Client options: #{client_options.inspect}"

    client = self.client(options.merge(client_options))
  else
    Log.debug "Reusing client: #{Log.fingerprint client}"
  end

  options[:model] ||= client_options[:model]

  extra_options(options, messages)

  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(messages, response, tools, options, &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 }

  options[:previous_response_id] = response['id'] unless options[:previous_response].to_s == 'false' || FalseClass === options[: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, messages, tools = [], parameters = {})
  formatted_tools = self.format_tool_definitions tools

  messages = extract_tools(messages, formatted_tools)

  parameters[:tools] = formatted_tools if formatted_tools.any?
  parameters[:input] = messages

  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, current_meta = 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(messages, options)
  tools = options.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 messages)
  tools.merge!(LLM.associations messages)

  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 update_meta(response, current_meta = nil)
  current_meta = {} if current_meta.nil?

  pattern = {
    'pt+': [['usage','prompt_tokens']],
    'ct+': [['usage','completion_tokens']],
    'tt+': [['usage','total_tokens']],
  }

  meta = {}
  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]
        meta[name] = value
        session_name = name + '_s'

        meta[session_name] ||= Thread.current[session_name] || 0
        meta[session_name] += value

        Thread.current[session_name] = meta[session_name]
        meta.delete name if meta[name] == meta[session_name]
      else
        value = value.gsub(/\s+/,' ') if String === value
        meta[name] = value
      end
    end
  end

  new = {}
  meta.each do |name,value|
    if name.end_with?('_s')
      chat_name = name.sub(/_s$/,'_c')
      current_value = current_meta[chat_name] || current_meta[name] || 0
      new[chat_name] = current_value + value
    end
  end

  meta.merge! new

  meta
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 upload_messages(server, messages, options)
  id = Misc.digest(messages)
  messages.unshift({role: 'backend', content: self::TAG})
  TmpFile.with_file [messages, options.except(:client)].to_json do |file|
    CMD.cmd("scp #{file} #{server}:.scout/var/query/#{ id }.json")
  end
  id
end