3 Commits

Author SHA1 Message Date
Jose Selesan
cc0611b6a0 fix: improve dictation 2026-10-29 10:53:15 -03:00
Jose Selesan
9159dd9c9b Merge branch 'feat/password-recovery' 2026-10-29 10:30:59 -03:00
01769314cb Merge pull request 'feat(auth): recover a password with a code sent by email' (#1) from feat/password-recovery into main
Reviewed-on: #1
2026-10-29 13:14:51 +00:00
5 changed files with 71 additions and 21 deletions

View File

@@ -6,11 +6,18 @@
* key in the browser bundle): * key in the browser bundle):
* - `GEMINI_API_KEY`: AI Studio API key. Without it every call fails with `missing-key`. * - `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_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' 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). */ /** Gemma 4's small, fast variant (a mixture of experts with ~4B active parameters). */
export const DEFAULT_GEMINI_MODEL = 'gemma-4-26b-a4b-it' export const DEFAULT_GEMINI_MODEL = 'gemma-4-26b-a4b-it'
@@ -74,20 +81,25 @@ export class GeminiClient implements TextGenerator {
async generate({ systemInstruction, turns }: GenerateInput): Promise<string> { async generate({ systemInstruction, turns }: GenerateInput): Promise<string> {
if (!this.config.apiKey) throw new GeminiError('missing-key') if (!this.config.apiKey) throw new GeminiError('missing-key')
let response: Response // One deadline for every attempt, so a retry never makes the user wait longer.
try { const signal = AbortSignal.timeout(this.config.timeoutMs)
response = await this.fetchFn( const request = {
`${GEMINI_API_URL}/${encodeURIComponent(this.config.model)}:generateContent`,
{
method: 'POST', method: 'POST',
headers: { 'content-type': 'application/json', 'x-goog-api-key': this.config.apiKey }, headers: { 'content-type': 'application/json', 'x-goog-api-key': this.config.apiKey },
body: JSON.stringify({ body: JSON.stringify({
systemInstruction: { parts: [{ text: systemInstruction }] }, systemInstruction: { parts: [{ text: systemInstruction }] },
contents: turns.map(({ role, text }) => ({ role, parts: [{ text }] })), contents: turns.map(({ role, text }) => ({ role, parts: [{ text }] })),
generationConfig: { temperature: 0 }, generationConfig: { temperature: 0, thinkingConfig: { thinkingLevel: 'minimal' } },
}), }),
signal: AbortSignal.timeout(this.config.timeoutMs), 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) { } catch (error) {
const name = error instanceof Error ? error.name : '' const name = error instanceof Error ? error.name : ''
@@ -96,6 +108,10 @@ export class GeminiClient implements TextGenerator {
) )
} }
if (response.status < 500) break
}
if (!response) throw new GeminiError('network')
if (response.status === 429) throw new GeminiError('rate-limited') if (response.status === 429) throw new GeminiError('rate-limited')
if (!response.ok) throw new GeminiError(`http-${response.status}`) if (!response.ok) throw new GeminiError(`http-${response.status}`)

View File

@@ -8,6 +8,7 @@ Recibís la transcripción de lo que alguien dictó y respondés SOLO con un arr
Reglas: Reglas:
- Un elemento por producto. - 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. - 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". - 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". - La cantidad va al principio: "2 l de leche", "400 g de queso", "12 huevos".

View File

@@ -120,6 +120,32 @@ describe('POST /api/voice/split', () => {
expect(JSON.stringify(warnings)).toContain('invalid-json') 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 () => { it('falls back without calling the model when there is no API key', async () => {
delete process.env.GEMINI_API_KEY delete process.env.GEMINI_API_KEY
const fetchMock = mockFetch(async () => modelAnswer('[]')) const fetchMock = mockFetch(async () => modelAnswer('[]'))

View File

@@ -26,6 +26,9 @@ const EXPECTED: Record<
'6 unidades de yogur': { name: 'Yogur', amount: 6, unit: null, notes: null }, '6 unidades de yogur': { name: 'Yogur', amount: 6, unit: null, notes: null },
'400g de queso': { name: 'Queso', amount: 400, unit: 'g', notes: null }, '400g de queso': { name: 'Queso', amount: 400, unit: 'g', notes: null },
'Leche (descremada)': { name: 'Leche', amount: null, unit: null, notes: 'Descremada' }, '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', () => { describe('dictation few-shot examples', () => {

View File

@@ -42,4 +42,8 @@ export const VOICE_SPLIT_EXAMPLES: { said: string; items: string[] }[] = [
said: 'cuatrocientos gramos de queso y leche descremada', said: 'cuatrocientos gramos de queso y leche descremada',
items: ['400g de queso', 'Leche (descremada)'], items: ['400g de queso', 'Leche (descremada)'],
}, },
{
said: 'azúcar leche y café',
items: ['Azúcar', 'Leche', 'Café'],
},
] ]