Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 11x 11x 11x 11x 11x 15x 15x 15x 10x 15x 15x 11x 15x 3x 3x 15x 21x 21x 21x 11x 15x 88x 11x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 181x 46x 46x 11x 7x 7x 7x 28x 22x 6x 6x 6x 6x 6x 6x 6x 31x 28x 7x 21x 7x 14x 2x 12x 12x 2x 10x 4x 6x 6x 3x 3x 2x 1x 28x 28x 28x 28x 28x 7x 21x 7x 14x 2x 12x 2x 10x 3x 28x 28x 11x 31x 31x 3x 28x 28x 28x 28x 2x 28x 28x 11x 21x 11x 7x 7x 7x | import { PROVIDER_DISPLAY_NAME } from "../shared/constants";
export type ApiErrorKind =
| "auth_failed"
| "rate_limited"
| "model_unavailable"
| "server_error"
| "timeout"
| "network_error"
| "context_overflow"
| "token_limit"
| "empty_stream"
| "invalid_request"
| "unknown";
export interface ApiErrorContext {
operation?: string;
model?: string;
status?: number;
detail?: string;
contextOverflow?: ContextOverflowInfo;
}
export interface StructuredError {
code: string;
cause: string;
action: string;
}
export const ERROR_MESSAGES: Record<string, StructuredError> = {
auth_failed: {
code: "AUTH_FAILED",
cause: "API key is invalid or expired.",
action: "Update your API key via Command Palette > NVIDIA NIM: Manage API Key.",
},
rate_limited: {
code: "RATE_LIMITED",
cause: "Too many requests to NVIDIA NIM API.",
action: "Wait a moment and try again. Consider switching to a different model.",
},
model_unavailable: {
code: "MODEL_UNAVAILABLE",
cause: "The selected NVIDIA NIM model is not available for this API key or endpoint.",
action: "Choose another model or refresh the NVIDIA NIM model list.",
},
server_error: {
code: "SERVER_ERROR",
cause: `${PROVIDER_DISPLAY_NAME} service is experiencing issues.`,
action: "Wait a few minutes and try again.",
},
timeout: {
code: "STREAM_TIMEOUT",
cause: "The model took too long to respond.",
action: "Try again with a shorter prompt or switch to a faster model.",
},
context_overflow: {
code: "CONTEXT_OVERFLOW",
cause: "The prompt exceeds the model's context window limit.",
action:
"The request will be retried with a shorter response. If it fails again, start a new chat.",
},
token_limit: {
code: "TOKEN_LIMIT_EXCEEDED",
cause: "The conversation is too long for this model's context window.",
action: "Start a new chat or switch to a model with a larger context window.",
},
empty_stream: {
code: "EMPTY_STREAM",
cause: "The model finished without returning any visible answer or tool call.",
action: "Try again. If it repeats, lower the reasoning effort or switch to a different model.",
},
network_error: {
code: "NETWORK_ERROR",
cause: "The request could not reach NVIDIA NIM.",
action: "Check your network connection and try again.",
},
invalid_request: {
code: "INVALID_REQUEST",
cause: "NVIDIA NIM rejected the request.",
action: "Check the selected model, messages, and tool arguments, then try again.",
},
unknown: {
code: "NVIDIA_NIM_ERROR",
cause: "The NVIDIA NIM request failed.",
action: "Try again. If the problem persists, switch models or inspect the debug log.",
},
};
const RETRYABLE_STATUS_CODES = new Set([429, 502, 503, 504, 529]);
/**
* Patterns that indicate the server rejected the request due to context overflow.
* Covers common OpenAI-compatible and NVIDIA NIM error message formats.
*/
const CONTEXT_OVERFLOW_PATTERNS = [
/maximum.*context.*length/i,
/context.*length.*exceed/i,
/token.*limit.*exceed/i,
/prompt.*too.*long/i,
/prompt.*length.*exceed/i,
/request.*too.*large/i,
// "max token" variants require an explicit excess/limit verb so unrelated
// 400s such as "invalid value for max_tokens" are not misclassified.
/max(?:imum)?[^.\n]{0,40}tokens?\s+(?:limit\s+)?exceed(?:s|ed)?/i,
/exceed(?:s|ed)?[^.\n]{0,40}max(?:imum)?[^.\n]{0,40}tokens?/i,
/max(?:imum)?\s+(?:context\s+)?(?:length|tokens?)\s+(?:limit\s+)?(?:is|of)\s+\d/i,
];
/**
* Extract reported maximum and actual usage from server error detail text.
* Handles formats like:
* "Maximum context length is 204800 tokens"
* "prompt is too long: 1048576 > 1048575"
* "token limit exceeded: 1000001 > 1000000"
*/
export function parseContextOverflowDetail(detail: string): ContextOverflowInfo {
const result: ContextOverflowInfo = {};
// Try to extract reported maximum
const maxMatch =
detail.match(/(?:maximum|max|limit).*?context.*?length.*?(?:is|=|:|of)\s*(\d[\d_,]*)/i) ??
detail.match(/(?:maximum|max|limit).*?(?:token|context).*?(?:is|=|:|of)\s*(\d[\d_,]*)/i) ??
detail.match(/(?:is|=|>)\s*(\d[\d_,]*)(?:\s*(?:token|>))/i);
if (maxMatch) {
result.reportedMaximum = parseNumericValue(maxMatch[1]);
}
// Try to extract actual usage
// The separator group must include 'has' to match NVIDIA NIM format:
// "your message has 524288 tokens" — 'has' is the separator, not a word prefix.
const usageMatch =
// Dedicated pattern for NVIDIA NIM format: "your message has 524288 tokens"
detail.match(/(?:has|had)\b\s+(\d[\d_,]*)/i) ??
// NVIDIA NIM format: "your messages resulted in 270981 tokens"
detail.match(/resulted\s+in\s+(\d[\d_,]*)/i) ??
detail.match(/(?:prompt|usage|actual|got|have).*?(?:is|=|:|>)\s*(\d[\d_,]*)/i) ??
detail.match(/(\d[\d_,]*)(?:\s*(?:>|token|\+))/i);
if (usageMatch) {
result.actualUsage = parseNumericValue(usageMatch[1]);
}
// Fallback: "N > M" pattern
if (result.actualUsage === undefined && result.reportedMaximum === undefined) {
const gtMatch = detail.match(/(\d[\d_,]*\s*>\s*\d[\d_,]*)/);
Iif (gtMatch) {
const nums = gtMatch[1].split(">").map((s) => parseNumericValue(s.trim()));
Iif (nums.length === 2 && nums[0] !== undefined && nums[1] !== undefined) {
result.actualUsage = nums[0];
result.reportedMaximum = nums[1];
}
}
}
return result;
}
function parseNumericValue(s: string): number | undefined {
const cleaned = s.replace(/[_,\s]/g, "");
const n = Number.parseInt(cleaned, 10);
return Number.isFinite(n) && n > 0 ? n : undefined;
}
/**
* Check whether an error detail string indicates a context overflow.
*/
export function isContextOverflowError(detail: string | undefined): boolean {
if (!detail) return false;
return CONTEXT_OVERFLOW_PATTERNS.some((p) => p.test(detail));
}
export interface ContextOverflowInfo {
reportedMaximum?: number;
actualUsage?: number;
}
export class NvidiaApiError extends Error {
readonly kind: ApiErrorKind;
readonly code: string;
readonly status?: number;
readonly operation?: string;
readonly retryable: boolean;
readonly contextOverflow?: ContextOverflowInfo;
constructor(kind: ApiErrorKind, message: string, context: ApiErrorContext = {}) {
super(message);
this.name = "NvidiaApiError";
this.kind = kind;
this.code = ERROR_MESSAGES[kind]?.code ?? "NVIDIA_NIM_ERROR";
this.status = context.status;
this.operation = context.operation;
this.retryable = context.status !== undefined && RETRYABLE_STATUS_CODES.has(context.status);
this.contextOverflow = context.contextOverflow;
if (typeof this.stack === "string") {
const lines = this.stack.split("\n");
const atIndex = lines.findIndex((line) => line.trimStart().startsWith("at "));
if (atIndex > 0) {
this.stack = lines.slice(atIndex).join("\n");
}
}
}
}
export function createStructuredError(
key: string,
detail?: string,
context: ApiErrorContext = {},
): NvidiaApiError {
const kind = (key in ERROR_MESSAGES ? key : "unknown") as ApiErrorKind;
const message = formatStructuredError(key, detail);
return new NvidiaApiError(kind, message, context);
}
function getErrorStatus(error: unknown, context: ApiErrorContext): number | undefined {
if (context.status !== undefined) {
return context.status;
}
if (typeof error === "object" && error !== null) {
const status = (error as { status?: unknown }).status;
Iif (typeof status === "number" && Number.isFinite(status)) {
return status;
}
}
if (error instanceof Error) {
const match = error.message.match(/\bHTTP\s+(\d{3})\b/i);
Iif (match) {
return Number(match[1]);
}
}
return undefined;
}
function isAbortError(error: unknown): error is Error {
return error instanceof Error && error.name === "AbortError";
}
function classifyKind(error: unknown, status: number | undefined): ApiErrorKind {
if (status === 401 || status === 403) {
return "auth_failed";
}
if (status === 429 || status === 529) {
return "rate_limited";
}
if (status === 404) {
return "model_unavailable";
}
Iif (status === 408 || status === 504) {
return "timeout";
}
if (status !== undefined && status >= 500 && status <= 599) {
return "server_error";
}
if (status !== undefined && status >= 400 && status <= 499) {
// HTTP 400 may be a context overflow — refine in classifyApiError below
return "invalid_request";
}
if (error instanceof Error) {
if (error.name === "TimeoutError" || /\btimeout\b|timed out/i.test(error.message)) {
return "timeout";
}
if (
error.name === "TypeError" ||
/network|fetch failed|econnreset|enotfound|socket|dns/i.test(error.message)
) {
return "network_error";
}
}
return "unknown";
}
function buildClassifiedMessage(
kind: ApiErrorKind,
error: unknown,
context: ApiErrorContext,
): string {
const structured = ERROR_MESSAGES[kind];
const originalDetail = context.detail ?? (error instanceof Error ? error.message : String(error));
const detail = originalDetail && originalDetail !== structured.cause ? originalDetail : undefined;
let cause = structured.cause;
if (kind === "auth_failed") {
cause = "Authentication failed. Your API key may be invalid or expired.";
} else if (kind === "rate_limited") {
cause = context.status === 529 ? "Service temporarily overloaded." : "Rate limited.";
} else if (kind === "model_unavailable" && context.model) {
cause = `NVIDIA NIM model "${context.model}" is not available for this API key or endpoint.`;
} else if (kind === "server_error") {
cause = "Server error. The NVIDIA NIM service may be experiencing issues.";
} else if (kind === "timeout" && context.operation === "stream") {
cause = "NVIDIA NIM streaming timeout: no data received. The model may be stalled.";
}
const statusDetail =
context.status !== undefined && !(detail ?? "").includes(`HTTP ${context.status}`)
? `HTTP ${context.status}${detail ? `: ${detail}` : ""}`
: detail;
return [
`[${structured.code}] ${cause}`,
statusDetail ? `Details: ${statusDetail}` : "",
`Action: ${structured.action}`,
]
.filter(Boolean)
.join("\n");
}
/**
* Convert HTTP, timeout, and network failures into one stable provider error.
* Abort errors intentionally pass through so callers can distinguish cancellation.
*/
export function classifyApiError(error: unknown, context: ApiErrorContext = {}): Error {
Iif (isAbortError(error)) {
return error;
}
if (error instanceof NvidiaApiError) {
return error;
}
const status = getErrorStatus(error, context);
let kind = classifyKind(error, status);
// Refine HTTP 400: only classify as context_overflow when the detail
// text matches known context-limit patterns; otherwise keep invalid_request.
const detail = context.detail;
if (kind === "invalid_request" && status === 400 && isContextOverflowError(detail)) {
kind = "context_overflow";
}
const contextOverflow =
kind === "context_overflow" && detail ? parseContextOverflowDetail(detail) : undefined;
return new NvidiaApiError(kind, buildClassifiedMessage(kind, error, { ...context, status }), {
...context,
status,
contextOverflow,
});
}
export function isRetryableApiStatus(status: number): boolean {
return RETRYABLE_STATUS_CODES.has(status);
}
export function formatStructuredError(key: string, detail?: string): string {
const err = ERROR_MESSAGES[key];
Iif (!err) return detail ?? "An unknown error occurred.";
return [`[${err.code}] ${err.cause}`, detail ? `Details: ${detail}` : "", `Action: ${err.action}`]
.filter(Boolean)
.join("\n");
}
|