Module: AIA::Directives::Models

Defined in:
lib/aia/directives/models.rb

Class Method Summary collapse

Class Method Details

.aliasesObject



11
12
13
# File 'lib/aia/directives/models.rb', line 11

def aliases
  @aliases ||= {}
end

.available_models(args = nil, context_manager = nil) ⇒ Object Also known as: am, available, models, all_models, llms



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/aia/directives/models.rb', line 32

def self.available_models(args = nil, context_manager = nil)
  # Check if we're using a local provider
  current_models = AIA.config.model
  current_models = [current_models] if current_models.is_a?(String)

  # Extract model names (handles both String and Hash formats)
  model_names = current_models.map do |m|
    m.is_a?(Hash) ? m[:model] : m
  end

  using_local_provider = model_names.any? { |m| m.start_with?('ollama/', 'lms/') }

  if using_local_provider
    show_local_models(model_names, args)
  else
    show_rubyllm_models(args)
  end

  ""
end

.build_aliases(methods) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/aia/directives/models.rb', line 15

def build_aliases(methods)
  methods.each do |method_name|
    method = self.method(method_name)
    aliases[method_name] = []

    methods.each do |other_method_name|
      next if method_name == other_method_name
      other_method = self.method(other_method_name)

      if method == other_method
        aliases[method_name] << other_method_name
      end
    end
  end
end

.compare(args, context_manager = nil) ⇒ Object Also known as: cmp



390
391
392
393
394
395
396
397
398
399
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
# File 'lib/aia/directives/models.rb', line 390

def self.compare(args, context_manager = nil)
  return 'Error: No prompt provided for comparison' if args.empty?

  # Parse arguments - first arg is the prompt, --models flag specifies models
  prompt = nil
  models = []

  i = 0
  while i < args.length
    if args[i] == '--models' && i + 1 < args.length
      models = args[i + 1].split(',')
      i += 2
    else
      prompt ||= args[i]
      i += 1
    end
  end

  return 'Error: No prompt provided for comparison' unless prompt
  return 'Error: No models specified. Use --models model1,model2,model3' if models.empty?

  puts "\nComparing responses for: #{prompt}\n"
  puts '=' * 80

  results = {}

  models.each do |model_name|
    model_name.strip!
    puts "\nšŸ¤– **#{model_name}:**"
    puts '-' * 40

    begin
      # Create a temporary chat instance for this model
      chat = RubyLLM.chat(model: model_name)
      response = chat.ask(prompt)
      content = response.content

      puts content
      results[model_name] = content
    rescue StandardError => e
      error_msg = "Error with #{model_name}: #{e.message}"
      puts error_msg
      results[model_name] = error_msg
    end
  end

  puts '\n' + '=' * 80
  puts "\nComparison complete!"

  ''
end

.descriptionsObject



7
8
9
# File 'lib/aia/directives/models.rb', line 7

def descriptions
  @descriptions ||= {}
end

.format_bytes(bytes) ⇒ Object



159
160
161
162
163
164
165
166
167
# File 'lib/aia/directives/models.rb', line 159

def self.format_bytes(bytes)
  units = ['B', 'KB', 'MB', 'GB', 'TB']
  return "0 B" if bytes.zero?

  exp = (Math.log(bytes) / Math.log(1024)).to_i
  exp = [exp, units.length - 1].min

  "%.1f %s" % [bytes.to_f / (1024 ** exp), units[exp]]
end

.help(args = nil, context_manager = nil) ⇒ Object



217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
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
# File 'lib/aia/directives/models.rb', line 217

