-
Notifications
You must be signed in to change notification settings - Fork 425
Expand file tree
/
Copy patherrors.ts
More file actions
474 lines (406 loc) · 13.4 KB
/
errors.ts
File metadata and controls
474 lines (406 loc) · 13.4 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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
import chalk from 'chalk';
import { MODEL_LIST, OCO_AI_PROVIDER_ENUM } from '../commands/config';
// Provider billing/help URLs for common errors
export const PROVIDER_BILLING_URLS: Record<string, string | null> = {
[OCO_AI_PROVIDER_ENUM.ANTHROPIC]: 'https://console.anthropic.com/settings/billing',
[OCO_AI_PROVIDER_ENUM.OPENAI]: 'https://platform.openai.com/settings/organization/billing',
[OCO_AI_PROVIDER_ENUM.GEMINI]: 'https://aistudio.google.com/app/plan',
[OCO_AI_PROVIDER_ENUM.GROQ]: 'https://console.groq.com/settings/billing',
[OCO_AI_PROVIDER_ENUM.MISTRAL]: 'https://console.mistral.ai/billing/',
[OCO_AI_PROVIDER_ENUM.DEEPSEEK]: 'https://platform.deepseek.com/usage',
[OCO_AI_PROVIDER_ENUM.OPENROUTER]: 'https://openrouter.ai/credits',
[OCO_AI_PROVIDER_ENUM.AIMLAPI]: 'https://aimlapi.com/app/billing',
[OCO_AI_PROVIDER_ENUM.AZURE]: 'https://portal.azure.com/#view/Microsoft_Azure_CostManagement',
[OCO_AI_PROVIDER_ENUM.MINIMAX]: 'https://platform.minimaxi.com/user-center/basic-information',
[OCO_AI_PROVIDER_ENUM.OLLAMA]: null,
[OCO_AI_PROVIDER_ENUM.MLX]: null,
[OCO_AI_PROVIDER_ENUM.FLOWISE]: null,
[OCO_AI_PROVIDER_ENUM.TEST]: null
};
// Error type for insufficient credits/quota
export class InsufficientCreditsError extends Error {
public readonly provider: string;
constructor(provider: string, message?: string) {
super(message || `Insufficient credits or quota for provider '${provider}'`);
this.name = 'InsufficientCreditsError';
this.provider = provider;
}
}
// Error type for rate limiting (429 errors)
export class RateLimitError extends Error {
public readonly provider: string;
public readonly retryAfter?: number;
constructor(provider: string, retryAfter?: number, message?: string) {
super(message || `Rate limit exceeded for provider '${provider}'`);
this.name = 'RateLimitError';
this.provider = provider;
this.retryAfter = retryAfter;
}
}
// Error type for service unavailable (5xx errors)
export class ServiceUnavailableError extends Error {
public readonly provider: string;
public readonly statusCode: number;
constructor(provider: string, statusCode: number = 503, message?: string) {
super(message || `Service unavailable for provider '${provider}'`);
this.name = 'ServiceUnavailableError';
this.provider = provider;
this.statusCode = statusCode;
}
}
// Error type for authentication failures
export class AuthenticationError extends Error {
public readonly provider: string;
constructor(provider: string, message?: string) {
super(message || `Authentication failed for provider '${provider}'`);
this.name = 'AuthenticationError';
this.provider = provider;
}
}
export class ModelNotFoundError extends Error {
public readonly modelName: string;
public readonly provider: string;
public readonly statusCode: number;
constructor(modelName: string, provider: string, statusCode: number = 404) {
super(`Model '${modelName}' not found for provider '${provider}'`);
this.name = 'ModelNotFoundError';
this.modelName = modelName;
this.provider = provider;
this.statusCode = statusCode;
}
}
export class ApiKeyMissingError extends Error {
public readonly provider: string;
constructor(provider: string) {
super(`API key is missing for provider '${provider}'`);
this.name = 'ApiKeyMissingError';
this.provider = provider;
}
}
export function isModelNotFoundError(error: unknown): boolean {
if (error instanceof ModelNotFoundError) {
return true;
}
if (error instanceof Error) {
const message = error.message.toLowerCase();
// OpenAI error patterns
if (
message.includes('model') &&
(message.includes('not found') ||
message.includes('does not exist') ||
message.includes('invalid model'))
) {
return true;
}
// Anthropic error patterns
if (
message.includes('model') &&
(message.includes('not found') || message.includes('invalid'))
) {
return true;
}
// Check for 404 status in axios/fetch errors
if (
'status' in (error as any) &&
(error as any).status === 404 &&
message.includes('model')
) {
return true;
}
// Check for response status
if ('response' in (error as any)) {
const response = (error as any).response;
if (response?.status === 404) {
return true;
}
}
}
return false;
}
export function isApiKeyError(error: unknown): boolean {
if (error instanceof ApiKeyMissingError) {
return true;
}
if (error instanceof Error) {
const message = error.message.toLowerCase();
// Common API key error patterns
if (
message.includes('api key') ||
message.includes('apikey') ||
message.includes('authentication') ||
message.includes('unauthorized') ||
message.includes('invalid_api_key') ||
message.includes('incorrect api key')
) {
return true;
}
// Check for 401 status
if ('response' in (error as any)) {
const response = (error as any).response;
if (response?.status === 401) {
return true;
}
}
}
return false;
}
export function getSuggestedModels(
provider: string,
failedModel: string
): string[] {
const providerKey = provider.toLowerCase() as keyof typeof MODEL_LIST;
const models = MODEL_LIST[providerKey];
if (!models || !Array.isArray(models)) {
return [];
}
// Return first 5 models as suggestions, excluding the failed one
return models.filter((m) => m !== failedModel).slice(0, 5);
}
export function getRecommendedModel(provider: string): string | null {
switch (provider.toLowerCase()) {
case OCO_AI_PROVIDER_ENUM.OPENAI:
return 'gpt-4o-mini';
case OCO_AI_PROVIDER_ENUM.ANTHROPIC:
return 'claude-sonnet-4-20250514';
case OCO_AI_PROVIDER_ENUM.GEMINI:
return 'gemini-1.5-flash';
case OCO_AI_PROVIDER_ENUM.GROQ:
return 'llama3-70b-8192';
case OCO_AI_PROVIDER_ENUM.MISTRAL:
return 'mistral-small-latest';
case OCO_AI_PROVIDER_ENUM.DEEPSEEK:
return 'deepseek-chat';
case OCO_AI_PROVIDER_ENUM.OPENROUTER:
return 'openai/gpt-4o-mini';
case OCO_AI_PROVIDER_ENUM.AIMLAPI:
return 'gpt-4o-mini';
case OCO_AI_PROVIDER_ENUM.MINIMAX:
return 'MiniMax-M2.7';
default:
return null;
}
}
export function formatErrorWithRecovery(
error: Error,
provider: string,
model: string
): string {
const suggestions = getSuggestedModels(provider, model);
const recommended = getRecommendedModel(provider);
let message = `\n${error.message}\n`;
if (suggestions.length > 0) {
message += '\nSuggested alternatives:\n';
suggestions.forEach((m, i) => {
const isRecommended = m === recommended;
message += ` ${i + 1}. ${m}${isRecommended ? ' (Recommended)' : ''}\n`;
});
}
message += '\nTo fix this, run: oco config set OCO_MODEL=<model-name>\n';
message += 'Or run: oco setup\n';
return message;
}
// Detect insufficient credits/quota errors from various providers
export function isInsufficientCreditsError(error: unknown): boolean {
if (error instanceof InsufficientCreditsError) {
return true;
}
if (error instanceof Error) {
const message = error.message.toLowerCase();
// Common patterns for insufficient credits/quota
if (
message.includes('insufficient') ||
message.includes('credit') ||
message.includes('quota') ||
message.includes('balance') ||
message.includes('billing') ||
message.includes('payment') ||
message.includes('exceeded') ||
message.includes('limit reached') ||
message.includes('no remaining')
) {
return true;
}
// Check for 402 Payment Required status
if ('status' in (error as any) && (error as any).status === 402) {
return true;
}
if ('response' in (error as any)) {
const response = (error as any).response;
if (response?.status === 402) {
return true;
}
}
}
return false;
}
// Detect rate limit errors (429)
export function isRateLimitError(error: unknown): boolean {
if (error instanceof RateLimitError) {
return true;
}
if (error instanceof Error) {
const message = error.message.toLowerCase();
// Common patterns for rate limiting
if (
message.includes('rate limit') ||
message.includes('rate_limit') ||
message.includes('too many requests') ||
message.includes('throttle')
) {
return true;
}
// Check for 429 status
if ('status' in (error as any) && (error as any).status === 429) {
return true;
}
if ('response' in (error as any)) {
const response = (error as any).response;
if (response?.status === 429) {
return true;
}
}
}
return false;
}
// Detect service unavailable errors (5xx)
export function isServiceUnavailableError(error: unknown): boolean {
if (error instanceof ServiceUnavailableError) {
return true;
}
if (error instanceof Error) {
const message = error.message.toLowerCase();
// Common patterns for service unavailable
if (
message.includes('service unavailable') ||
message.includes('server error') ||
message.includes('internal error') ||
message.includes('temporarily unavailable') ||
message.includes('overloaded')
) {
return true;
}
// Check for 5xx status
const status = (error as any).status || (error as any).response?.status;
if (status && status >= 500 && status < 600) {
return true;
}
}
return false;
}
// User-friendly formatted error structure
export interface FormattedError {
title: string;
message: string;
helpUrl: string | null;
suggestion: string | null;
}
// Format an error into a user-friendly structure
export function formatUserFriendlyError(error: unknown, provider: string): FormattedError {
const billingUrl = PROVIDER_BILLING_URLS[provider] || null;
// Handle our custom error types first
if (error instanceof InsufficientCreditsError) {
return {
title: 'Insufficient Credits',
message: `Your ${provider} account has insufficient credits or quota.`,
helpUrl: billingUrl,
suggestion: 'Add credits to your account to continue using the service.'
};
}
if (error instanceof RateLimitError) {
const retryMsg = error.retryAfter
? `Please wait ${error.retryAfter} seconds before retrying.`
: 'Please wait a moment before retrying.';
return {
title: 'Rate Limit Exceeded',
message: `You've made too many requests to ${provider}.`,
helpUrl: billingUrl,
suggestion: retryMsg
};
}
if (error instanceof ServiceUnavailableError) {
return {
title: 'Service Unavailable',
message: `The ${provider} service is temporarily unavailable.`,
helpUrl: null,
suggestion: 'Please try again in a few moments.'
};
}
if (error instanceof AuthenticationError) {
return {
title: 'Authentication Failed',
message: `Your ${provider} API key is invalid or expired.`,
helpUrl: billingUrl,
suggestion: 'Run `oco setup` to configure a valid API key.'
};
}
if (error instanceof ModelNotFoundError) {
return {
title: 'Model Not Found',
message: `The model '${error.modelName}' is not available for ${provider}.`,
helpUrl: null,
suggestion: 'Run `oco setup` to select a valid model.'
};
}
// Detect error type from raw errors
if (isInsufficientCreditsError(error)) {
return {
title: 'Insufficient Credits',
message: `Your ${provider} account has insufficient credits or quota.`,
helpUrl: billingUrl,
suggestion: 'Add credits to your account to continue using the service.'
};
}
if (isRateLimitError(error)) {
return {
title: 'Rate Limit Exceeded',
message: `You've made too many requests to ${provider}.`,
helpUrl: billingUrl,
suggestion: 'Please wait a moment before retrying.'
};
}
if (isServiceUnavailableError(error)) {
return {
title: 'Service Unavailable',
message: `The ${provider} service is temporarily unavailable.`,
helpUrl: null,
suggestion: 'Please try again in a few moments.'
};
}
if (isApiKeyError(error)) {
return {
title: 'Authentication Failed',
message: `Your ${provider} API key is invalid or expired.`,
helpUrl: billingUrl,
suggestion: 'Run `oco setup` to configure a valid API key.'
};
}
if (isModelNotFoundError(error)) {
const model = (error as any).modelName || (error as any).model || 'unknown';
return {
title: 'Model Not Found',
message: `The model '${model}' is not available for ${provider}.`,
helpUrl: null,
suggestion: 'Run `oco setup` to select a valid model.'
};
}
// Default: generic error
const errorMessage = error instanceof Error ? error.message : String(error);
return {
title: 'Error',
message: errorMessage,
helpUrl: null,
suggestion: 'Run `oco setup` to reconfigure or check your settings.'
};
}
// Print a formatted error as a chalk-styled string
export function printFormattedError(formatted: FormattedError): string {
let output = `\n${chalk.red('✖')} ${chalk.bold.red(formatted.title)}\n`;
output += ` ${formatted.message}\n`;
if (formatted.helpUrl) {
output += `\n ${chalk.cyan('Help:')} ${chalk.underline(formatted.helpUrl)}\n`;
}
if (formatted.suggestion) {
output += `\n ${chalk.yellow('Suggestion:')} ${formatted.suggestion}\n`;
}
return output;
}