Method: OpenAIClient#models

Defined in:
lib/simple-openai-client.rb

#modelsObject

Return an array with the available models



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
# File 'lib/simple-openai-client.rb', line 23

def models
  uri = URI("https://api.openai.com/v1/models")
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  
  # Create a GET request instead of POST
  request = Net::HTTP::Get.new(uri.request_uri, {
    "Authorization" => "Bearer #{self.api_key}",
    "Content-Type" => "application/json"
    # Removed "OpenAI-Beta" header as it's typically not required
  })
  
  response = http.request(request)
  
  if response.is_a?(Net::HTTPSuccess)
    parsed_response = JSON.parse(response.body)
    # Extract and return the list of models
    parsed_response['data'].map { |model| model['id'] }
  else
    raise "Error: #{response.code} #{response.message}"
    #puts response.body
    #[]
  end
rescue JSON::ParserError => e
  raise "Failed to parse JSON response: #{e.message}"
  #[]
rescue StandardError => e
  raise "An error occurred: #{e.message}"
  #[]
end