Published · 3 min read
Two free models, one schema
Content OS writes a fitness creator's scripts, carousels, captions and DM replies. It runs on the free tiers of Gemini and Groq, which is enough for one creator and costs nothing — until a provider answers with a 429, takes a minute, or returns JSON that is almost right. The tool is opened every morning to record that day's video, so “try again later” is not an acceptable answer. This is how seven AI features share one way of failing gracefully.
Ask for objects, not prose
Every feature asks for a typed object: a script is a hook, three alternative hooks, a body, a call to action, on-screen text, a list of scenes, notes and an SEO block. The interface renders each field in its own place, so it cannot depend on how a model chooses to phrase a paragraph.
/**
* Esquemas de SALIDA de la IA. Se mantienen simples (sin min/max en strings)
* porque Gemini y Groq solo soportan un subconjunto de JSON Schema.
*/
export const scriptOutputSchema = z.object({
title: z.string().describe('Título interno corto del guion (máx. 8 palabras)'),
hook: z.string().describe('Hook de los primeros 1-3 segundos. Debe detener el scroll.'),
hook_alternatives: z.array(z.string()).describe('Exactamente 3 hooks alternativos con ángulos distintos'),
body: z.string().describe('Cuerpo del guion listo para leer a cámara.'),
cta: z.string().describe('Llamada a la acción final, idealmente a DM con palabra clave'),
shot_list: z.array(shotSchema).describe('Desglose por escenas para grabar y editar'),
// ...
seo: seoSchema,
})The schema sent to the model is deliberately loose. Both providers accept only part of JSON Schema, and a minimum or maximum length on a string is a common reason for a request to be rejected outright. The descriptions carry the intent instead, and the stricter limits are applied afterwards by a second schema that validates what gets saved.
One loop for every feature
The seven routes — script, replicate, hooks, carousel, SEO, trend and DM reply — all call the same function with a schema and a prompt. It builds a list of candidates from the keys that are configured, Gemini first and Groq second, and walks through it.
// El último proveedor tiene una segunda oportunidad: a veces devuelve un JSON
// que no cumple el esquema (error 400 que el SDK no reintenta por sí solo)
const attempts = [...list, list[list.length - 1]]
for (const [i, c] of attempts.entries()) {
// Si queda un respaldo, no se insiste: mejor pasar a Groq que hacer esperar
const hasFallback = i < attempts.length - 2
const started = Date.now()
try {
const { output } = await generateText({
model: c.model,
instructions: SYSTEM_PROMPT,
prompt,
output: Output.object({ schema }),
maxRetries: hasFallback ? 0 : 1,
timeout: hasFallback ? 30_000 : 60_000,
maxOutputTokens: 16_000,
})
await log(supabase, { userId, feature, c, ok: true, latency: Date.now() - started })
return { output: output as T, model: `${c.provider}:${c.modelId}` }
} catch (error) {
lastError = error
await log(supabase, { userId, feature, c, ok: false, latency: Date.now() - started /* , error */ })
}
}Three details matter more than the loop itself:
- While a fallback is waiting, the primary gets no retries and 30 seconds. Without that, the SDK's own retries on a slow Gemini kept the user waiting; now it hands over to Groq, which in practice answers sooner.
- The last provider appears twice. A response that does not match the schema is a 400 that the SDK will not retry, and a second attempt fixes most of those.
- Generous output tokens. Reasoning models spend tokens thinking before they answer, and a full script with scenes and SEO used to be cut off in the middle of the JSON.
The log is the rate limit
Every attempt — success or failure, either provider — is written to an ai_requests table with the feature, model and latency. Before calling a model, the route counts that user's rows in the last minute and the last day.
const [perMinute, perDay] = await Promise.all([
supabase.from('ai_requests').select('id', { count: 'exact', head: true })
.eq('user_id', userId).gte('created_at', minuteAgo),
supabase.from('ai_requests').select('id', { count: 'exact', head: true })
.eq('user_id', userId).gte('created_at', dayAgo),
])
if ((perMinute.count ?? 0) >= env.AI_RATE_LIMIT_PER_MINUTE) {
throw new RateLimitError('Vas muy rápido. Espera un minuto antes de generar otra vez.', 60)
}There is no Redis and no extra service. The count cannot be reset from the browser because row-level security on that table allows a user to insert and read their own rows, and nothing else: there is no update or delete policy. Failed attempts count too, which is intended — a burst of failures is exactly when a client should slow down.
Facts stay facts
A script can cite a real client's result: weeks, kilos, centimeters, the habits that changed. That is personal data, and the business rule is that it may only be used with the client's consent. The form only offers transformations that have it, but the form is not the boundary — the route is.
if (input.transformation_id) {
const { data: t } = await supabase
.from('transformations').select('*')
.eq('id', input.transformation_id).maybeSingle()
if (!t) return error('Esa transformación no existe.', 404)
// Regla de negocio: sin consentimiento, la IA no puede usarla
if (!t.consent_given) return error('Esa transformación no tiene consentimiento.', 400)
proof = describeTransformation(t)
}The transformation is then passed as exact numbers in its own block of the prompt, with an instruction not to round them up. A model asked to write persuasive copy will otherwise improve on the truth.
What it costs
- Two providers means two sets of quirks. Prompts have to work with both, and the output from Groq is sometimes a little flatter than Gemini's.
- A loose schema moves validation to a second step, which is one more thing to keep in sync.
- Free tiers still have a ceiling; the daily limit is set below it on purpose.
- Seventy checks run the whole pipeline against a mock model, so none of this needs an API key to test — but the real providers are only exercised in use.