-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherror-classifier.ts
More file actions
280 lines (224 loc) · 7.55 KB
/
error-classifier.ts
File metadata and controls
280 lines (224 loc) · 7.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
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
57
58
59
60
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
import { DEFAULT_CONFIG, RETRYABLE_ERROR_PATTERNS } from "./constants"
function getObjectRecord(value: unknown): Record<string, unknown> | undefined {
return value && typeof value === "object" ? (value as Record<string, unknown>) : undefined
}
function normalizeMessage(value: string): string {
return value.trim().length === 0 ? "" : value.toLowerCase()
}
function getStringField(value: unknown, key: string): string | undefined {
const record = getObjectRecord(value)
const field = record?.[key]
if (typeof field !== "string") return undefined
const normalized = normalizeMessage(field)
return normalized.length > 0 ? normalized : undefined
}
export function getErrorMessage(error: unknown): string {
if (!error) return ""
if (typeof error === "string") return normalizeMessage(error)
const errorObj = error as Record<string, unknown>
const paths = [
(errorObj.data as Record<string, unknown>)?.error,
errorObj.data,
errorObj.error,
errorObj,
]
for (const obj of paths) {
const record = getObjectRecord(obj)
if (!record || !("message" in record)) continue
const rawMessage = record.message
if (typeof rawMessage === "string") {
return normalizeMessage(rawMessage)
}
}
try {
return normalizeMessage(JSON.stringify(error))
} catch {
return ""
}
}
export function extractStatusCode(error: unknown, retryOnErrors?: number[]): number | undefined {
if (!error) return undefined
const errorObj = error as Record<string, unknown>
const statusCode =
errorObj.statusCode ??
errorObj.status ??
(errorObj.data as Record<string, unknown>)?.statusCode
if (typeof statusCode === "number") {
return statusCode
}
if (typeof statusCode === "string") {
const parsed = Number.parseInt(statusCode, 10)
if (!Number.isNaN(parsed)) {
return parsed
}
}
const codes = retryOnErrors ?? DEFAULT_CONFIG.retry_on_errors
const message = getErrorMessage(error)
const contextualPattern = new RegExp(
`(?:status(?:\\s+code)?|code|http)\D*(${codes.join("|")})\\b|\\b(${codes.join("|")})\\b(?=\ |[^0-9])`,
"i"
)
const statusMatch = message.match(contextualPattern)
const extracted = statusMatch?.[1] ?? statusMatch?.[2]
if (extracted) {
return parseInt(extracted, 10)
}
return undefined
}
export function extractErrorName(error: unknown): string | undefined {
if (!error || typeof error !== "object") return undefined
const errorObj = error as Record<string, unknown>
const directName = errorObj.name
if (typeof directName === "string" && directName.length > 0) {
return directName
}
const nestedError = errorObj.error as Record<string, unknown> | undefined
const nestedName = nestedError?.name
if (typeof nestedName === "string" && nestedName.length > 0) {
return nestedName
}
const dataError = (errorObj.data as Record<string, unknown> | undefined)?.error as
| Record<string, unknown>
| undefined
const dataErrorName = dataError?.name
if (typeof dataErrorName === "string" && dataErrorName.length > 0) {
return dataErrorName
}
return undefined
}
export function classifyErrorType(error: unknown): string | undefined {
const message = getErrorMessage(error)
const errorName = extractErrorName(error)?.toLowerCase()
if (
errorName?.includes("loadapi") ||
(/api.?key.?is.?missing/i.test(message) && /environment variable/i.test(message)) ||
/(?:x-api-key|api key).*(?:is required|missing|required)/i.test(message) ||
/(?:missing|required).*(?:x-api-key|api key)/i.test(message)
) {
return "missing_api_key"
}
if (
(/api.?key/i.test(message) && /must be a string/i.test(message)) ||
/incorrect api key provided/i.test(message) ||
/api key not valid/i.test(message) ||
/invalid api key/i.test(message)
) {
return "invalid_api_key"
}
if (errorName?.includes("unknownerror") && /model\s+not\s+found/i.test(message)) {
return "model_not_found"
}
if (
/model\s+(?:is\s+)?not\s+(?:found|supported|available)/i.test(message) ||
/the model .+ does not exist/i.test(message)
) {
return "model_not_found"
}
return undefined
}
export interface AutoRetrySignal {
signal: string
}
export const AUTO_RETRY_PATTERNS: Array<(combined: string) => boolean> = [
(combined) => /retrying\s+in/i.test(combined),
(combined) =>
/(?:too\s+many\s+requests|quota\s*exceeded|usage\s+limit|rate\s+limit|limit\s+reached)/i.test(
combined
),
]
export function extractAutoRetrySignal(
info: Record<string, unknown> | undefined
): AutoRetrySignal | undefined {
if (!info) return undefined
const candidates: string[] = []
const directStatus = info.status
if (typeof directStatus === "string") candidates.push(directStatus)
const summary = info.summary
if (typeof summary === "string") candidates.push(summary)
const message = info.message
if (typeof message === "string") candidates.push(message)
const details = info.details
if (typeof details === "string") candidates.push(details)
const combined = candidates.join("\n")
if (!combined) return undefined
const isAutoRetry = AUTO_RETRY_PATTERNS.every((test) => test(combined))
if (isAutoRetry) {
return { signal: combined }
}
return undefined
}
export function containsErrorContent(
parts: Array<{ type?: string; text?: string }> | undefined
): { hasError: boolean; errorMessage?: string } {
if (!parts || parts.length === 0) return { hasError: false }
const errorParts = parts.filter((p) => p.type === "error")
if (errorParts.length > 0) {
const errorMessages = errorParts
.map((p) => p.text)
.filter((text): text is string => typeof text === "string")
const errorMessage = errorMessages.length > 0 ? errorMessages.join("\n") : undefined
return { hasError: true, errorMessage }
}
return { hasError: false }
}
export function detectErrorInTextParts(
parts: Array<{ type?: string; text?: string }> | undefined
): { hasError: boolean; errorType?: string; errorMessage?: string } {
if (!parts || parts.length === 0) return { hasError: false }
const textContent = parts
.filter((p) => p.type === "text" && typeof p.text === "string" && p.text.length > 0)
.map((p) => p.text!)
.join("\n")
if (!textContent) return { hasError: false }
const errorType = classifyErrorType({ message: textContent, name: "TextContent" })
if (errorType) {
return { hasError: true, errorType, errorMessage: textContent }
}
return { hasError: false }
}
export function extractErrorContentFromParts(
parts: Array<{ type?: string; text?: string }> | undefined
): { hasError: boolean; errorMessage?: string } {
if (!parts || parts.length === 0) return { hasError: false }
const errorParts = parts.filter(
(p) => p.type === "error" && typeof p.text === "string" && p.text.length > 0
)
if (errorParts.length > 0) {
const errorMessage = errorParts.map((p) => p.text).join("\n")
return { hasError: true, errorMessage }
}
return { hasError: false }
}
export function isRetryableError(
error: unknown,
retryOnErrors: number[],
userPatterns?: string[]
): boolean {
const statusCode = extractStatusCode(error, retryOnErrors)
const message = getErrorMessage(error)
const errorType = classifyErrorType(error)
if (errorType === "missing_api_key") {
return true
}
if (errorType === "model_not_found") {
return true
}
if (statusCode && retryOnErrors.includes(statusCode)) {
return true
}
if (RETRYABLE_ERROR_PATTERNS.some((pattern) => pattern.test(message))) {
return true
}
// Check user-provided retryable_error_patterns from config
if (userPatterns && userPatterns.length > 0) {
for (const patternStr of userPatterns) {
try {
const re = new RegExp(patternStr, "i")
if (re.test(message)) return true
} catch {
// Invalid regex — skip silently
}
}
}
return false
}