Refactor error handling to config-driven approach with centralized error rules

Made-with: Cursor
This commit is contained in:
decolua
2026-04-15 11:46:47 +07:00
parent b1288c5064
commit b669b6ffc1
20 changed files with 1056 additions and 991 deletions
+82
View File
@@ -0,0 +1,82 @@
// OpenAI-compatible error types mapping (client-facing)
export const ERROR_TYPES = {
400: { type: "invalid_request_error", code: "bad_request" },
401: { type: "authentication_error", code: "invalid_api_key" },
402: { type: "billing_error", code: "payment_required" },
403: { type: "permission_error", code: "insufficient_quota" },
404: { type: "invalid_request_error", code: "model_not_found" },
406: { type: "invalid_request_error", code: "model_not_supported" },
429: { type: "rate_limit_error", code: "rate_limit_exceeded" },
500: { type: "server_error", code: "internal_server_error" },
502: { type: "server_error", code: "bad_gateway" },
503: { type: "server_error", code: "service_unavailable" },
504: { type: "server_error", code: "gateway_timeout" }
};
// Default error messages per status code (client-facing)
export const DEFAULT_ERROR_MESSAGES = {
400: "Bad request",
401: "Invalid API key provided",
402: "Payment required",
403: "You exceeded your current quota",
404: "Model not found",
406: "Model not supported",
429: "Rate limit exceeded",
500: "Internal server error",
502: "Bad gateway - upstream provider error",
503: "Service temporarily unavailable",
504: "Gateway timeout"
};
// Exponential backoff config for rate limits
export const BACKOFF_CONFIG = {
base: 1000,
max: 3 * 60 * 1000,
maxLevel: 15
};
// Default cooldown for transient/unknown errors
export const TRANSIENT_COOLDOWN_MS = 30 * 1000;
// Cooldown durations (ms)
const COOLDOWN = {
long: 2 * 60 * 1000,
short: 5 * 1000,
};
/**
* Unified error classification rules.
* Checked top-to-bottom: text rules first (by order), then status rules.
* Each rule: { text?, status?, cooldownMs?, backoff? }
* - text: substring match (case-insensitive) on error message
* - status: HTTP status code match
* - cooldownMs: fixed cooldown duration
* - backoff: true = use exponential backoff (rate limit)
*/
export const ERROR_RULES = [
// --- Text-based rules (checked first, order = priority) ---
{ text: "no credentials", cooldownMs: COOLDOWN.long },
{ text: "request not allowed", cooldownMs: COOLDOWN.short },
{ text: "improperly formed request", cooldownMs: COOLDOWN.long },
{ text: "rate limit", backoff: true },
{ text: "too many requests", backoff: true },
{ text: "quota exceeded", backoff: true },
{ text: "capacity", backoff: true },
{ text: "overloaded", backoff: true },
// --- Status-based rules (fallback when text doesn't match) ---
{ status: 401, cooldownMs: COOLDOWN.long },
{ status: 402, cooldownMs: COOLDOWN.long },
{ status: 403, cooldownMs: COOLDOWN.long },
{ status: 404, cooldownMs: COOLDOWN.long },
{ status: 429, backoff: true },
];
// Backward compat: COOLDOWN_MS object (used by index.js re-export)
export const COOLDOWN_MS = {
unauthorized: COOLDOWN.long,
paymentRequired: COOLDOWN.long,
notFound: COOLDOWN.long,
transient: TRANSIENT_COOLDOWN_MS,
requestNotAllowed: COOLDOWN.short,
};
+9 -51
View File
@@ -1,5 +1,5 @@
import { PROVIDERS } from "./providers.js";
import { GOOGLE_TTS_LANGUAGES } from "./googleTtsLanguages.js";
import { buildTtsProviderModels } from "./ttsModels.js";
// Provider models - Single source of truth
// Key = alias (cc, cx, gc, qw, if, ag, gh for OAuth; id for API Key)
@@ -144,10 +144,10 @@ export const PROVIDER_MODELS = {
{ id: "deepseek/deepseek-reasoner", name: "DeepSeek Reasoner" },
],
oc: [ // OpenCode
{ id: "nemotron-3-super-free", name: "Nemotron 3 Super" },
// { id: "nemotron-3-super-free", name: "Nemotron 3 Super" },
// { id: "qwen3.6-plus-free", name: "Qwen 3.6 Plus" },
// { id: "big-pickle", name: "Big Pickle", targetFormat: "claude" },
{ id: "minimax-m2.5-free", name: "MiniMax M2.5", targetFormat: "claude" },
// { id: "minimax-m2.5-free", name: "MiniMax M2.5", targetFormat: "claude" },
// { id: "trinity-large-preview-free", name: "Trinity Large Preview" },
],
@@ -230,6 +230,10 @@ export const PROVIDER_MODELS = {
{ id: "perplexity/pplx-embed-v1-4b", name: "Perplexity Embed V1 4B", type: "embedding" },
{ id: "perplexity/pplx-embed-v1-0.6b", name: "Perplexity Embed V1 0.6B", type: "embedding" },
{ id: "nvidia/llama-nemotron-embed-vl-1b-v2:free", name: "NVIDIA Nemotron Embed VL 1B V2 (Free)", type: "embedding" },
// TTS models
{ id: "openai/gpt-4o-mini-tts", name: "GPT-4o Mini TTS", type: "tts" },
{ id: "openai/tts-1-hd", name: "TTS-1 HD", type: "tts" },
{ id: "openai/tts-1", name: "TTS-1", type: "tts" },
],
glm: [
{ id: "glm-5.1", name: "GLM 5.1" },
@@ -377,54 +381,8 @@ export const PROVIDER_MODELS = {
{ id: "zai-org/glm-5-maas", name: "GLM-5 (Vertex)" },
],
// Free/noAuth TTS providers
"local-device": [
{ id: "default", name: "System Default Voice", type: "tts" },
],
"google-tts": GOOGLE_TTS_LANGUAGES,
// OpenAI TTS voices (hardcoded — no public API to list them)
// Used by ttsCore.js when provider = openai
"openai-tts-voices": [
{ id: "alloy", name: "Alloy", type: "tts" },
{ id: "ash", name: "Ash", type: "tts" },
{ id: "ballad", name: "Ballad", type: "tts" },
{ id: "cedar", name: "Cedar", type: "tts" },
{ id: "coral", name: "Coral", type: "tts" },
{ id: "echo", name: "Echo", type: "tts" },
{ id: "fable", name: "Fable", type: "tts" },
{ id: "marin", name: "Marin", type: "tts" },
{ id: "nova", name: "Nova", type: "tts" },
{ id: "onyx", name: "Onyx", type: "tts" },
{ id: "sage", name: "Sage", type: "tts" },
{ id: "shimmer", name: "Shimmer", type: "tts" },
{ id: "verse", name: "Verse", type: "tts" },
],
// OpenAI TTS models
"openai-tts-models": [
{ id: "gpt-4o-mini-tts", name: "GPT-4o Mini TTS", type: "tts" },
{ id: "tts-1-hd", name: "TTS-1 HD", type: "tts" },
{ id: "tts-1", name: "TTS-1", type: "tts" },
],
// ElevenLabs TTS models
"elevenlabs-tts-models": [
{ id: "eleven_flash_v2_5", name: "Flash v2.5 (Fastest)", type: "tts" },
{ id: "eleven_turbo_v2_5", name: "Turbo v2.5 (Fast)", type: "tts" },
{ id: "eleven_multilingual_v2", name: "Multilingual v2 (Quality)", type: "tts" },
{ id: "eleven_monolingual_v1", name: "Monolingual v1 (English)", type: "tts" },
],
"edge-tts": [
{ id: "en-US-AriaNeural", name: "Aria (en-US)", type: "tts" },
{ id: "en-US-GuyNeural", name: "Guy (en-US)", type: "tts" },
{ id: "en-GB-SoniaNeural", name: "Sonia (en-GB)", type: "tts" },
{ id: "vi-VN-HoaiMyNeural", name: "Hoai My (vi-VN)", type: "tts" },
{ id: "vi-VN-NamMinhNeural", name: "Nam Minh (vi-VN)", type: "tts" },
{ id: "zh-CN-XiaoxiaoNeural", name: "Xiaoxiao (zh-CN)", type: "tts" },
{ id: "zh-CN-YunxiNeural", name: "Yunxi (zh-CN)", type: "tts" },
{ id: "fr-FR-DeniseNeural", name: "Denise (fr-FR)", type: "tts" },
{ id: "de-DE-KatjaNeural", name: "Katja (de-DE)", type: "tts" },
{ id: "ja-JP-NanamiNeural", name: "Nanami (ja-JP)", type: "tts" },
{ id: "ko-KR-SunHiNeural", name: "SunHi (ko-KR)", type: "tts" },
],
// TTS entries are loaded from ttsModels.js via buildTtsProviderModels()
...buildTtsProviderModels(),
};
// Helper functions
+2 -47
View File
@@ -14,33 +14,8 @@ export const HTTP_STATUS = {
GATEWAY_TIMEOUT: 504
};
// OpenAI-compatible error types mapping
export const ERROR_TYPES = {
[HTTP_STATUS.BAD_REQUEST]: { type: "invalid_request_error", code: "bad_request" },
[HTTP_STATUS.UNAUTHORIZED]: { type: "authentication_error", code: "invalid_api_key" },
[HTTP_STATUS.FORBIDDEN]: { type: "permission_error", code: "insufficient_quota" },
[HTTP_STATUS.NOT_FOUND]: { type: "invalid_request_error", code: "model_not_found" },
[HTTP_STATUS.NOT_ACCEPTABLE]: { type: "invalid_request_error", code: "model_not_supported" },
[HTTP_STATUS.RATE_LIMITED]: { type: "rate_limit_error", code: "rate_limit_exceeded" },
[HTTP_STATUS.SERVER_ERROR]: { type: "server_error", code: "internal_server_error" },
[HTTP_STATUS.BAD_GATEWAY]: { type: "server_error", code: "bad_gateway" },
[HTTP_STATUS.SERVICE_UNAVAILABLE]: { type: "server_error", code: "service_unavailable" },
[HTTP_STATUS.GATEWAY_TIMEOUT]: { type: "server_error", code: "gateway_timeout" }
};
// Default error messages per status code
export const DEFAULT_ERROR_MESSAGES = {
[HTTP_STATUS.BAD_REQUEST]: "Bad request",
[HTTP_STATUS.UNAUTHORIZED]: "Invalid API key provided",
[HTTP_STATUS.FORBIDDEN]: "You exceeded your current quota",
[HTTP_STATUS.NOT_FOUND]: "Model not found",
[HTTP_STATUS.NOT_ACCEPTABLE]: "Model not supported",
[HTTP_STATUS.RATE_LIMITED]: "Rate limit exceeded",
[HTTP_STATUS.SERVER_ERROR]: "Internal server error",
[HTTP_STATUS.BAD_GATEWAY]: "Bad gateway - upstream provider error",
[HTTP_STATUS.SERVICE_UNAVAILABLE]: "Service temporarily unavailable",
[HTTP_STATUS.GATEWAY_TIMEOUT]: "Gateway timeout"
};
// Re-export error config (backward compat)
export { ERROR_TYPES, DEFAULT_ERROR_MESSAGES, BACKOFF_CONFIG, COOLDOWN_MS } from "./errorConfig.js";
// Cache TTLs (seconds)
export const CACHE_TTL = {
@@ -73,26 +48,6 @@ export const DEFAULT_RETRY_CONFIG = {
502: 1 // Bad gateway - retry 1 time (transient)
};
// Exponential backoff config for rate limits
export const BACKOFF_CONFIG = {
base: 1000,
max: 2 * 60 * 1000,
maxLevel: 15
};
// Error-based cooldown times
export const COOLDOWN_MS = {
unauthorized: 2 * 60 * 1000,
paymentRequired: 2 * 60 * 1000,
notFound: 2 * 60 * 1000,
transient: 30 * 1000,
requestNotAllowed: 5 * 1000,
// Legacy aliases
rateLimit: 2 * 60 * 1000,
serviceUnavailable: 2 * 1000,
authExpired: 2 * 60 * 1000
};
// Requests containing these texts will bypass provider
export const SKIP_PATTERNS = [
"Please write a 5-10 word title for the following conversation:"
+109
View File
@@ -0,0 +1,109 @@
import { GOOGLE_TTS_LANGUAGES } from "./googleTtsLanguages.js";
// ── Voice definitions (DRY — reused across providers) ──────────────────────
const VOICES = {
alloy: { id: "alloy", name: "Alloy" },
ash: { id: "ash", name: "Ash" },
ballad: { id: "ballad", name: "Ballad" },
cedar: { id: "cedar", name: "Cedar" },
coral: { id: "coral", name: "Coral" },
echo: { id: "echo", name: "Echo" },
fable: { id: "fable", name: "Fable" },
marin: { id: "marin", name: "Marin" },
nova: { id: "nova", name: "Nova" },
onyx: { id: "onyx", name: "Onyx" },
sage: { id: "sage", name: "Sage" },
shimmer: { id: "shimmer", name: "Shimmer" },
verse: { id: "verse", name: "Verse" },
};
const v = (...keys) => keys.map((k) => ({ ...VOICES[k], type: "tts" }));
// 9 voices for tts-1 / tts-1-hd
const VOICES_STANDARD = v("alloy", "ash", "coral", "echo", "fable", "nova", "onyx", "sage", "shimmer");
// 13 voices for gpt-4o-mini-tts
const VOICES_FULL = v("alloy", "ash", "ballad", "cedar", "coral", "echo", "fable", "marin", "nova", "onyx", "sage", "shimmer", "verse");
// ── TTS Config (config-driven, single source of truth) ─────────────────────
export const TTS_MODELS_CONFIG = {
openai: {
models: [
{ id: "gpt-4o-mini-tts", name: "GPT-4o Mini TTS", type: "tts" },
{ id: "tts-1-hd", name: "TTS-1 HD", type: "tts" },
{ id: "tts-1", name: "TTS-1", type: "tts" },
],
voices: {
"gpt-4o-mini-tts": VOICES_FULL,
"tts-1": VOICES_STANDARD,
"tts-1-hd": VOICES_STANDARD,
},
// Flat voice list (all unique voices) for backward compat
allVoices: VOICES_FULL,
},
openrouter: {
models: [
{ id: "openai/gpt-4o-mini-tts", name: "GPT-4o Mini TTS", type: "tts" },
{ id: "openai/tts-1-hd", name: "TTS-1 HD", type: "tts" },
{ id: "openai/tts-1", name: "TTS-1", type: "tts" },
],
voices: {
"openai/gpt-4o-mini-tts": VOICES_FULL,
"openai/tts-1": VOICES_STANDARD,
"openai/tts-1-hd": VOICES_STANDARD,
},
allVoices: VOICES_FULL,
},
elevenlabs: {
models: [
{ id: "eleven_flash_v2_5", name: "Flash v2.5 (Fastest)", type: "tts" },
{ id: "eleven_turbo_v2_5", name: "Turbo v2.5 (Fast)", type: "tts" },
{ id: "eleven_multilingual_v2", name: "Multilingual v2 (Quality)", type: "tts" },
{ id: "eleven_monolingual_v1", name: "Monolingual v1 (English)", type: "tts" },
],
// voices come from API, not hardcoded
},
"edge-tts": {
defaults: [
{ id: "en-US-AriaNeural", name: "Aria (en-US)", type: "tts" },
{ id: "en-US-GuyNeural", name: "Guy (en-US)", type: "tts" },
{ id: "en-GB-SoniaNeural", name: "Sonia (en-GB)", type: "tts" },
{ id: "vi-VN-HoaiMyNeural", name: "Hoai My (vi-VN)", type: "tts" },
{ id: "vi-VN-NamMinhNeural", name: "Nam Minh (vi-VN)", type: "tts" },
{ id: "zh-CN-XiaoxiaoNeural", name: "Xiaoxiao (zh-CN)", type: "tts" },
{ id: "zh-CN-YunxiNeural", name: "Yunxi (zh-CN)", type: "tts" },
{ id: "fr-FR-DeniseNeural", name: "Denise (fr-FR)", type: "tts" },
{ id: "de-DE-KatjaNeural", name: "Katja (de-DE)", type: "tts" },
{ id: "ja-JP-NanamiNeural", name: "Nanami (ja-JP)", type: "tts" },
{ id: "ko-KR-SunHiNeural", name: "SunHi (ko-KR)", type: "tts" },
],
},
"local-device": {
defaults: [
{ id: "default", name: "System Default Voice", type: "tts" },
],
},
"google-tts": {
defaults: GOOGLE_TTS_LANGUAGES,
},
};
// ── Helper: get voices for a specific model ────────────────────────────────
export function getTtsVoicesForModel(provider, modelId) {
const cfg = TTS_MODELS_CONFIG[provider];
if (!cfg?.voices) return null;
return cfg.voices[modelId] || cfg.allVoices || null;
}
// ── Build flat entries for PROVIDER_MODELS backward compat ─────────────────
export function buildTtsProviderModels() {
const entries = {};
for (const [provider, cfg] of Object.entries(TTS_MODELS_CONFIG)) {
if (cfg.models) entries[`${provider}-tts-models`] = cfg.models;
if (cfg.allVoices) entries[`${provider}-tts-voices`] = cfg.allVoices;
if (cfg.defaults) entries[provider] = cfg.defaults;
}
// Keep openai-tts-voices key pointing to full voice list for backward compat
entries["openai-tts-voices"] = TTS_MODELS_CONFIG.openai.allVoices;
entries["openrouter-tts-voices"] = TTS_MODELS_CONFIG.openrouter.allVoices;
return entries;
}