Module: LLM::Backend::ClassMethods

Included in:
Anthropic, GLM, 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



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
541
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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
# File 'lib/scout/llm/backends/default.rb', line 481

def ask(question, options = {}, &block)
  original_options = options.dup

  return_messages, log_response, current_meta, relay, process, prompt_strategies = IndiferentHash.process_options options, 
    :return_messages, :log_response, :current_meta, :relay, :process, :prompt_strategies,
    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)
    formatted_prompt = format_messages(messages)
    tools = tools(formatted_prompt, options)
  else

    client = prepare_client options, messages
    prompt = Chat.prepare_prompt(messages, prompt_strategies)
    formatted_prompt = format_messages(prompt)
    tools = tools(formatted_prompt, options)

    response = begin
                 Log.medium "Calling #{self}: #{Log.fingerprint(options.except(:tools))}}"
                 query(client, formatted_prompt, tools, options)
               rescue Exception => e
                 Log.debug 'Asking error. Options: ' + "\n" + JSON.pretty_generate(options.except(:tools))
                 begin
                   tmpfile = TmpFile.tmp_file 
                   Open.write tmpfile + ".chat", Chat.print(messages)
                   Open.write tmpfile + ".options", options.except(:messages, :tools).to_json
                   Open.write tmpfile + ".meta", current_meta.to_json
                   Log.warn "Messages and options saved in #{tmpfile}"
                   e.extend LLM::Backend::BackendException
                   e.chat tmpfile
                 rescue
                 end

                 raise e
               end
  end

  timestamp = Chat.timestamp

  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 = begin
             process_response messages, response, tools, options, &block
           rescue Exception => e

             Log.debug 'Processing response error. Options: ' + "\n" + JSON.pretty_generate(options.except(:tools))
             begin
               tmpfile = TmpFile.tmp_file 
               previous_response_id_error = options.delete
               if previous_response_id_error
                 message.unshift IndiferentHash.setup({role: :previous_response_id, content: previous_response_id_error})
               end
               Open.write tmpfile + ".chat", Chat.print(messages)
               Open.write tmpfile + ".options", options.except(:messages, :tools).to_json
               Open.write tmpfile + ".meta", current_meta.to_json
               Log.warn "Messages and options saved in #{tmpfile}"
               e.extend LLM::Backend::BackendException
               e.chat tmpfile
             rescue
             end
             raise e
           end

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

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

  if log_response && meta && meta.any?
    # The meta is about to become the first message of a segment that
    # runs until the next meta (a chained tool-call ask, whose own meta
    # was already unshifted inside `output` by the recursive call) or
    # the end of the response.  A reasoning-only request produces no
    # message at all, so its meta covers zero messages: `output` is
    # empty, or starts with the nested meta.  Such rounds are real cost
    # (~7% of prompt tokens in one measured agent log) with nothing to
    # show for it, so mark them explicitly instead of leaving a bare
    # meta for the reader to puzzle over.  `Chat.trace_indices` derives
    # the same fact independently; the marker only makes the persisted
    # meta self-explanatory and is inert for accounting.
    #
    # ScoutCoder: orphan is only meaningful for the meta that opens a
    # segment. Chained tool calls recurse into `ask`, and their metas
    # were already unshifted onto `output` before this point, so the
    # first message of `output` decides: an empty list, or one starting
    # with the nested meta, means this round covered nothing. Do not
    # recompute this from `trace_indices` here: that helper sees the
    # whole chat (parent copies included) and does not exist on this
    # path.
    meta['orphan'] = true if output.empty? || output.first[:role].to_s == 'meta'

    output.unshift({role: :meta, content: Chat.serialize_meta(meta)})
  end

  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



342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
# File 'lib/scout/llm/backends/default.rb', line 342

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



34
35
36
37
38
39
40
# File 'lib/scout/llm/backends/default.rb', line 34

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: 12000, 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.to_i)
end

#client_options(options) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
# File 'lib/scout/llm/backends/default.rb', line 42

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, request_timeout: request_timeout }.reject { |_k, v| v.nil? }
end

#embed(text, options = {}) ⇒ Object



623
624
625
626
# File 'lib/scout/llm/backends/default.rb', line 623

def embed(text, options = {})
  client = prepare_client options
  embed_query client, text, options
end

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



616
617
618
619
620
621
# File 'lib/scout/llm/backends/default.rb', line 616

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



155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
# File 'lib/scout/llm/backends/default.rb', line 155

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



173
174
175
176
177
178
# File 'lib/scout/llm/backends/default.rb', line 173

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



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/scout/llm/backends/default.rb', line 54

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



290
291
292
293
294
295
296
297
298
299
# File 'lib/scout/llm/backends/default.rb', line 290

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



273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
# File 'lib/scout/llm/backends/default.rb', line 273

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



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
208
209
210
211
212
# File 'lib/scout/llm/backends/default.rb', line 180

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



