From cc0611b6a0b7fdc77db357af2b7b666064c48f9c Mon Sep 17 00:00:00 2001 From: Jose Selesan Date: Thu, 29 Oct 2026 10:53:15 -0300 Subject: [PATCH] fix: improve dictation --- apps/api/src/lib/gemini.ts | 58 ++++++++++++------- apps/api/src/modules/voice/split/prompt.ts | 1 + .../api/src/modules/voice/split/route.test.ts | 26 +++++++++ .../lib/natural-input/voice-examples.test.ts | 3 + packages/shared/src/voice.ts | 4 ++ 5 files changed, 71 insertions(+), 21 deletions(-) diff --git a/apps/api/src/lib/gemini.ts b/apps/api/src/lib/gemini.ts index 6abb93f..13b3b4f 100644 --- a/apps/api/src/lib/gemini.ts +++ b/apps/api/src/lib/gemini.ts @@ -6,11 +6,18 @@ * key in the browser bundle): * - `GEMINI_API_KEY`: AI Studio API key. Without it every call fails with `missing-key`. * - `GEMINI_MODEL`: model id, `gemma-4-26b-a4b-it` by default. - * - `GEMINI_TIMEOUT_MS`: request timeout, 8000 ms by default. + * - `GEMINI_TIMEOUT_MS`: request timeout, 8000 ms by default (retries included). + * + * Gemma 4 writes out its reasoning before answering, which takes from 5 to over 30 + * seconds, so the request asks for `thinkingLevel: 'minimal'` (about a second). The API + * also answers 5xx now and then, fast; those calls are retried once. */ const GEMINI_API_URL = 'https://generativelanguage.googleapis.com/v1beta/models' +/** Attempts per call when the API answers 5xx. */ +const MAX_ATTEMPTS = 2 + /** Gemma 4's small, fast variant (a mixture of experts with ~4B active parameters). */ export const DEFAULT_GEMINI_MODEL = 'gemma-4-26b-a4b-it' @@ -74,28 +81,37 @@ export class GeminiClient implements TextGenerator { async generate({ systemInstruction, turns }: GenerateInput): Promise { if (!this.config.apiKey) throw new GeminiError('missing-key') - let response: Response - try { - response = await this.fetchFn( - `${GEMINI_API_URL}/${encodeURIComponent(this.config.model)}:generateContent`, - { - method: 'POST', - headers: { 'content-type': 'application/json', 'x-goog-api-key': this.config.apiKey }, - body: JSON.stringify({ - systemInstruction: { parts: [{ text: systemInstruction }] }, - contents: turns.map(({ role, text }) => ({ role, parts: [{ text }] })), - generationConfig: { temperature: 0 }, - }), - signal: AbortSignal.timeout(this.config.timeoutMs), - }, - ) - } catch (error) { - const name = error instanceof Error ? error.name : '' - throw new GeminiError( - name === 'TimeoutError' || name === 'AbortError' ? 'timeout' : 'network', - ) + // One deadline for every attempt, so a retry never makes the user wait longer. + const signal = AbortSignal.timeout(this.config.timeoutMs) + const request = { + method: 'POST', + headers: { 'content-type': 'application/json', 'x-goog-api-key': this.config.apiKey }, + body: JSON.stringify({ + systemInstruction: { parts: [{ text: systemInstruction }] }, + contents: turns.map(({ role, text }) => ({ role, parts: [{ text }] })), + generationConfig: { temperature: 0, thinkingConfig: { thinkingLevel: 'minimal' } }, + }), + signal, } + let response: Response | undefined + for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) { + try { + response = await this.fetchFn( + `${GEMINI_API_URL}/${encodeURIComponent(this.config.model)}:generateContent`, + request, + ) + } catch (error) { + const name = error instanceof Error ? error.name : '' + throw new GeminiError( + name === 'TimeoutError' || name === 'AbortError' ? 'timeout' : 'network', + ) + } + + if (response.status < 500) break + } + + if (!response) throw new GeminiError('network') if (response.status === 429) throw new GeminiError('rate-limited') if (!response.ok) throw new GeminiError(`http-${response.status}`) diff --git a/apps/api/src/modules/voice/split/prompt.ts b/apps/api/src/modules/voice/split/prompt.ts index ec90267..5526810 100644 --- a/apps/api/src/modules/voice/split/prompt.ts +++ b/apps/api/src/modules/voice/split/prompt.ts @@ -8,6 +8,7 @@ Recibís la transcripción de lo que alguien dictó y respondés SOLO con un arr Reglas: - Un elemento por producto. +- La transcripción casi nunca trae comas: los productos nombrados uno tras otro son elementos distintos ("azúcar leche y café" son 3), salvo que juntos formen un solo producto ("dulce de leche", "queso crema", "pan rallado"). - Números en dígitos: "dos" → 2, "media docena" → 6, "una docena" → 12, "un kilo" → 1 kg, "un kilo y medio" → 1,5 kg. - Unidades abreviadas: g, kg, ml, l. Los envases quedan como palabra: "1 lata", "2 paquetes". - La cantidad va al principio: "2 l de leche", "400 g de queso", "12 huevos". diff --git a/apps/api/src/modules/voice/split/route.test.ts b/apps/api/src/modules/voice/split/route.test.ts index 4abd7bd..56e87eb 100644 --- a/apps/api/src/modules/voice/split/route.test.ts +++ b/apps/api/src/modules/voice/split/route.test.ts @@ -120,6 +120,32 @@ describe('POST /api/voice/split', () => { expect(JSON.stringify(warnings)).toContain('invalid-json') }) + it('asks for minimal thinking and retries a 5xx once', async () => { + let calls = 0 + const fetchMock = mockFetch(async () => + ++calls === 1 + ? new Response('{}', { status: 500 }) + : modelAnswer('["Azúcar", "Leche", "Café"]'), + ) + + const response = await split({ text: 'azúcar leche y café' }) + + expect(await response.json()).toEqual({ items: ['Azúcar', 'Leche', 'Café'] }) + expect(fetchMock).toHaveBeenCalledTimes(2) + const sent = JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body)) + expect(sent.generationConfig.thinkingConfig).toEqual({ thinkingLevel: 'minimal' }) + }) + + it('falls back when the model answers 5xx twice', async () => { + const fetchMock = mockFetch(async () => new Response('{}', { status: 503 })) + + const response = await split({ text: 'pan y leche' }) + + expect(await response.json()).toEqual({ items: ['pan', 'leche'] }) + expect(fetchMock).toHaveBeenCalledTimes(2) + expect(JSON.stringify(warnings)).toContain('http-503') + }) + it('falls back without calling the model when there is no API key', async () => { delete process.env.GEMINI_API_KEY const fetchMock = mockFetch(async () => modelAnswer('[]')) diff --git a/apps/web/src/lib/natural-input/voice-examples.test.ts b/apps/web/src/lib/natural-input/voice-examples.test.ts index 3199190..5bbdac0 100644 --- a/apps/web/src/lib/natural-input/voice-examples.test.ts +++ b/apps/web/src/lib/natural-input/voice-examples.test.ts @@ -26,6 +26,9 @@ const EXPECTED: Record< '6 unidades de yogur': { name: 'Yogur', amount: 6, unit: null, notes: null }, '400g de queso': { name: 'Queso', amount: 400, unit: 'g', notes: null }, 'Leche (descremada)': { name: 'Leche', amount: null, unit: null, notes: 'Descremada' }, + Azúcar: { name: 'Azúcar', amount: null, unit: null, notes: null }, + Leche: { name: 'Leche', amount: null, unit: null, notes: null }, + Café: { name: 'Café', amount: null, unit: null, notes: null }, } describe('dictation few-shot examples', () => { diff --git a/packages/shared/src/voice.ts b/packages/shared/src/voice.ts index 6d806df..8f743e5 100644 --- a/packages/shared/src/voice.ts +++ b/packages/shared/src/voice.ts @@ -42,4 +42,8 @@ export const VOICE_SPLIT_EXAMPLES: { said: string; items: string[] }[] = [ said: 'cuatrocientos gramos de queso y leche descremada', items: ['400g de queso', 'Leche (descremada)'], }, + { + said: 'azúcar leche y café', + items: ['Azúcar', 'Leche', 'Café'], + }, ]