Module: OpenAICompatibleErrors::Normalizer

Defined in:
lib/openai_compatible_errors/normalize.rb

Constant Summary collapse

MAX_BODY_BYTES =
65_536
MAX_IDENTIFIER_BYTES =
256
UNSET =
Object.new.freeze

Class Method Summary collapse

Class Method Details

.classify(status:, code:, error_type:, class_name:, exception_message:) ⇒ Object



211
212
213
214
215
216
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
# File 'lib/openai_compatible_errors/normalize.rb', line 211

def classify(status:, code:, error_type:, class_name:, exception_message:)
  structured = [code, error_type, class_name].compact.join(" ").downcase
  transport = [structured, exception_message].compact.join(" ").downcase

  return :schema if structured.include?("apiresponsevalidationerror")
  return :validation if [400, 422].include?(status)
  return :conflict if status == 409
  return :authentication if status == 401
  return :permission if status == 403
  if status == 404
    return structured.match?(/model|deployment|resource/) ? :not_found : :endpoint
  end
  return :timeout if status == 408
  return :payload_too_large if status == 413
  if status == 429
    return structured.match?(/insufficient[_ -]?quota|quota[_ -]?(exhausted|exceeded)|billing|credit/) ? :quota : :rate_limit
  end
  return :upstream if [502, 503, 504].include?(status)
  return :server if status && status >= 500
  return :validation if status && status >= 400

  return :timeout if structured.match?(/timeout|timedout|etimedout/)
  return :network if structured.match?(/connection|connecterror|proxyerror|protocolerror/)
  return :aborted if transport.match?(/abort|cancel/)
  return :quota if structured.match?(/insufficient[_ -]?quota|quota[_ -]?(exhausted|exceeded)|billing|credit/)
  return :authentication if structured.match?(/invalid[_ -]?api[_ -]?key|authentication|unauthori[sz]ed/)
  return :permission if structured.match?(/permission|forbidden|access[_ -]?denied/)
  return :rate_limit if structured.match?(/rate[_ -]?limit/)
  return :timeout if transport.match?(/timed?[_ -]?out|timeout|etimedout/)
  return :network if transport.match?(/connection|econnreset|econnrefused|enotfound|network/)
  return :schema if structured.match?(/json|schema|parse[_ -]?error|malformed|decode/)

  :unknown
end

.decode_body(value) ⇒ Object



107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/openai_compatible_errors/normalize.rb', line 107

def decode_body(value)
  return nil if value == UNSET || value.nil?
  return value if value.is_a?(Hash) || value.is_a?(Array)

  if value.is_a?(String)
    return nil if value.bytesize > MAX_BODY_BYTES

    text = value.scrub
    candidate = text.strip
    return value unless candidate.start_with?("{", "[")

    begin
      return JSON.parse(candidate, allow_nan: false, max_nesting: 100)
    rescue JSON::ParserError, ArgumentError, SystemStackError
      return value
    end
  end

  if value.respond_to?(:to_hash)
    begin
      converted = value.to_hash
      return converted if converted.is_a?(Hash)
    rescue StandardError
      return value
    end
  end
  value
end

.detect_source(input, status) ⇒ Object



202
203
204
205
206
207
208
209
# File 'lib/openai_compatible_errors/normalize.rb', line 202

def detect_source(input, status)
  name = safe_class_name(input)
  return :openai_sdk if name.match?(/OpenAI|APIError|RateLimitError|AuthenticationError/i)
  return :httpx if name.start_with?("HTTPX::")
  return :http if status

  :unknown
end

.error_payload(value) ⇒ Object



136
137
138
139
140
141
142
143
144
145
146
# File 'lib/openai_compatible_errors/normalize.rb', line 136

def error_payload(value)
  return value unless value.is_a?(Hash)

  nested = value[:response] || value["response"]
  if nested.is_a?(Hash)
    nested_error = nested[:error] || nested["error"]
    return nested_error unless nested_error.nil?
  end
  error = value[:error] || value["error"]
  error.nil? ? value : error
end

.exception_message(value) ⇒ Object



184
185
186
187
188
189
190
191
192
193
# File 'lib/openai_compatible_errors/normalize.rb', line 184

def exception_message(value)
  return nil unless value.is_a?(Exception)

  begin
    text = value.message
    text.is_a?(String) && text.bytesize <= 2_000 ? text : nil
  rescue StandardError
    nil
  end
end

.first_present(*values) ⇒ Object



93
94
95
# File 'lib/openai_compatible_errors/normalize.rb', line 93

def first_present(*values)
  values.find { |value| value != UNSET && !value.nil? }
end

.first_text(*values) ⇒ Object



159
160
161
162
163
164
165
166
167
168
169
170
171
# File 'lib/openai_compatible_errors/normalize.rb', line 159

