Class: RubyLLM::Models

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/ruby_llm/models.rb

Overview

Registry of available AI models and their capabilities.

Constant Summary collapse

MODELS_DEV_PROVIDER_MAP =
{
  'openai' => 'openai',
  'anthropic' => 'anthropic',
  'google' => 'gemini',
  'google-vertex' => 'vertexai',
  'amazon-bedrock' => 'bedrock',
  'deepseek' => 'deepseek',
  'mistral' => 'mistral',
  'openrouter' => 'openrouter',
  'perplexity' => 'perplexity'
}.freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(models = nil) ⇒ Models

Returns a new instance of Models.



263
264
265
# File 'lib/ruby_llm/models.rb', line 263

def initialize(models = nil)
  @models = models || self.class.load_models
end

Class Method Details

.add_provider_metadata(models_dev_model, provider_model) ⇒ Object



170
171
172
173
174
175
# File 'lib/ruby_llm/models.rb', line 170

def (models_dev_model, provider_model)
  data = models_dev_model.to_h
  data[:metadata] = provider_model..merge(data[:metadata] || {})
  data[:capabilities] = (models_dev_model.capabilities + provider_model.capabilities).uniq
  Model::Info.new(data)
end

.fetch_from_models_devObject



106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
# File 'lib/ruby_llm/models.rb', line 106

def fetch_from_models_dev
  RubyLLM.logger.info 'Fetching models from models.dev API...'

  connection = Connection.basic do |f|
    f.request :json
    f.response :json, parser_options: { symbolize_names: true }
  end
  response = connection.get 'https://models.dev/api.json'
  providers = response.body || {}

  models = providers.flat_map do |provider_key, provider_data|
    provider_slug = MODELS_DEV_PROVIDER_MAP[provider_key.to_s]
    next [] unless provider_slug

    (provider_data[:models] || {}).values.map do |model_data|
      Model::Info.new(models_dev_model_to_info(model_data, provider_slug, provider_key.to_s))
    end
  end
  models.reject { |model| model.provider.nil? || model.id.nil? }
end

.fetch_from_providers(remote_only: true) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/ruby_llm/models.rb', line 47

def fetch_from_providers(remote_only: true)
  config = RubyLLM.config
  configured_classes = if remote_only
                         Provider.configured_remote_providers(config)
                       else
                         Provider.configured_providers(config)
                       end
  configured = configured_classes.map { |klass| klass.new(config) }

  RubyLLM.logger.info "Fetching models from providers: #{configured.map(&:name).join(', ')}"

  configured.flat_map(&:list_models)
end

.find_models_dev_model(key, models_dev_by_key) ⇒ Object



149
150
151
152
153
154
155
156
157
158
159
160
161
162
# File 'lib/ruby_llm/models.rb', line 149

def find_models_dev_model(key, models_dev_by_key)
  # Direct match
  return models_dev_by_key[key] if models_dev_by_key[key]

  # VertexAI uses same models as Gemini
  provider, model_id = key.split(':', 2)
  return unless provider == 'vertexai'

  gemini_model = models_dev_by_key["gemini:#{model_id}"]
  return unless gemini_model

  # Return Gemini's models.dev data but with VertexAI as provider
  Model::Info.new(gemini_model.to_h.merge(provider: 'vertexai'))
end

.index_by_key(models) ⇒ Object



164
165
166
167
168
# File 'lib/ruby_llm/models.rb', line 164

def index_by_key(models)
  models.each_with_object({}) do |model, hash|
    hash["#{model.provider}:#{model.id}"] = model
  end
end

.instanceObject



21
22
23
# File 'lib/ruby_llm/models.rb', line 21

def instance
  @instance ||= new
end

.load_models(file = RubyLLM.config.model_registry_file) ⇒ Object



29
30
31
# File 'lib/ruby_llm/models.rb', line 29

def load_models(file = RubyLLM.config.model_registry_file)
  read_from_json(file)
end

.merge_models(provider_models, models_dev_models) ⇒ Object



127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/ruby_llm/models.rb', line 127

def merge_models(provider_models, models_dev_models)
  models_dev_by_key = index_by_key(models_dev_models)
  provider_by_key = index_by_key(provider_models)

  all_keys = models_dev_by_key.keys | provider_by_key.keys

  models = all_keys.map do |key|
    models_dev_model = find_models_dev_model(key, models_dev_by_key)
    provider_model = provider_by_key[key]

    if models_dev_model && provider_model
      (models_dev_model, provider_model)
    elsif models_dev_model
      models_dev_model
    else
      provider_model
    end
  end

  models.sort_by { |m| [m.provider, m.id] }
