Open History to see the last commit
1import { APICallError } from "ai";
2import { DomainError } from "./auth";
3
4const budgetCodes = new Set([
5 "insufficient_quota",
6 "insufficient_credits",
7 "insufficient_balance",
8 "credits_exhausted",
9 "credit_balance_exhausted",
10 "out_of_credits",
11 "budget_exceeded",
12 "spend_limit_exceeded",
13]);
14
15function budgetDetails(value: unknown): boolean {
16 if (!value || typeof value !== "object") return false;
17 const detail = value as Record<string, unknown>;
18 if (
19 [detail.error_code, detail.code, detail.type].some(
20 (code) => typeof code === "string" && budgetCodes.has(code.toLowerCase()),
21 )
22 )
23 return true;
24 const message = typeof detail.message === "string" ? detail.message : "";
25 // REQUEST_LIMIT_EXCEEDED also covers TPM limits; require financial context.
26 return (
27 /\b(?:budget|spend(?:ing)? (?:limit|cap)|(?:prepaid )?credits?|(?:credit )?balance)\b.{0,80}\b(?:exceeded|exhausted|depleted|insufficient|too low|empty)\b/i.test(
28 message,
29 ) ||
30 /\b(?:insufficient|exhausted|depleted|no remaining|out of)\b.{0,30}\b(?:credits?|(?:credit )?balance|budget)\b/i.test(
31 message,
32 )
33 );
34}
35
36function isBudgetError(error: APICallError): boolean {
37 let body: unknown = error.data;
38 if (error.responseBody) {
39 try {
40 body = JSON.parse(error.responseBody);
41 } catch {}
42 }
43 return (
44 budgetDetails(body) ||
45 (body !== null &&
46 typeof body === "object" &&
47 budgetDetails((body as Record<string, unknown>).error)) ||
48 budgetDetails({ message: error.message })
49 );
50}
51
52export function aiBuildErrorMessage(
53 error: unknown,
54 interrupted = false,
55): string {
56 if (error instanceof DomainError) return error.message;
57 if (interrupted) return "This build was interrupted. Please try again.";
58 if (APICallError.isInstance(error)) {
59 if (
60 [400, 402, 403, 429].includes(error.statusCode || 0) &&
61 isBudgetError(error)
62 )
63 return "Neon's AI Gateway budget has been used. Check the prepaid credits or spending limit in Neon.";
64 if (error.statusCode === 429)
65 return "Neon's AI Gateway is busy. Please try again shortly.";
66 }
67 return "AI couldn't finish this build. Please try again.";
68}