def self.help(args = nil, context_manager = nil)
  puts
  puts "Available Directives"
  puts "===================="
  puts

  # Manual descriptions for all directives
  directive_descriptions = {
    # Configuration directives
    'config' => 'View or set configuration values',
    'model' => 'View or change the AI model',
    'temperature' => 'Set the temperature parameter for AI responses',
    'top_p' => 'Set the top_p parameter for AI responses',
    'clear' => 'Clear the conversation context',
    'review' => 'Display the current conversation context with checkpoint markers',
    'checkpoint' => 'Create a named checkpoint of the current context',
    'restore' => 'Restore context to a previous checkpoint',
    'checkpoints_list' => 'List all available checkpoints',

    # Utility directives
    'tools' => 'List available tools (optional filter by name substring)',
    'next' => 'Set the next prompt in the sequence',
    'pipeline' => 'Set or view the prompt workflow sequence',
    'terse' => 'Add instruction for concise responses',
    'robot' => 'Display ASCII robot art',

    # Execution directives
    'ruby' => 'Execute Ruby code',
    'shell' => 'Execute shell commands',
    'say' => 'Use text-to-speech to speak the text',

    # Web and File directives
    'webpage' => 'Fetch and include content from a webpage',
    'include' => 'Include content from a file',
    'include_file' => 'Include file content (internal use)',
    'included_files' => 'List files that have been included',
    'included_files=' => 'Set the list of included files',

    # Model directives
    'available_models' => 'List all available AI models',
    'compare' => 'Compare responses from multiple models',
    'help' => 'Show this help message',

    # Aliases (these get their descriptions from main directive)
    'cfg' => nil,  # alias for config
    'temp' => nil, # alias for temperature
    'topp' => nil, # alias for top_p
    'context' => nil, # alias for review
    'ckp' => nil, # alias for checkpoint
    'cp' => nil, # alias for checkpoint
    'workflow' => nil, # alias for pipeline
    'rb' => nil, # alias for ruby
    'sh' => nil, # alias for shell
    'web' => nil, # alias for webpage
    'website' => nil, # alias for webpage
    'import' => nil, # alias for include
    'models' => nil, # alias for available_models
    'all_models' => nil, # alias for available_models
    'am' => nil, # alias for available_models
    'llms' => nil, # alias for available_models
    'available' => nil, # alias for available_models
    'cmp' => nil, # alias for compare
  }

  # Get all registered directive modules from the Registry
  all_modules = [
    AIA::Directives::WebAndFile,
    AIA::Directives::Utility,
    AIA::Directives::Configuration,
    AIA::Directives::Execution,
    AIA::Directives::Models,
    AIA::Directives::Checkpoint
  ]

  all_directives = {}
  excluded_methods = ['run', 'initialize', 'private?', 'descriptions', 'aliases', 'build_aliases',
                     'desc', 'method_added', 'register_directive_module', 'process',
                     'directive?', 'prefix_size', 'reset!', 'checkpoint_names',
                     'checkpoint_positions', 'get_chats', 'deep_copy_message',
                     'format_message_content', 'checkpoints', 'checkpoint_counter',
                     'last_checkpoint_name', 'checkpoints=', 'checkpoint_counter=',
                     'last_checkpoint_name=']

  # Collect directives from all modules
  all_modules.each do |mod|
    methods = mod.methods(false).map(&:to_s).reject { |m| excluded_methods.include?(m) }

    methods.each do |method|
      # Skip if this is an alias (has nil description)
      next if directive_descriptions.key?(method) && directive_descriptions[method].nil?

      description = directive_descriptions[method] || method.gsub('_', ' ').capitalize

      all_directives[method] = {
        module: mod.name.split('::').last,
        description: description,
        aliases: []
      }
    end
  end

  # Manually map known aliases
  alias_mappings = {
    'config' => ['cfg'],
    'temperature' => ['temp'],
    'top_p' => ['topp'],
    'review' => ['context'],
    'checkpoint' => ['ckp', 'cp'],
    'pipeline' => ['workflow'],
    'ruby' => ['rb'],
    'shell' => ['sh'],
    'webpage' => ['web', 'website'],
    'include' => ['import'],
    'available_models' => ['models', 'all_models', 'am', 'llms', 'available'],
    'compare' => ['cmp']
  }

  # Apply alias mappings
  alias_mappings.each do |directive, aliases|
    if all_directives[directive]
      all_directives[directive][:aliases] = aliases
    end
  end

  # Sort and display directives by category
  categories = {
    'Configuration' => ['config', 'model', 'temperature', 'top_p', 'clear', 'review', 'checkpoint', 'restore', 'checkpoints_list'],
    'Utility' => ['tools', 'next', 'pipeline', 'terse', 'robot', 'help'],
    'Execution' => ['ruby', 'shell', 'say'],
    'Web & Files' => ['webpage', 'include'],
    'Models' => ['available_models', 'compare']
  }

  categories.each do |category, directives|
    puts "#{category}:"
    puts "-" * category.length

    directives.each do |directive|
      info = all_directives[directive]
      next unless info

      if info[:aliases] && !info[:aliases].empty?
        with_prefix = info[:aliases].map { |m| PromptManager::Prompt::DIRECTIVE_SIGNAL + m }
        alias_text = " (aliases: #{with_prefix.join(', ')})"
      else
        alias_text = ""
      end

      puts "  //#{directive}#{alias_text}"
      puts "      #{info[:description]}"
      puts
    end
  end

  # Show any uncategorized directives
  categorized = categories.values.flatten
  uncategorized = all_directives.keys - categorized - ['include_file', 'included_files', 'included_files=']

  if uncategorized.any?
    puts "Other:"
    puts "------"
    uncategorized.sort.each do |directive|
      info = all_directives[directive]
      puts "  //#{directive}"
      puts "      #{info[:description]}"
      puts
    end
  end

  puts "\nTotal: #{all_directives.size} directives available"
  ""