end

.method_missing(method) ⇒ Object



94
95
96
97
98
99
100
# File 'lib/ruby_llm/models.rb', line 94

def method_missing(method, ...)
  if instance.respond_to?(method)
    instance.send(method, ...)
  else
    super
  end
end

.models_dev_capabilities(model_data, modalities) ⇒ Object



197
198
199
200
201
202
203
204
# File 'lib/ruby_llm/models.rb', line 197

def models_dev_capabilities(model_data, modalities)
  capabilities = []
  capabilities << 'function_calling' if model_data[:tool_call]
  capabilities << 'structured_output' if model_data[:structured_output]
  capabilities << 'reasoning' if model_data[:reasoning]
  capabilities << 'vision' if modalities[:input].intersect?(%w[image video pdf])
  capabilities.uniq
end

.models_dev_metadata(model_data, provider_key) ⇒ Object



227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
# File 'lib/ruby_llm/models.rb', line 227

def (model_data, provider_key)
   = {
    source: 'models.dev',
    provider_id: provider_key,
    open_weights: model_data[:open_weights],
    attachment: model_data[:attachment],
    temperature: model_data[:temperature],
    last_updated: model_data[:last_updated],
    status: model_data[:status],
    interleaved: model_data[:interleaved],
    cost: model_data[:cost],
    limit: model_data[:limit],
    knowledge: model_data[:knowledge]
  }
  .compact
end

.models_dev_model_to_info(model_data, provider_slug, provider_key) ⇒ Object



177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
# File 'lib/ruby_llm/models.rb', line 177

def models_dev_model_to_info(model_data, provider_slug, provider_key)
  modalities = normalize_models_dev_modalities(model_data[:modalities])
  capabilities = models_dev_capabilities(model_data, modalities)

  {
    id: model_data[:id],
    name: model_data[:name] || model_data[:id],
    provider: provider_slug,
    family: model_data[:family],
    created_at: model_data[:release_date] || model_data[:last_updated],
    context_window: model_data.dig(:limit, :context),
    max_output_tokens: model_data.dig(:limit, :output),
    knowledge_cutoff: normalize_models_dev_knowledge(model_data[:knowledge]),
    modalities: modalities,
    capabilities: capabilities,
    pricing: models_dev_pricing(model_data[:cost]),
    metadata: (model_data, provider_key)
  }
end

.models_dev_pricing(cost) ⇒ Object



206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
# File 'lib/ruby_llm/models.rb', line 206

def models_dev_pricing(cost)
  return {} unless cost

  text_standard = {
    input_per_million: cost[:input],
    output_per_million: cost[:output],
    cached_input_per_million: cost[:cache_read],
    reasoning_output_per_million: cost[:reasoning]
  }.compact

  audio_standard = {
    input_per_million: cost[:input_audio],
    output_per_million: cost[:output_audio]
  }.compact

  pricing = {}
  pricing[:text_tokens] = { standard: text_standard } if text_standard.any?
  pricing[:audio_tokens] = { standard: audio_standard } if audio_standard.any?
  pricing
end

.normalize_models_dev_knowledge(value) ⇒ Object



253
254
255
256
257
258
259
260
# File 'lib/ruby_llm/models.rb', line 253

def normalize_models_dev_knowledge(value)
  return if value.nil?
  return value if value.is_a?(Date)

  Date.parse(value.to_s)
rescue ArgumentError
  nil
end

.normalize_models_dev_modalities(modalities) ⇒ Object



244
245
246
247
248
249
250
251
# File 'lib/ruby_llm/models.rb', line 244

def normalize_models_dev_modalities(modalities)
  normalized = { input: [], output: [] }
  return normalized unless modalities

  normalized[:input] = Array(modalities[:input]).compact
  normalized[:output] = Array(modalities[:output]).compact
  normalized
end

.read_from_json(file = RubyLLM.config.model_registry_file) ⇒ Object



33
34
35
36
37
38
# File 'lib/ruby_llm/models.rb', line 33

def read_from_json(file = RubyLLM.config.model_registry_file)
  data = File.exist?(file) ? File.read(file) : '[]'
  JSON.parse(data, symbolize_names: true).map { |model| Model::Info.new(model) }
rescue JSON::ParserError
  []
end

.refresh!(remote_only: false) ⇒ Object



40
41
42
43
44
45
# File 'lib/ruby_llm/models.rb', line 40

def refresh!(remote_only: false)
  provider_models = fetch_from_providers(remote_only: remote_only)
  models_dev_models = fetch_from_models_dev
  merged_models = merge_models(provider_models, models_dev_models)
  @instance = new(merged_models)