def first_text(*values)
  values.each do |value|
    next unless value.is_a?(Hash)

    candidate = value[:message] || value["message"]
    return candidate if candidate.is_a?(String) && !candidate.empty?
  end
  values.each do |value|
    candidate = exception_message(value)
    return candidate unless candidate.nil?
  end
  nil
end

.first_value(field, *values) ⇒ Object



148
149
150
151
152
153
154
155
156
157
# File 'lib/openai_compatible_errors/normalize.rb', line 148

def first_value(field, *values)
  values.each do |value|
    next unless value.is_a?(Hash)

    return value[field] if value.key?(field) && !value[field].nil?
    string_key = field.to_s
    return value[string_key] if value.key?(string_key) && !value[string_key].nil?
  end
  UNSET
end

.normalize(input, status: nil, headers: nil, body: nil, include_provider_message: false, now: Time.now, source: nil) ⇒ 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
# File 'lib/openai_compatible_errors/normalize.rb', line 13

def normalize(input, status: nil, headers: nil, body: nil,
              include_provider_message: false, now: Time.now, source: nil)
  response_status, response_headers, response_body = response_parts(input)
  status = valid_status(status) || response_status
  headers = response_headers if headers.nil?
  body = response_body if body.nil?

  decoded = decode_body(body.nil? && input.is_a?(Hash) ? input : body)
  payload = error_payload(decoded)
  code = safe_identifier(first_value(:code, payload, decoded, input))
  error_type = safe_identifier(first_value(:type, payload, decoded, input))
  request_id = Headers.request_id(headers) ||
               safe_identifier(first_value(:request_id, payload, decoded, input))
  class_name = safe_class_name(input)
  exception_message = exception_message(input)
  category = classify(status: status, code: code, error_type: error_type,
                      class_name: class_name, exception_message: exception_message)
  provider_message =
    if include_provider_message
      Redaction.redact_sensitive_text(
        first_text(payload, decoded, input),
        max_chars: 2_000
      )
    end

  ApiError.new(
    category: category,
    source: source || detect_source(input, status),
    status: status,
    code: code,
    type: error_type,
    request_id: request_id,
    retry_after_ms: Headers.retry_after_ms(headers, now: now),
    provider_message: provider_message
  )
end

.read(value, *keys) ⇒ Object



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/openai_compatible_errors/normalize.rb', line 68

def read(value, *keys)
  return UNSET if value.nil?

  if value.is_a?(Hash)
    keys.each do |key|
      return value[key] if value.key?(key)
      string_key = key.to_s
      return value[string_key] if value.key?(string_key)
    end
    return UNSET
  end

  keys.each do |key|
    next unless value.respond_to?(key)

    begin
      result = value.public_send(key)
      return result unless result.nil?
    rescue StandardError
      next
    end
  end
  UNSET
end

.response_parts(input) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/openai_compatible_errors/normalize.rb', line 50

def response_parts(input)
  status = valid_status(read(input, :status_code)) || valid_status(read(input, :status))
  headers = read(input, :headers)
  content = first_present(read(input, :body), read(input, :content), read(input, :data))

  nested_response = read(input, :response)
  if nested_response && nested_response != input
    status ||= valid_status(read(nested_response, :status_code)) ||
               valid_status(read(nested_response, :status))
    headers ||= read(nested_response, :headers)
    content = first_present(content, read(nested_response, :body),
                             read(nested_response, :content),
                             read(nested_response, :data))
  end

  [status, headers, content]
end

.safe_class_name(value) ⇒ Object



195
196
197
198
199
200
# File 'lib/openai_compatible_errors/normalize.rb', line 195

def safe_class_name(value)
  name = value.class.name
  name.is_a?(String) ? name.byteslice(0, 256).to_s : ""
rescue StandardError
  ""
end

.safe_identifier(value) ⇒ Object



173
174
175
176
177
178
179
180
181
182
# File 'lib/openai_compatible_errors/normalize.rb', line 173

def safe_identifier(value)
  return nil unless value.is_a?(String)

  candidate = value.strip
  return nil if candidate.empty? || candidate.bytesize > MAX_IDENTIFIER_BYTES
  return nil unless candidate.match?(/\A[A-Za-z0-9][A-Za-z0-9._:\/-]*\z/)
  return nil if candidate.match?(/bearer|api[_ -]?key|secret|token/i)

  candidate
end

.valid_status(value) ⇒ Object



97
98
99
100
101
102
103
104
105
# File 'lib/openai_compatible_errors/normalize.rb', line 97

def valid_status(value)
  candidate =
    if value.is_a?(Integer) && !value.is_a?(TrueClass) && !value.is_a?(FalseClass)
      value
    elsif value.is_a?(String) && value.bytesize <= 16 && value.strip.match?(/\A\d+\z/)
      value.to_i
    end
  candidate && candidate.between?(100, 599) ? candidate : nil
end