feat(voice): split dictations with Groq when it is configured

Gemma through the Gemini API answered 500 or timed out on most calls, so
dictated lists fell back to splitting on commas and "y" ("Azúcar leche y
café" became two items). With GROQ_API_KEY set the API now asks Groq
(openai/gpt-oss-120b by default), which answers in about a second; Gemini
stays as the provider when only its key is set.

The HTTP call, its deadline and the single retry on 5xx move to
lib/text-generator.ts and are shared by both clients.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jose Selesan
2026-10-29 11:04:13 -03:00
parent cc0611b6a0
commit 6830c827d7
13 changed files with 311 additions and 87 deletions

View File

@@ -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<string, string | undefined> = 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<string> }
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<string> {
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
}

79
apps/api/src/lib/groq.ts Normal file
View File

@@ -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<string, string | undefined> = 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<string> {
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
}
}

17
apps/api/src/lib/model.ts Normal file
View File

@@ -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<string, string | undefined> = process.env,
): TextGenerator {
const groq = groqConfigFromEnv(env)
if (groq.apiKey) return new GroqClient(groq)
return new GeminiClient(geminiConfigFromEnv(env))
}

View File

@@ -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<string> }
/** 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<string, string>,
body: unknown,
timeoutMs: number,
): Promise<unknown> {
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')
}
}