7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.
TypeScript
fix(providers): fail over on 200-OK out-of-credits notices (Pollinations) (#1241)
𝐒ukaimi 𝐒ukri176261d073ac
diff --git a/server/src/__tests__/providers/openai-compat.test.ts b/server/src/__tests__/providers/openai-compat.test.tsindex 916c9d15..c0e5a8c1 100644--- a/server/src/__tests__/providers/openai-compat.test.ts+++ b/server/src/__tests__/providers/openai-compat.test.ts@@ -1,6 +1,6 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import dns from 'node:dns';-import { OpenAICompatProvider } from '../../providers/openai-compat.js';+import { OpenAICompatProvider, inBandCreditsError } from '../../providers/openai-compat.js';describe('OpenAICompatProvider', () => {let provider: OpenAICompatProvider;@@ -1039,3 +1039,94 @@ describe('reasoning: request knob + <think> extraction (P2 #16)', () => {expect(chunks.some(c => (c.choices?.[0]?.delta as any)?.reasoning_content != null)).toBe(false);});});++describe('OpenAICompatProvider in-band out-of-credits notice (#pollinations-inband)', () => {+ // The canned Pollinations top-up message returned as a 200 body.+ const CREDITS = "The account behind this API key doesn't have enough credits. " ++ 'Please top up (https://enter.pollinations.ai/top-up?ref=agent_low_balance_topup) or ' ++ 'complete a quest (https://enter.pollinations.ai/quests?ref=agent_low_balance_quests), then try again.';++ afterEach(() => vi.restoreAllMocks());++ const provider = () => new OpenAICompatProvider({ platform: 'groq', name: 'Pollinations', baseUrl: 'https://x/v1' });++ function sse(frames: string[]): any {+ const stream = new ReadableStream<Uint8Array>({+ start(controller) {+ const encoder = new TextEncoder();+ for (const f of frames) controller.enqueue(encoder.encode(f));+ controller.close();+ },+ });+ return { ok: true, body: stream, headers: new Headers() };+ }+ const dataFrame = (delta: Record<string, unknown>, finish: string | null = null) =>+ `data: ${JSON.stringify({ id: 's1', object: 'chat.completion.chunk', created: 1, model: 'm', choices: [{ index: 0, delta, finish_reason: finish }] })}\n\n`;+ async function collect<T>(g: AsyncGenerator<T>): Promise<T[]> {+ const out: T[] = [];+ for await (const c of g) out.push(c);+ return out;+ }++ describe('inBandCreditsError', () => {+ it('flags the Pollinations notice and a truncated prefix of it', () => {+ expect(inBandCreditsError(CREDITS)).toBeTruthy();+ expect(inBandCreditsError("doesn't have enough credits. Please top up")).toBeTruthy();+ });+ it('does not flag a genuine reply that merely mentions credits', () => {+ expect(inBandCreditsError("You don't need enough credits upfront — just enable billing.")).toBeNull();+ expect(inBandCreditsError('Here is a poem about the ocean.')).toBeNull();+ expect(inBandCreditsError('')).toBeNull();+ expect(inBandCreditsError(undefined)).toBeNull();+ });+ });++ it('non-stream: throws a payment-required error instead of returning the notice', async () => {+ vi.spyOn(global, 'fetch').mockImplementation(async () => ({+ ok: true,+ headers: new Headers(),+ json: () => Promise.resolve({+ id: 'x', object: 'chat.completion', created: 1, model: 'm',+ choices: [{ index: 0, message: { role: 'assistant', content: CREDITS }, finish_reason: 'stop' }],+ }),+ }) as any);+ await expect(provider().chatCompletion('k', [{ role: 'user', content: 'q' }], 'm'))+ .rejects.toThrow(/402|insufficient credit/i);+ });++ it('non-stream: a normal reply is returned unchanged', async () => {+ vi.spyOn(global, 'fetch').mockImplementation(async () => ({+ ok: true,+ headers: new Headers(),+ json: () => Promise.resolve({+ id: 'x', object: 'chat.completion', created: 1, model: 'm',+ choices: [{ index: 0, message: { role: 'assistant', content: 'hello there' }, finish_reason: 'stop' }],+ }),+ }) as any);+ const res = await provider().chatCompletion('k', [{ role: 'user', content: 'q' }], 'm');+ expect(res.choices[0].message.content).toBe('hello there');+ });++ it('stream: throws before yielding any chunk when the body is a credits notice', async () => {+ vi.spyOn(global, 'fetch').mockImplementation(async () => sse([+ dataFrame({ role: 'assistant' }),+ dataFrame({ content: CREDITS }),+ dataFrame({}, 'stop'),+ 'data: [DONE]\n\n',+ ]));+ await expect(collect(provider().streamChatCompletion('k', [{ role: 'user', content: 'q' }], 'm')))+ .rejects.toThrow(/402|insufficient credit/i);+ });++ it('stream: a normal reply passes through unchanged', async () => {+ vi.spyOn(global, 'fetch').mockImplementation(async () => sse([+ dataFrame({ role: 'assistant' }),+ dataFrame({ content: 'Hello ' }),+ dataFrame({ content: 'world' }),+ dataFrame({}, 'stop'),+ 'data: [DONE]\n\n',+ ]));+ const chunks = await collect(provider().streamChatCompletion('k', [{ role: 'user', content: 'q' }], 'm'));+ expect(chunks.map(c => c.choices?.[0]?.delta?.content ?? '').join('')).toBe('Hello world');+ });+});diff --git a/server/src/providers/openai-compat.ts b/server/src/providers/openai-compat.tsindex d982efdd..c5aff35d 100644--- a/server/src/providers/openai-compat.ts+++ b/server/src/providers/openai-compat.ts@@ -38,6 +38,27 @@ export function isMoonshotEndpoint(baseUrl: string): boolean {return MOONSHOT_HOST_SUFFIXES.some((d) => host === d || host.endsWith(`.${d}`));}+/**+ * Some free-tier upstreams (notably Pollinations) answer HTTP 200 but put an+ * out-of-credits / top-up notice in the assistant message instead of returning+ * a 402. That reads as a successful completion, so the fallback loop never+ * rotates off the dead key (#pollinations-inband). Detect the notice so callers+ * can throw a payment-required error and fail over. Kept deliberately tight —+ * requires the credits phrase AND a top-up/quest/Pollinations marker — so a+ * genuine reply that merely discusses credits does not trip it.+ */+export function inBandCreditsError(text: string | null | undefined): string | null {+ if (!text) return null;+ const t = text.toLowerCase();+ const mentionsCredits = t.includes('enough credits') || t.includes('insufficient credit');+ if (!mentionsCredits) return null;+ const topUpMarker =+ t.includes('top up') || t.includes('top-up') ||+ t.includes('complete a quest') || t.includes('pollinations');+ if (!topUpMarker) return null;+ return text.trim().slice(0, 200);+}+/*** Generic provider for platforms that use an OpenAI-compatible API.* Covers: Groq, Cerebras, NVIDIA NIM, Mistral, OpenRouter,@@ -359,6 +380,16 @@ export class OpenAICompatProvider extends BaseProvider {);}normalizeChoices(data);+ // #pollinations-inband: a 200 whose body is really an out-of-credits notice+ // must fail over, not be returned as the answer. The "402 ... insufficient+ // credit" wording makes isPaymentRequiredError classify it as retryable and+ // bench the key with the day-long payment-required cooldown.+ const creditsNotice = inBandCreditsError(+ (data.choices ?? []).map(c => contentToString((c.message as ChatMessage)?.content)).join('\n'),+ );+ if (creditsNotice) {+ throw new Error(`${this.name} API error 402: insufficient credit (upstream returned 200 with an out-of-credits notice): ${creditsNotice}`);+ }data._routed_via = { platform: this.platform, model: modelId };return data;}@@ -422,7 +453,41 @@ export class OpenAICompatProvider extends BaseProvider {// First-byte grace (#584): the same chat timeout that bounded the headers// also budgets the first stream read — NIM-style providers send SSE// headers instantly, then prefill long prompts for minutes.- yield* this.readSseStream(res, { firstByteTimeoutMs: options?.timeoutMs ?? this.timeoutMs });+ yield* this.guardInBandCreditsError(+ this.readSseStream(res, { firstByteTimeoutMs: options?.timeoutMs ?? this.timeoutMs }),+ );+ }++ /**+ * #pollinations-inband: wrap a chat stream so an in-band out-of-credits notice+ * (a 200 that streams the top-up message as content) fails over instead of+ * being shown as the answer. Only the FIRST content-bearing chunk is inspected+ * — a Pollinations credits notice arrives as a single canned message — so the+ * stream is otherwise byte-for-byte unchanged: reasoning/role chunks pass+ * straight through (first-token ttfb intact) and every chunk after the first+ * content one is untouched. Throwing on that first content chunk happens before+ * it reaches the proxy's commit point, so the fallback loop can still rotate.+ */+ private async *guardInBandCreditsError(+ src: AsyncGenerator<ChatCompletionChunk>,+ ): AsyncGenerator<ChatCompletionChunk> {+ let sawContent = false;+ for await (const chunk of src) {+ if (!sawContent) {+ const content = (chunk.choices ?? [])+ .map(c => (c.delta as { content?: unknown } | undefined)?.content)+ .filter((c): c is string => typeof c === 'string')+ .join('');+ if (content) {+ sawContent = true;+ const notice = inBandCreditsError(content);+ if (notice) {+ throw new Error(`${this.name} API error 402: insufficient credit (upstream streamed an out-of-credits notice): ${notice}`);+ }+ }+ }+ yield chunk;+ }}/** This provider's OpenAI-style model catalog URL. */