Module: Legion::LLM::API::OpenAI::Models

Extended by:
Legion::Logging::Helper
Defined in:
lib/legion/llm/api/openai/models.rb

Class Method Summary collapse

Class Method Details

.build_model_listObject



58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/legion/llm/api/openai/models.rb', line 58

def self.build_model_list
  models = Legion::LLM::Inventory.offerings(type: :inference).map do |offering|
    Legion::LLM::API::Translators::OpenAIResponse.format_model_object(
      offering[:model],
      owned_by: offering[:provider_family]
    )
  end
  seen = {}
  models.select { |m| seen[m[:id]] ? false : (seen[m[:id]] = true) }
rescue StandardError => e
  handle_exception(e, level: :warn, handled: true, operation: 'llm.api.openai.models.inventory')
  []
end

.registered(app) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/legion/llm/api/openai/models.rb', line 13

def self.registered(app)
  log.debug('[llm][api][openai][models] registering GET /v1/models and GET /v1/models/:id')

  app.get '/v1/models' do
    log.debug('[llm][api][openai][models] action=list')
    require_llm!

    model_list = Legion::LLM::API::OpenAI::Models.build_model_list
    log.debug("[llm][api][openai][models] action=listed count=#{model_list.size}")

    content_type :json
    Legion::JSON.dump({ object: 'list', data: model_list })
  rescue StandardError => e
    handle_exception(e, level: :error, handled: true, operation: 'llm.api.openai.models.list')
    halt 500, { 'Content-Type' => 'application/json' },
         Legion::JSON.dump({ error: { message: e.message, type: 'server_error' } })
  end

  app.get '/v1/models/:id' do
    model_id = params[:id]
    log.debug("[llm][api][openai][models] action=get id=#{model_id}")
    require_llm!

    model_list = Legion::LLM::API::OpenAI::Models.build_model_list
    found = model_list.find { |m| m[:id] == model_id }

    unless found
      log.debug("[llm][api][openai][models] action=not_found id=#{model_id}")
      halt 404, { 'Content-Type' => 'application/json' },
           Legion::JSON.dump({ error: { message: "Model '#{model_id}' not found",
                                        type: 'invalid_request_error', code: 'model_not_found' } })
    end

    log.debug("[llm][api][openai][models] action=found id=#{model_id}")
    content_type :json
    Legion::JSON.dump(found)
  rescue StandardError => e
    handle_exception(e, level: :error, handled: true, operation: 'llm.api.openai.models.get')
    halt 500, { 'Content-Type' => 'application/json' },
         Legion::JSON.dump({ error: { message: e.message, type: 'server_error' } })
  end

  log.debug('[llm][api][openai][models] GET /v1/models routes registered')
end