Compare commits
3 Commits
feat/passw
...
cc0611b6a0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cc0611b6a0 | ||
|
|
9159dd9c9b | ||
| 01769314cb |
@@ -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,20 +81,25 @@ export class GeminiClient implements TextGenerator {
|
||||
async generate({ systemInstruction, turns }: GenerateInput): Promise<string> {
|
||||
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`,
|
||||
{
|
||||
// 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 },
|
||||
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) {
|
||||
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.ok) throw new GeminiError(`http-${response.status}`)
|
||||
|
||||
|
||||
@@ -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".
|
||||
|
||||
@@ -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('[]'))
|
||||
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -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é'],
|
||||
},
|
||||
]
|
||||
|
||||
Reference in New Issue
Block a user