diff --git a/.env.example b/.env.example index 4de2e9d..c9dda70 100644 --- a/.env.example +++ b/.env.example @@ -27,6 +27,13 @@ WEB_APP_URL="http://localhost:7153" # GEMINI_MODEL="gemma-4-26b-a4b-it" # Optional: timeout of the model request, in milliseconds # GEMINI_TIMEOUT_MS="8000" +# Dictation: Groq API key, backend only (NEVER prefix it with VITE_). When set, Groq +# splits dictated text instead of Gemini; it is faster and steadier. +# GROQ_API_KEY="" +# Optional: model id +# GROQ_MODEL="openai/gpt-oss-120b" +# Optional: timeout of the model request, in milliseconds +# GROQ_TIMEOUT_MS="8000" # --- apps/web --- # Optional. In dev, Vite proxies /api/* to the API (http://localhost:4100), so diff --git a/AGENTS.md b/AGENTS.md index 802efef..c46186d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -7,8 +7,8 @@ Biome as the only JS/TS tool and the text Bun lockfile committed. It is deployed Dokploy (`docker-compose.yml`); there is no hosted CI. Not done yet: product features are just starting (sign-up, password recovery with an emailed OTP, shopping lists, list items and invitations exist; -there is no Google login and no email verification; the `voice` module splits dictated text with Gemma 4 -through the Gemini API). The `health` module is the reference example. +there is no Google login and no email verification; the `voice` module splits dictated text with Groq, or Gemma 4 +through the Gemini API when Groq is not configured). The `health` module is the reference example. ## Stack (source of truth: `STACK.md`) @@ -100,7 +100,8 @@ Run from the repo root. Verification order is `build`, then `lint` → `typechec `apps/web/nginx.conf`, which also proxies `/api/*` to `http://superlist-api:4100` (re-resolved through Docker's DNS, so API redeploys don't leave nginx on a stale IP). Required env vars are interpolated by Compose (`DATABASE_URL`, `BETTER_AUTH_SECRET`, `BETTER_AUTH_URL`, `CORS_ORIGIN`, `WEB_APP_URL`); set them - in Dokploy. The dictation variables (`GEMINI_API_KEY`, `GEMINI_MODEL`, `GEMINI_TIMEOUT_MS`) are optional and + in Dokploy. The dictation variables (`GROQ_API_KEY`, `GROQ_MODEL`, `GROQ_TIMEOUT_MS`, `GEMINI_API_KEY`, `GEMINI_MODEL`, + `GEMINI_TIMEOUT_MS`) are optional (Groq wins when its key is set) and backend-only — never give them a `VITE_` prefix, or Vite would ship the key in the browser bundle. There is no hosted CI. - Generated files are gitignored and must never be edited by hand: `apps/web/src/routeTree.gen.ts`, `apps/api/src/generated/`. diff --git a/apps/api/.env.example b/apps/api/.env.example index 5010476..111e21a 100644 --- a/apps/api/.env.example +++ b/apps/api/.env.example @@ -20,3 +20,10 @@ WEB_APP_URL="http://localhost:7153" # GEMINI_MODEL="gemma-4-26b-a4b-it" # Optional: timeout of the model request, in milliseconds # GEMINI_TIMEOUT_MS="8000" +# Dictation: Groq API key, backend only (NEVER prefix it with VITE_). When set, Groq +# splits dictated text instead of Gemini; it is faster and steadier. +# GROQ_API_KEY="" +# Optional: model id +# GROQ_MODEL="openai/gpt-oss-120b" +# Optional: timeout of the model request, in milliseconds +# GROQ_TIMEOUT_MS="8000" diff --git a/apps/api/src/lib/gemini.ts b/apps/api/src/lib/gemini.ts index 13b3b4f..902fa30 100644 --- a/apps/api/src/lib/gemini.ts +++ b/apps/api/src/lib/gemini.ts @@ -13,10 +13,15 @@ * also answers 5xx now and then, fast; those calls are retried once. */ -const GEMINI_API_URL = 'https://generativelanguage.googleapis.com/v1beta/models' +import { + type GenerateInput, + ModelError, + postJson, + readTimeout, + type TextGenerator, +} from './text-generator' -/** Attempts per call when the API answers 5xx. */ -const MAX_ATTEMPTS = 2 +const GEMINI_API_URL = 'https://generativelanguage.googleapis.com/v1beta/models' /** Gemma 4's small, fast variant (a mixture of experts with ~4B active parameters). */ export const DEFAULT_GEMINI_MODEL = 'gemma-4-26b-a4b-it' @@ -31,99 +36,38 @@ export type GeminiConfig = { /** Reads the configuration from the environment, with the defaults above. */ export function geminiConfigFromEnv(env: Record = process.env) { - const timeout = Number.parseInt(env.GEMINI_TIMEOUT_MS ?? '', 10) - return { apiKey: env.GEMINI_API_KEY?.trim() || undefined, model: env.GEMINI_MODEL?.trim() || DEFAULT_GEMINI_MODEL, - timeoutMs: Number.isFinite(timeout) && timeout > 0 ? timeout : DEFAULT_GEMINI_TIMEOUT_MS, + timeoutMs: readTimeout(env.GEMINI_TIMEOUT_MS, DEFAULT_GEMINI_TIMEOUT_MS), } satisfies GeminiConfig } -/** Why a call failed, short enough to log (it never includes the prompt). */ -export type GeminiFailureReason = - | 'missing-key' - | 'timeout' - | 'rate-limited' - | `http-${number}` - | 'network' - | 'empty-response' - -export class GeminiError extends Error { - constructor(readonly reason: GeminiFailureReason) { - super(`Gemini request failed: ${reason}`) - this.name = 'GeminiError' - } -} - -/** One turn of the conversation: `user` for the input, `model` for an example answer. */ -export type GeminiTurn = { role: 'user' | 'model'; text: string } - -export type GenerateInput = { - systemInstruction: string - turns: GeminiTurn[] -} - type GenerateContentResponse = { candidates?: { content?: { parts?: { text?: string; thought?: boolean }[] } }[] } -/** Something that answers a prompt with text: the Gemini client, or a fake in tests. */ -export type TextGenerator = { generate(input: GenerateInput): Promise } - export class GeminiClient implements TextGenerator { constructor( private readonly config: GeminiConfig = geminiConfigFromEnv(), private readonly fetchFn: typeof fetch = fetch, ) {} - /** The model's text answer. Throws `GeminiError` on any failure. */ + /** The model's text answer. Throws `ModelError` on any failure. */ async generate({ systemInstruction, turns }: GenerateInput): Promise { - if (!this.config.apiKey) throw new GeminiError('missing-key') + if (!this.config.apiKey) throw new ModelError('missing-key') - // 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({ + const body = (await postJson( + this.fetchFn, + `${GEMINI_API_URL}/${encodeURIComponent(this.config.model)}:generateContent`, + { 'x-goog-api-key': this.config.apiKey }, + { 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}`) - - let body: GenerateContentResponse - try { - body = (await response.json()) as GenerateContentResponse - } catch (error) { - const name = error instanceof Error ? error.name : '' - throw new GeminiError( - name === 'TimeoutError' || name === 'AbortError' ? 'timeout' : 'empty-response', - ) - } + }, + this.config.timeoutMs, + )) as GenerateContentResponse // Thinking models may send their reasoning as `thought` parts: only the answer counts. const text = (body.candidates?.[0]?.content?.parts ?? []) @@ -132,7 +76,7 @@ export class GeminiClient implements TextGenerator { .join('') .trim() - if (!text) throw new GeminiError('empty-response') + if (!text) throw new ModelError('empty-response') return text } diff --git a/apps/api/src/lib/groq.ts b/apps/api/src/lib/groq.ts new file mode 100644 index 0000000..ec285bf --- /dev/null +++ b/apps/api/src/lib/groq.ts @@ -0,0 +1,79 @@ +/** + * Minimal client for Groq's OpenAI-compatible `chat/completions` endpoint, called with + * `fetch` — no SDK. Groq answers in about a second, which suits dictation. The model is + * a reasoning one (gpt-oss): Groq returns its reasoning apart, so `content` is the answer. + * + * Configuration (backend only — never prefix these with `VITE_`, or Vite would put the + * key in the browser bundle): + * - `GROQ_API_KEY`: Groq API key (`gsk_…`). Without it every call fails with `missing-key`. + * - `GROQ_MODEL`: model id, `openai/gpt-oss-120b` by default. + * - `GROQ_TIMEOUT_MS`: request timeout, 8000 ms by default (retries included). + */ + +import { + type GenerateInput, + ModelError, + postJson, + readTimeout, + type TextGenerator, +} from './text-generator' + +const GROQ_API_URL = 'https://api.groq.com/openai/v1/chat/completions' + +export const DEFAULT_GROQ_MODEL = 'openai/gpt-oss-120b' + +export const DEFAULT_GROQ_TIMEOUT_MS = 8000 + +export type GroqConfig = { + apiKey: string | undefined + model: string + timeoutMs: number +} + +/** Reads the configuration from the environment, with the defaults above. */ +export function groqConfigFromEnv(env: Record = process.env) { + return { + apiKey: env.GROQ_API_KEY?.trim() || undefined, + model: env.GROQ_MODEL?.trim() || DEFAULT_GROQ_MODEL, + timeoutMs: readTimeout(env.GROQ_TIMEOUT_MS, DEFAULT_GROQ_TIMEOUT_MS), + } satisfies GroqConfig +} + +type ChatCompletionResponse = { + choices?: { message?: { content?: string | null } }[] +} + +export class GroqClient implements TextGenerator { + constructor( + private readonly config: GroqConfig = groqConfigFromEnv(), + private readonly fetchFn: typeof fetch = fetch, + ) {} + + /** The model's text answer. Throws `ModelError` on any failure. */ + async generate({ systemInstruction, turns }: GenerateInput): Promise { + if (!this.config.apiKey) throw new ModelError('missing-key') + + const body = (await postJson( + this.fetchFn, + GROQ_API_URL, + { authorization: `Bearer ${this.config.apiKey}` }, + { + model: this.config.model, + messages: [ + { role: 'system', content: systemInstruction }, + ...turns.map(({ role, text }) => ({ + role: role === 'model' ? 'assistant' : 'user', + content: text, + })), + ], + temperature: 0, + }, + this.config.timeoutMs, + )) as ChatCompletionResponse + + const text = body.choices?.[0]?.message?.content?.trim() + if (!text) throw new ModelError('empty-response') + + return text + } +} diff --git a/apps/api/src/lib/model.ts b/apps/api/src/lib/model.ts new file mode 100644 index 0000000..772348d --- /dev/null +++ b/apps/api/src/lib/model.ts @@ -0,0 +1,17 @@ +import { GeminiClient, geminiConfigFromEnv } from './gemini' +import { GroqClient, groqConfigFromEnv } from './groq' +import type { TextGenerator } from './text-generator' + +/** + * The model the API asks: Groq when `GROQ_API_KEY` is set (fast and steady), Gemini / + * Gemma otherwise. Without any key the Gemini client fails with `missing-key` and + * callers fall back to their own non-AI path. + */ +export function createTextGenerator( + env: Record = process.env, +): TextGenerator { + const groq = groqConfigFromEnv(env) + if (groq.apiKey) return new GroqClient(groq) + + return new GeminiClient(geminiConfigFromEnv(env)) +} diff --git a/apps/api/src/lib/text-generator.ts b/apps/api/src/lib/text-generator.ts new file mode 100644 index 0000000..fd9d46c --- /dev/null +++ b/apps/api/src/lib/text-generator.ts @@ -0,0 +1,89 @@ +/** + * What every model client shares: the prompt shape, the `TextGenerator` contract and the + * HTTP call with its deadline, retry and error reasons. The clients themselves + * (`gemini.ts`, `groq.ts`) only build the request body and read the answer. + */ + +/** Attempts per call when the API answers 5xx (those fail fast and often pass on retry). */ +const MAX_ATTEMPTS = 2 + +/** One turn of the conversation: `user` for the input, `model` for an example answer. */ +export type ModelTurn = { role: 'user' | 'model'; text: string } + +export type GenerateInput = { + systemInstruction: string + turns: ModelTurn[] +} + +/** Something that answers a prompt with text: a model client, or a fake in tests. */ +export type TextGenerator = { generate(input: GenerateInput): Promise } + +/** Why a call failed, short enough to log (it never includes the prompt). */ +export type ModelFailureReason = + | 'missing-key' + | 'timeout' + | 'rate-limited' + | `http-${number}` + | 'network' + | 'empty-response' + +export class ModelError extends Error { + constructor(readonly reason: ModelFailureReason) { + super(`Model request failed: ${reason}`) + this.name = 'ModelError' + } +} + +/** Reads a positive number of milliseconds, or `fallback` when it is missing or invalid. */ +export function readTimeout(value: string | undefined, fallback: number): number { + const timeout = Number.parseInt(value ?? '', 10) + + return Number.isFinite(timeout) && timeout > 0 ? timeout : fallback +} + +function isAbort(error: unknown): boolean { + const name = error instanceof Error ? error.name : '' + + return name === 'TimeoutError' || name === 'AbortError' +} + +/** + * POSTs `body` as JSON and returns the parsed answer. A 5xx is retried once, all attempts + * within one `timeoutMs` deadline so a retry never makes the user wait longer. Throws + * `ModelError` on any failure. + */ +export async function postJson( + fetchFn: typeof fetch, + url: string, + headers: Record, + body: unknown, + timeoutMs: number, +): Promise { + const init = { + method: 'POST', + headers: { 'content-type': 'application/json', ...headers }, + body: JSON.stringify(body), + signal: AbortSignal.timeout(timeoutMs), + } + + let response: Response | undefined + for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) { + try { + response = await fetchFn(url, init) + } catch (error) { + throw new ModelError(isAbort(error) ? 'timeout' : 'network') + } + + if (response.status < 500) break + } + + if (!response) throw new ModelError('network') + if (response.status === 429) throw new ModelError('rate-limited') + if (!response.ok) throw new ModelError(`http-${response.status}`) + + try { + return await response.json() + } catch (error) { + throw new ModelError(isAbort(error) ? 'timeout' : 'empty-response') + } +} diff --git a/apps/api/src/modules/voice/split/prompt.ts b/apps/api/src/modules/voice/split/prompt.ts index 5526810..28dc1b5 100644 --- a/apps/api/src/modules/voice/split/prompt.ts +++ b/apps/api/src/modules/voice/split/prompt.ts @@ -1,6 +1,6 @@ import { VOICE_SPLIT_EXAMPLES } from '@superlist/shared' -import type { GeminiTurn, GenerateInput } from '@/lib/gemini' +import type { GenerateInput, ModelTurn } from '@/lib/text-generator' /** What the model is told to do. Gemma accepts it as `systemInstruction`. */ export const SPLIT_INSTRUCTION = `Sos un asistente que arma listas de compras en español rioplatense. @@ -19,7 +19,7 @@ Reglas: /** The conversation sent to the model: the few-shot examples, then the transcript. */ export function buildSplitPrompt(text: string): GenerateInput { - const examples: GeminiTurn[] = VOICE_SPLIT_EXAMPLES.flatMap(({ said, items }) => [ + const examples: ModelTurn[] = VOICE_SPLIT_EXAMPLES.flatMap(({ said, items }) => [ { role: 'user' as const, text: said }, { role: 'model' as const, text: JSON.stringify(items) }, ]) diff --git a/apps/api/src/modules/voice/split/route.test.ts b/apps/api/src/modules/voice/split/route.test.ts index 56e87eb..78407b8 100644 --- a/apps/api/src/modules/voice/split/route.test.ts +++ b/apps/api/src/modules/voice/split/route.test.ts @@ -52,6 +52,10 @@ beforeEach(() => { process.env.GEMINI_API_KEY = 'test-key' process.env.GEMINI_MODEL = 'gemma-test' process.env.GEMINI_TIMEOUT_MS = '50' + // `bun test` loads `.env`: a real Groq key there would take over these Gemini tests. + delete process.env.GROQ_API_KEY + delete process.env.GROQ_MODEL + delete process.env.GROQ_TIMEOUT_MS }) afterEach(() => { @@ -175,3 +179,67 @@ describe('POST /api/voice/split', () => { expect(sent.contents.at(-1).parts[0].text).toHaveLength(500) }) }) + +describe('POST /api/voice/split with Groq', () => { + beforeEach(() => { + process.env.GROQ_API_KEY = 'gsk_test' + process.env.GROQ_MODEL = 'llama-test' + process.env.GROQ_TIMEOUT_MS = '50' + }) + + function groqAnswer(content: string) { + return Response.json({ choices: [{ message: { role: 'assistant', content } }] }) + } + + it('asks Groq instead of Gemini when its key is set', async () => { + const fetchMock = mockFetch(async () => groqAnswer('["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(warnings).toHaveLength(0) + + const [url, init] = fetchMock.mock.calls[0] ?? [] + expect(url).toBe('https://api.groq.com/openai/v1/chat/completions') + expect(new Headers(init?.headers).get('authorization')).toBe('Bearer gsk_test') + const sent = JSON.parse(String(init?.body)) + expect(sent.model).toBe('llama-test') + expect(sent.temperature).toBe(0) + expect(sent.messages[0]).toEqual({ + role: 'system', + content: expect.stringContaining('array JSON'), + }) + expect(sent.messages[2].role).toBe('assistant') + expect(sent.messages.at(-1)).toEqual({ role: 'user', content: 'azúcar leche y café' }) + }) + + it('retries a 5xx once', async () => { + let calls = 0 + const fetchMock = mockFetch(async () => + ++calls === 1 ? new Response('{}', { status: 502 }) : groqAnswer('["Pan"]'), + ) + + const response = await split({ text: 'pan' }) + + expect(await response.json()).toEqual({ items: ['Pan'] }) + expect(fetchMock).toHaveBeenCalledTimes(2) + }) + + it('falls back when Groq is rate limited (429)', async () => { + mockFetch(async () => new Response('{}', { status: 429 })) + + const response = await split({ text: 'pan y queso' }) + + expect(await response.json()).toEqual({ items: ['pan', 'queso'] }) + expect(JSON.stringify(warnings)).toContain('rate-limited') + }) + + it('falls back when Groq answers with no content', async () => { + mockFetch(async () => groqAnswer('')) + + const response = await split({ text: 'pan, queso' }) + + expect(await response.json()).toEqual({ items: ['pan', 'queso'] }) + expect(JSON.stringify(warnings)).toContain('empty-response') + }) +}) diff --git a/apps/api/src/modules/voice/split/route.ts b/apps/api/src/modules/voice/split/route.ts index b46d670..eedf434 100644 --- a/apps/api/src/modules/voice/split/route.ts +++ b/apps/api/src/modules/voice/split/route.ts @@ -1,7 +1,7 @@ import { Hono } from 'hono' import { requireSession } from '@/lib/auth-session' -import { GeminiClient } from '@/lib/gemini' +import { createTextGenerator } from '@/lib/model' import { resultJson } from '@/lib/result-json' import { validate } from '@/lib/validate' import type { AppEnv } from '@/types' @@ -16,7 +16,9 @@ export const splitVoiceRoute = new Hono().post( validate.json(SplitVoiceSchema), async (c) => { const { text } = c.req.valid('json') - const result = await new SplitVoiceText(new GeminiClient(), c.get('logger')).execute({ text }) + const result = await new SplitVoiceText(createTextGenerator(), c.get('logger')).execute({ + text, + }) return resultJson(c, result) }, diff --git a/apps/api/src/modules/voice/split/use-case.ts b/apps/api/src/modules/voice/split/use-case.ts index e5678d4..7893a88 100644 --- a/apps/api/src/modules/voice/split/use-case.ts +++ b/apps/api/src/modules/voice/split/use-case.ts @@ -6,8 +6,8 @@ import { type VoiceSplitResponse, } from '@superlist/shared' -import { GeminiError, type TextGenerator } from '@/lib/gemini' import type { Logger } from '@/lib/logger' +import { ModelError, type TextGenerator } from '@/lib/text-generator' import { cleanItems, fallbackSplit, parseModelItems } from './items' import { buildSplitPrompt } from './prompt' @@ -36,7 +36,7 @@ export class SplitVoiceText { try { answer = await this.model.generate(buildSplitPrompt(text)) } catch (error) { - return this.fallback(text, error instanceof GeminiError ? error.reason : 'unexpected-error') + return this.fallback(text, error instanceof ModelError ? error.reason : 'unexpected-error') } const items = parseModelItems(answer) diff --git a/docker-compose.yml b/docker-compose.yml index 729de77..6a0d3ec 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -24,7 +24,11 @@ services: LOG_LEVEL: ${LOG_LEVEL:-} RESEND_API_KEY: ${RESEND_API_KEY:-} MAIL_FROM: ${MAIL_FROM:-} - # Dictation (optional): without the key, dictated text is split without AI. + # Dictation (optional): Groq when its key is set, else Gemini; without any key, + # dictated text is split without AI. + GROQ_API_KEY: ${GROQ_API_KEY:-} + GROQ_MODEL: ${GROQ_MODEL:-openai/gpt-oss-120b} + GROQ_TIMEOUT_MS: ${GROQ_TIMEOUT_MS:-8000} GEMINI_API_KEY: ${GEMINI_API_KEY:-} GEMINI_MODEL: ${GEMINI_MODEL:-gemma-4-26b-a4b-it} GEMINI_TIMEOUT_MS: ${GEMINI_TIMEOUT_MS:-8000} diff --git a/turbo.json b/turbo.json index bce070d..4ad7638 100644 --- a/turbo.json +++ b/turbo.json @@ -21,7 +21,10 @@ "WEB_APP_URL", "GEMINI_API_KEY", "GEMINI_MODEL", - "GEMINI_TIMEOUT_MS" + "GEMINI_TIMEOUT_MS", + "GROQ_API_KEY", + "GROQ_MODEL", + "GROQ_TIMEOUT_MS" ] }, "dev": { @@ -40,6 +43,9 @@ "GEMINI_API_KEY", "GEMINI_MODEL", "GEMINI_TIMEOUT_MS", + "GROQ_API_KEY", + "GROQ_MODEL", + "GROQ_TIMEOUT_MS", "VITE_API_URL" ] },