240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
# File 'lib/scout/llm/backends/default.rb', line 240

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



216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
# File 'lib/scout/llm/backends/default.rb', line 216

def format_tool_definitions(tools)
  return [] if tools.nil?

  tools.values.collect do |obj, definition|
    definition = obj if Hash === obj
    definition

    next definition if definition.keys.collect{|k| k.to_s } == ['type']

    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



259
260
261
262
263
264
265
266
267
268
269
270
271
# File 'lib/scout/llm/backends/default.rb', line 259

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



469
470
471
472
473
474
475
476
477
478
479
# File 'lib/scout/llm/backends/default.rb', line 469

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



605
606
607
608
609
610
611
612
613
614
# File 'lib/scout/llm/backends/default.rb', line 605

def image(question, options = {}, &block)
  messages = ask(question, options.merge({tools: [{type: 'image_generation'}], return_messages: true}), &block)

  base64_image = begin
                   messages.select{|info| info[:role] == 'image' }.first['content']['result']
                 rescue
                   Log.warn 'Image error: ' + "\n" + JSON.pretty_generate(messages)
                   raise $!
                 end
end

#messages(question, options) ⇒ Object

{{{ Processing



330
331
332
333
334
335
336
337
338
339
340
# File 'lib/scout/llm/backends/default.rb', line 330

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



365
366
367
368
369
370
371
372
373
# File 'lib/scout/llm/backends/default.rb', line 365

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



71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/scout/llm/backends/default.rb', line 71

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



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
# File 'lib/scout/llm/backends/default.rb', line 106

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



375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
# File 'lib/scout/llm/backends/default.rb', line 375

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 'image_generation_call'
      {role: 'image', content: output}
    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



91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/scout/llm/backends/default.rb', line 91

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



449
450
451
452
453
454
455
456
457
# File 'lib/scout/llm/backends/default.rb', line 449

def reasoning(response, current_meta = nil)
  begin
    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
  rescue
  end
end

#tools(messages, options) ⇒ Object



301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
# File 'lib/scout/llm/backends/default.rb', line 301

def tools(messages, options)
  tools = options.delete :tools

  case tools
  when Array
    tools = tools.inject({}) do |acc, definition|
      next definition unless Hash === definition
      IndiferentHash.setup definition
      name = definition.dig('name') || definition.dig('function', 'name')
      if name
        acc.merge(name => definition)
      else
        acc.merge(definition[:type] => definition)
      end
    end
  when nil
    tools = {}
  end

  tools.merge!(LLM.tools messages)
  tools.merge!(LLM.associations messages)

  Log.medium "Tools: #{Log.fingerprint tools.keys}" if tools

  tools
end

#update_meta(response, current_meta = nil) ⇒ Object



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
446
447
# File 'lib/scout/llm/backends/default.rb', line 414

def update_meta(response, current_meta = nil)
  current_meta = {} if current_meta.nil?
  IndiferentHash.setup current_meta

  # Extract normalised token fields from the provider usage hash.
  # Chat.normalize_usage handles all known backend response formats
  # (OpenAI Chat, Responses API, GLM, Anthropic) and returns a flat
  # hash keyed by the short names defined in Chat::TOKEN_KEYS.
  tokens = Chat.normalize_usage(response.dig('usage')).reject { |_name, value| value.nil? }

  # Keep the provider values for this request separate from aggregate
  # values.  In particular, do not add the running thread/session total
  # to the chat total: doing that on every request produces the observed
  # triangular (and, after aggregation, worse) growth.
  meta = IndiferentHash.setup(tokens.dup)
  # A lineage digest identifies copied conversational history, not an
  # actual backend request. Persist a request identity so provenance can
  # distinguish two genuinely repeated, otherwise identical inferences.
  meta['inference_id'] = SecureRandom.uuid
  meta['provider_response_id'] = response['id'] if response['id']
  tokens.each do |name, value|
    session_name = name + '_s'
    Thread.current[session_name] = Thread.current[session_name].to_i + value.to_i
    meta[session_name] = Thread.current[session_name]
  end

  Chat::TOKEN_KEYS.each do |name|
    meta["#{name}_c"] = current_meta["#{name}_c"].to_i + tokens[name].to_i
  end

  Log.medium "Meta: #{Log.fingerprint meta}"

  meta
end

#upload_messages(server, messages, options) ⇒ Object



460
461
462
463
464
465
466
467
# File 'lib/scout/llm/backends/default.rb', line 460

def upload_messages(server, messages, options)
  id = Misc.digest(messages)
  messages.unshift({role: 'backend', content: self::TAG})
  TmpFile.with_file [messages, options].to_json do |file|
    CMD.cmd("scp #{file} #{server}:.scout/var/query/#{ id }.json")
  end
  id
end