end

.show_lms_models(api_base, args) ⇒ Object



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
# File 'lib/aia/directives/models.rb', line 118

def self.show_lms_models(api_base, args)
  begin
    uri = URI("#{api_base.gsub(%r{/v1/?$}, '')}/v1/models")
    response = Net::HTTP.get_response(uri)

    unless response.is_a?(Net::HTTPSuccess)
      puts "āŒ Cannot connect to LM Studio at #{api_base}"
      return
    end

    data = JSON.parse(response.body)
    models = data['data'] || []

    if models.empty?
      puts "No LM Studio models found"
      return
    end

    puts "LM Studio Models (#{api_base}):"
    puts "-" * 60

    counter = 0
    models.each do |model|
      name = model['id']
      entry = "- lms/#{name}"

      # Apply query filter if provided
      if args.nil? || args.empty? || args.any? { |q| entry.downcase.include?(q.downcase) }
        puts entry
        counter += 1
      end
    end

    puts
    puts "#{counter} LM Studio model(s) available"
    puts
  rescue StandardError => e
    puts "āŒ Error fetching LM Studio models: #{e.message}"
  end
end

.show_local_models(current_models, args) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/aia/directives/models.rb', line 53

def self.show_local_models(current_models, args)
  require 'net/http'
  require 'json'

  puts "\nLocal LLM Models:"
  puts

  current_models.each do |model_spec|
    if model_spec.start_with?('ollama/')
      # Ollama uses its native API, not /v1
      api_base = ENV.fetch('OLLAMA_API_BASE', 'http://localhost:11434')
      # Remove /v1 suffix if present
      api_base = api_base.gsub(%r{/v1/?$}, '')
      show_ollama_models(api_base, args)
    elsif model_spec.start_with?('lms/')
      api_base = ENV.fetch('LMS_API_BASE', 'http://localhost:1234')
      show_lms_models(api_base, args)
    end
  end
end

.show_ollama_models(api_base, args) ⇒ Object



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
# File 'lib/aia/directives/models.rb', line 74

def self.show_ollama_models(api_base, args)
  begin
    uri = URI("#{api_base}/api/tags")
    response = Net::HTTP.get_response(uri)

    unless response.is_a?(Net::HTTPSuccess)
      puts "āŒ Cannot connect to Ollama at #{api_base}"
      return
    end

    data = JSON.parse(response.body)
    models = data['models'] || []

    if models.empty?
      puts "No Ollama models found"
      return
    end

    puts "Ollama Models (#{api_base}):"
    puts "-" * 60

    counter = 0
    models.each do |model|
      name = model['name']
      size = model['size'] ? format_bytes(model['size']) : 'unknown'
      modified = model['modified_at'] ? Time.parse(model['modified_at']).strftime('%Y-%m-%d') : 'unknown'

      entry = "- ollama/#{name} (size: #{size}, modified: #{modified})"

      # Apply query filter if provided
      if args.nil? || args.empty? || args.any? { |q| entry.downcase.include?(q.downcase) }
        puts entry
        counter += 1
      end
    end

    puts
    puts "#{counter} Ollama model(s) available"
    puts
  rescue StandardError => e
    puts "āŒ Error fetching Ollama models: #{e.message}"
  end
end

.show_rubyllm_models(args) ⇒ Object



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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
# File 'lib/aia/directives/models.rb', line 169

def self.show_rubyllm_models(args)
  query = args

  if query && 1 == query.size
    query = query.first.split(',')
  end

  header = "\nAvailable LLMs"
  header += " for #{query.join(' and ')}" if query

  puts header + ':'
  puts

  q1 = query ? query.select { |q| q.include?('_to_') } : []
  q2 = query ? query.reject { |q| q.include?('_to_') } : []

  counter = 0

  RubyLLM.models.all.each do |llm|
    cw = llm.context_window
    caps = llm.capabilities.join(',')
    inputs = llm.modalities.input.join(',')
    outputs = llm.modalities.output.join(',')
    mode = "#{inputs} to #{outputs}"
    in_1m = llm.pricing.text_tokens.standard.to_h[:input_per_million]
    entry = "- #{llm.id} (#{llm.provider}) in: $#{in_1m} cw: #{cw} mode: #{mode} caps: #{caps}"

    if query.nil? || query.empty?
      counter += 1
      puts entry
      next
    end

    show_it = true
    q1.each { |q| show_it &&= llm.modalities.send("#{q}?") }
    q2.each { |q| show_it &&= entry.include?(q) }

    if show_it
      counter += 1
      puts entry
    end
  end

  puts if counter > 0
  puts "#{counter} LLMs matching your query"
  puts
end