end

.resolve(model_id, provider: nil, assume_exists: false, config: nil) ⇒ Object

rubocop:disable Metrics/PerceivedComplexity



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
# File 'lib/ruby_llm/models.rb', line 61

def resolve(model_id, provider: nil, assume_exists: false, config: nil) # rubocop:disable Metrics/PerceivedComplexity
  config ||= RubyLLM.config
  provider_class = provider ? Provider.providers[provider.to_sym] : nil

  if provider_class
    temp_instance = provider_class.new(config)
    assume_exists = true if temp_instance.local?
  end

  if assume_exists
    raise ArgumentError, 'Provider must be specified if assume_exists is true' unless provider

    provider_class ||= raise(Error, "Unknown provider: #{provider.to_sym}")
    provider_instance = provider_class.new(config)

    model = if provider_instance.local?
              begin
                Models.find(model_id, provider)
              rescue ModelNotFoundError
                nil
              end
            end

    model ||= Model::Info.default(model_id, provider_instance.slug)
  else
    model = Models.find model_id, provider
    provider_class = Provider.providers[model.provider.to_sym] || raise(Error,
                                                                        "Unknown provider: #{model.provider}")
    provider_instance = provider_class.new(config)
  end
  [model, provider_instance]
end

.respond_to_missing?(method, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


102
103
104
# File 'lib/ruby_llm/models.rb', line 102

def respond_to_missing?(method, include_private = false)
  instance.respond_to?(method, include_private) || super
end

.schema_fileObject



25
26
27
# File 'lib/ruby_llm/models.rb', line 25

def schema_file
  File.expand_path('models_schema.json', __dir__)
end

Instance Method Details

#allObject



275
276
277
# File 'lib/ruby_llm/models.rb', line 275

def all
  @models
end

#audio_modelsObject



299
300
301
# File 'lib/ruby_llm/models.rb', line 299

def audio_models
  self.class.new(all.select { |m| m.type == 'audio' || m.modalities.output.include?('audio') })
end

#by_family(family) ⇒ Object



307
308
309
# File 'lib/ruby_llm/models.rb', line 307

def by_family(family)
  self.class.new(all.select { |m| m.family == family.to_s })
end

#by_provider(provider) ⇒ Object



311
312
313
# File 'lib/ruby_llm/models.rb', line 311

def by_provider(provider)
  self.class.new(all.select { |m| m.provider == provider.to_s })
end

#chat_modelsObject



291
292
293
# File 'lib/ruby_llm/models.rb', line 291

def chat_models
  self.class.new(all.select { |m| m.type == 'chat' })
end

#eachObject



279
280
281
# File 'lib/ruby_llm/models.rb', line 279

def each(&)
  all.each(&)
end

#embedding_modelsObject



295
296
297
# File 'lib/ruby_llm/models.rb', line 295

def embedding_models
  self.class.new(all.select { |m| m.type == 'embedding' || m.modalities.output.include?('embeddings') })
end

#find(model_id, provider = nil) ⇒ Object



283
284
285
286
287
288
289
# File 'lib/ruby_llm/models.rb', line 283

def find(model_id, provider = nil)
  if provider
    find_with_provider(model_id, provider)
  else
    find_without_provider(model_id)
  end
end

#image_modelsObject



303
304
305
# File 'lib/ruby_llm/models.rb', line 303

def image_models
  self.class.new(all.select { |m| m.type == 'image' || m.modalities.output.include?('image') })
end

#load_from_json!(file = RubyLLM.config.model_registry_file) ⇒ Object



267
268
269
# File 'lib/ruby_llm/models.rb', line 267

def load_from_json!(file = RubyLLM.config.model_registry_file)
  @models = self.class.read_from_json(file)
end

#refresh!(remote_only: false) ⇒ Object



315
316
317
# File 'lib/ruby_llm/models.rb', line 315

def refresh!(remote_only: false)
  self.class.refresh!(remote_only: remote_only)
end

#resolve(model_id, provider: nil, assume_exists: false, config: nil) ⇒ Object



319
320
321
# File 'lib/ruby_llm/models.rb', line 319

def resolve(model_id, provider: nil, assume_exists: false, config: nil)
  self.class.resolve(model_id, provider: provider, assume_exists: assume_exists, config: config)
end

#save_to_json(file = RubyLLM.config.model_registry_file) ⇒ Object



271
272
273
# File 'lib/ruby_llm/models.rb', line 271

def save_to_json(file = RubyLLM.config.model_registry_file)
  File.write(file, JSON.pretty_generate(all.map(&:to_h)))
end