Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 18 additions & 5 deletions lib/ai/analyze.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
* Uses withFallback so any provider failure auto-retries on next key.
*/

import { withFallback, type Provider } from './providers';
import { withFallback, UnusableOutputError, type Provider } from './providers';
import { getSetting } from '../db';
import type OpenAI from 'openai';

Expand Down Expand Up @@ -206,14 +206,21 @@ async function analyzeDimension(
const response = await provider.client.chat.completions.create({
model: provider.model,
messages,
max_tokens: 1800,
max_tokens: 3000,
temperature: 0.85,
...(provider.jsonMode ? { response_format: { type: 'json_object' as const } } : {}),
});

const parsed = parseDimensionJson(response.choices[0]?.message?.content ?? '');
const choice = response.choices[0];
const content = choice?.message?.content ?? '';
const parsed = parseDimensionJson(content);
if (!parsed) {
// Throwing (not returning a fake score) lets withFallback try the next provider.
throw new Error(`${provider.name} returned output that is not valid audit JSON`);
// Throwing (not returning a fake score) lets withFallback try the next provider. The snippet and
// finish_reason show whether the model was cut off, answered in prose, or put everything in reasoning.
const snippet = content.replace(/\s+/g, ' ').slice(0, 160);
throw new UnusableOutputError(
`${provider.name} returned output that is not valid audit JSON (finish_reason=${choice?.finish_reason ?? 'none'}, ${content.length} chars: "${snippet}")`,
);
}
parsed.dimension = dimension;
return parsed;
Expand Down Expand Up @@ -241,6 +248,9 @@ export function parseDimensionJson(raw: string): DimensionResult | null {

// ─── Full audit (all dimensions, with fallback per dimension) ─────────────────

/** Stop starting new dimensions after this long (the route's maxDuration is 120s). */
const AUDIT_TIME_BUDGET_MS = 85_000;

export async function runAudit(params: {
imageBase64: string;
mimeType: 'image/jpeg' | 'image/png' | 'image/webp';
Expand All @@ -261,9 +271,12 @@ export async function runAudit(params: {
const results: DimensionResult[] = [];
let lastProvider = 'unknown';
let succeeded = 0;
const startedAt = Date.now();

// Analyze dimensions sequentially to avoid hammering rate limits
for (const dim of dimensions) {
// The route has a hard 120s limit. Past this point finish with the bits we have rather than get cut off.
if (succeeded > 0 && Date.now() - startedAt > AUDIT_TIME_BUDGET_MS) break;
let result: DimensionResult;
let providerUsed = lastProvider;
try {
Expand Down
144 changes: 92 additions & 52 deletions lib/ai/providers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,29 @@ export type Provider = {
client: OpenAI;
model: string;
supportsVision: boolean;
/** Ask for response_format json_object (only set where the provider documents support). */
jsonMode?: boolean;
};

/** Thrown when a model answers but not with usable audit JSON. */
export class UnusableOutputError extends Error {
constructor(message: string) {
super(message);
this.name = 'UnusableOutputError';
}
}

// maxRetries 0: the SDK's default of 2 retries hammers a rate-limited free tier and slows every
// failure; withFallback already moves on to the next provider. The timeout keeps one hung
// provider from eating the whole function budget.
function makeClient(baseURL: string, apiKey: string, extraHeaders?: Record<string, string>): OpenAI {
return new OpenAI({
baseURL,
apiKey,
dangerouslyAllowBrowser: false,
defaultHeaders: extraHeaders,
maxRetries: 0,
timeout: 30_000,
});
}

Expand All @@ -27,60 +42,46 @@ const OPENROUTER_HEADERS = {
'X-Title': 'RoastLab',
};

interface ProviderConfig {
name: string;
baseURL: string;
apiKey: string;
model: string;
headers?: Record<string, string>;
jsonMode?: boolean;
}

/**
* Ordered fallback chain.
* Index 0 = primary; last index = last resort.
* Add/remove entries here as keys change.
*
* Model IDs last checked 2026-11-03 against the providers' own errors and docs:
* - Groq retired meta-llama/llama-4-scout-17b-16e-instruct on 2026-07-17 (every call returned 404).
* Its vision model is now qwen/qwen3.8-27b (preview, JSON mode supported, 3 images per request).
* - OpenRouter free models: only list ones that actually answer chat completions. Being
* image-capable in /models is not enough (thinkingmachines/inkling:free returns 403
* "only available on agentic harnesses").
*/
export function getProviders(): Provider[] {
return [
// Groq — only working reliable free vision model. Both keys use the same
// model (llama-4-scout is Groq's ONLY vision model) to double free quota.
{
name: 'groq-1',
client: makeClient('https://api.groq.com/openai/v1', process.env.GROQ_KEY_1 ?? ''),
model: 'meta-llama/llama-4-scout-17b-16e-instruct',
supportsVision: true,
},
{
name: 'groq-2',
client: makeClient('https://api.groq.com/openai/v1', process.env.GROQ_KEY_2 ?? ''),
model: 'meta-llama/llama-4-scout-17b-16e-instruct',
supportsVision: true,
},
// OpenRouter free vision models — verified live against GET /api/v1/models
// on 2026-11-02. qwen2.5-vl-7b, nemotron-nano-12b-v2-vl and
// llama-3.2-11b-vision-instruct were all retired/renamed and had been
// returning "not a valid model ID" on every request.
{
name: 'openrouter-gemma',
client: makeClient('https://openrouter.ai/api/v1', process.env.OPENROUTER_KEY_1 ?? '', OPENROUTER_HEADERS),
model: 'google/gemma-4-26b-a4b-it:free',
supportsVision: true,
},
{
name: 'openrouter-nemotron',
client: makeClient('https://openrouter.ai/api/v1', process.env.OPENROUTER_KEY_2 ?? '', OPENROUTER_HEADERS),
model: 'nvidia/nemotron-3.5-super-vl:free',
supportsVision: true,
},
{
name: 'openrouter-gemma-31b',
client: makeClient('https://openrouter.ai/api/v1', process.env.OPENROUTER_KEY_1 ?? '', OPENROUTER_HEADERS),
model: 'google/gemma-4-31b-it:free',
supportsVision: true,
},
{
name: 'openrouter-inkling',
client: makeClient('https://openrouter.ai/api/v1', process.env.OPENROUTER_KEY_2 ?? '', OPENROUTER_HEADERS),
model: 'thinkingmachines/inkling:free',
const configs: ProviderConfig[] = [
{ name: 'groq-1', baseURL: 'https://api.groq.com/openai/v1', apiKey: process.env.GROQ_KEY_1 ?? '', model: 'qwen/qwen3.8-27b', jsonMode: true },
{ name: 'groq-2', baseURL: 'https://api.groq.com/openai/v1', apiKey: process.env.GROQ_KEY_2 ?? '', model: 'qwen/qwen3.8-27b', jsonMode: true },
{ name: 'openrouter-gemma', baseURL: 'https://openrouter.ai/api/v1', apiKey: process.env.OPENROUTER_KEY_1 ?? '', model: 'google/gemma-4-26b-a4b-it:free', headers: OPENROUTER_HEADERS },
{ name: 'openrouter-nemotron', baseURL: 'https://openrouter.ai/api/v1', apiKey: process.env.OPENROUTER_KEY_2 ?? '', model: 'nvidia/nemotron-3.5-super-vl:free', headers: OPENROUTER_HEADERS },
{ name: 'openrouter-gemma-31b', baseURL: 'https://openrouter.ai/api/v1', apiKey: process.env.OPENROUTER_KEY_1 ?? '', model: 'google/gemma-4-31b-it:free', headers: OPENROUTER_HEADERS },
];

// Filter on the key BEFORE building clients: the SDK throws synchronously on an empty apiKey.
return configs
.filter((c) => c.apiKey.length > 10)
.map((c) => ({
name: c.name,
client: makeClient(c.baseURL, c.apiKey, c.headers),
model: c.model,
supportsVision: true,
},
].filter((p) => {
// Skip providers with missing keys at runtime
const key = p.client.apiKey;
return key && key.length > 10;
});
jsonMode: c.jsonMode,
}));
}

/** True when worth trying next provider (rate limit, quota, server error, model not found, network). */
Expand All @@ -95,29 +96,66 @@ export function isRetryableError(err: unknown): boolean {
// 5xx = server error
return err.status === 400 || err.status === 403 || err.status === 404 || err.status === 429 || err.status >= 500;
}
// Network errors, timeouts, DNS failures — always retry next provider
// Network errors, timeouts, DNS failures, unusable model output — always retry next provider
return true;
}

/* ─── provider health ───────────────────────────────────────────────────────
A provider that failed in a way that will not fix itself within seconds (retired model, no
access, bad request, quota, rate limit, a model that never returns JSON) is skipped for a
while, so the remaining dimensions of an audit do not pay for it again. In-memory: lasts as
long as the warm function instance, which is what an audit needs. */

const unavailableUntil = new Map<string, number>();

/** How long to skip a provider after this failure; 0 = keep trying it. */
export function cooldownMs(err: unknown): number {
if (err instanceof UnusableOutputError) return 60_000;
if (!(err instanceof OpenAI.APIError)) return 0;
const status = err.status;
if (status === 404 || status === 401 || status === 403) return 30 * 60_000;
if (status === 400) return 10 * 60_000;
if (status === 429) {
const retryAfter = Number((err.headers as Record<string, string> | undefined)?.['retry-after']);
return Number.isFinite(retryAfter) && retryAfter > 0 ? Math.min(retryAfter * 1000, 120_000) : 30_000;
}
return 0;
}

export function markUnavailable(name: string, ms: number, now = Date.now()): void {
if (ms > 0) unavailableUntil.set(name, now + ms);
}

export function isAvailable(name: string, now = Date.now()): boolean {
return (unavailableUntil.get(name) ?? 0) <= now;
}

export function resetProviderHealth(): void {
unavailableUntil.clear();
}

/** Status + short message for logs, with anything that looks like an API key redacted. */
function describeError(err: unknown): string {
const status = err instanceof OpenAI.APIError ? err.status : undefined;
const msg = (err instanceof Error ? err.message : String(err))
.replace(/\b(?:gsk_|sk-|sk_|fc-)[\w-]{6,}/g, '[redacted]')
.replace(/\s+/g, ' ')
.slice(0, 200);
.slice(0, 240);
return `${status ?? 'no-status'} ${msg}`;
}

/**
* Run fn with automatic fallback across providers.
* Tries each provider in order; stops on first success.
* Tries each available provider in order; stops on first success.
* Re-throws the last error if all providers fail.
*/
export async function withFallback<T>(
fn: (provider: Provider) => Promise<T>
): Promise<{ result: T; providerUsed: string }> {
const providers = getProviders();
const all = getProviders();
// If every provider is cooling down, try them all anyway rather than failing without a call.
const healthy = all.filter((p) => isAvailable(p.name));
const providers = healthy.length > 0 ? healthy : all;
let lastErr: unknown;

for (const provider of providers) {
Expand All @@ -127,7 +165,9 @@ export async function withFallback<T>(
} catch (err) {
lastErr = err;
if (isRetryableError(err)) {
console.warn(`[ai] ${provider.name} (${provider.model}) failed: ${describeError(err)} — trying next`);
const cool = cooldownMs(err);
markUnavailable(provider.name, cool);
console.warn(`[ai] ${provider.name} (${provider.model}) failed: ${describeError(err)} — trying next${cool ? ` (skipping it for ${Math.round(cool / 1000)}s)` : ''}`);
continue;
}
// Non-retryable (auth error, bad request) — fail fast
Expand Down
Loading