/** * Map an inference error (as surfaced by the AI SDK chat hook) to something * a researcher can act on. The backend prefixes provider failures with * `HTTP :` (see backend/src/agent/stream-errors.ts); pre-stream * failures arrive as a JSON body `{ "error": "..." }`. */ export type ChatErrorKind = "auth" | "credits" | "rate" | "network" | "other"; export interface ChatErrorInfo { kind: ChatErrorKind; title: string; detail: string; action?: { label: string; href: string }; retryable: boolean; } export const HF_BILLING_URL = "https://huggingface.co/settings/billing"; export const HF_TOKENS_URL = "https://huggingface.co/settings/tokens"; function unwrap(raw: string): string { const trimmed = raw.trim(); if (!trimmed.startsWith("{")) return trimmed; try { const parsed = JSON.parse(trimmed) as { error?: unknown; message?: unknown }; if (typeof parsed.error === "string") return parsed.error; if (typeof parsed.message === "string") return parsed.message; } catch { // Not JSON after all: show it as is. } return trimmed; } function statusOf(text: string): number | null { const m = text.match(/\bHTTP (\d{3})\b/) ?? text.match(/\bstatus(?: code)?:? (\d{3})\b/i); return m ? Number(m[1]) : null; } export function describeChatError(raw: string | null | undefined): ChatErrorInfo { const message = unwrap(raw || "An error occurred"); const status = statusOf(message); const detail = message.replace(/^HTTP \d{3}:\s*/, ""); if (status === 402 || /\b(credits?|payment required|billing|exceeded your monthly)\b/i.test(message)) { return { kind: "credits", title: "You are out of inference credits", detail: "The studio runs on your Hugging Face Inference Providers credits (PRO includes $2 per month). " + "Add credits or wait for the monthly reset, then retry.", action: { label: "Check your credits", href: HF_BILLING_URL }, retryable: true, }; } if (status === 429 || /\b(rate limit|too many requests)\b/i.test(message)) { return { kind: "rate", title: "Too many requests", detail: "The inference provider is rate limiting you. Wait a few seconds, then retry.", retryable: true, }; } if (status === 401 || status === 403 || /\b(unauthori[sz]ed|no hugging face token|invalid token|forbidden)\b/i.test(message)) { return { kind: "auth", title: "Not signed in to Hugging Face inference", detail: "Your session has no token allowed to call Inference Providers. Sign in again (or set HF_TOKEN when running locally), then retry.", action: { label: "Manage tokens", href: HF_TOKENS_URL }, retryable: true, }; } if (/\b(failed to fetch|network ?error|fetch failed|socket hang up|ECONNRESET|load failed)\b/i.test(message)) { return { kind: "network", title: "Connection lost", detail: "The request did not reach the server. Check your connection, then retry.", retryable: true, }; } return { kind: "other", title: "The assistant stopped with an error", detail, retryable: true }; }