Module: Apidepth::ModelNameExtractor

Defined in:
lib/apidepth/model_name_extractor.rb

Constant Summary collapse

AI_VENDOR_HOSTS =
%w[
  api.openai.com
  api.anthropic.com
  generativelanguage.googleapis.com
  api.mistral.ai
  api.cohere.com
].to_set.freeze
MAX_BODY_BYTES =
8_192

Class Method Summary collapse

Class Method Details

.extract(host, response) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/apidepth/model_name_extractor.rb', line 36

def self.extract(host, response)
  return nil unless Apidepth.configuration.capture_model_names
  return nil unless AI_VENDOR_HOSTS.include?(host)
  return nil unless response["content-type"]&.include?("application/json")

  body = response.body
  return nil if body.nil? || body.empty?

  parsed = JSON.parse(body.byteslice(0, MAX_BODY_BYTES), symbolize_names: true)
  model = parsed[:model]
  model.is_a?(String) && !model.empty? ? model : nil
rescue JSON::ParserError, Encoding::UndefinedConversionError, TypeError
  nil
end