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:
@@ -27,6 +27,13 @@ WEB_APP_URL="http://localhost:7153"
|
|||||||
# GEMINI_MODEL="gemma-4-26b-a4b-it"
|
# GEMINI_MODEL="gemma-4-26b-a4b-it"
|
||||||
# Optional: timeout of the model request, in milliseconds
|
# Optional: timeout of the model request, in milliseconds
|
||||||
# GEMINI_TIMEOUT_MS="8000"
|
# 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 ---
|
# --- apps/web ---
|
||||||
# Optional. In dev, Vite proxies /api/* to the API (http://localhost:4100), so
|
# Optional. In dev, Vite proxies /api/* to the API (http://localhost:4100), so
|
||||||
|
|||||||
@@ -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.
|
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;
|
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
|
there is no Google login and no email verification; the `voice` module splits dictated text with Groq, or Gemma 4
|
||||||
through the Gemini API). The `health` module is the reference example.
|
through the Gemini API when Groq is not configured). The `health` module is the reference example.
|
||||||
|
|
||||||
## Stack (source of truth: `STACK.md`)
|
## 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
|
`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
|
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
|
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.
|
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`,
|
- Generated files are gitignored and must never be edited by hand: `apps/web/src/routeTree.gen.ts`,
|
||||||
`apps/api/src/generated/`.
|
`apps/api/src/generated/`.
|
||||||
|
|||||||
@@ -20,3 +20,10 @@ WEB_APP_URL="http://localhost:7153"
|
|||||||
# GEMINI_MODEL="gemma-4-26b-a4b-it"
|
# GEMINI_MODEL="gemma-4-26b-a4b-it"
|
||||||
# Optional: timeout of the model request, in milliseconds
|
# Optional: timeout of the model request, in milliseconds
|
||||||
# GEMINI_TIMEOUT_MS="8000"
|
# 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"
|
||||||
|
|||||||
@@ -13,10 +13,15 @@
|
|||||||
* also answers 5xx now and then, fast; those calls are retried once.
|
* 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 GEMINI_API_URL = 'https://generativelanguage.googleapis.com/v1beta/models'
|
||||||
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'
|
||||||
@@ -31,99 +36,38 @@ export type GeminiConfig = {
|
|||||||
|
|
||||||
/** Reads the configuration from the environment, with the defaults above. */
|
/** Reads the configuration from the environment, with the defaults above. */
|
||||||
export function geminiConfigFromEnv(env: Record<string, string | undefined> = process.env) {
|
export function geminiConfigFromEnv(env: Record<string, string | undefined> = process.env) {
|
||||||
const timeout = Number.parseInt(env.GEMINI_TIMEOUT_MS ?? '', 10)
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
apiKey: env.GEMINI_API_KEY?.trim() || undefined,
|
apiKey: env.GEMINI_API_KEY?.trim() || undefined,
|
||||||
model: env.GEMINI_MODEL?.trim() || DEFAULT_GEMINI_MODEL,
|
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
|
} 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 = {
|
type GenerateContentResponse = {
|
||||||
candidates?: { content?: { parts?: { text?: string; thought?: boolean }[] } }[]
|
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 {
|
export class GeminiClient implements TextGenerator {
|
||||||
constructor(
|
constructor(
|
||||||
private readonly config: GeminiConfig = geminiConfigFromEnv(),
|
private readonly config: GeminiConfig = geminiConfigFromEnv(),
|
||||||
private readonly fetchFn: typeof fetch = fetch,
|
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> {
|
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 body = (await postJson(
|
||||||
const signal = AbortSignal.timeout(this.config.timeoutMs)
|
this.fetchFn,
|
||||||
const request = {
|
`${GEMINI_API_URL}/${encodeURIComponent(this.config.model)}:generateContent`,
|
||||||
method: 'POST',
|
{ 'x-goog-api-key': this.config.apiKey },
|
||||||
headers: { 'content-type': 'application/json', 'x-goog-api-key': this.config.apiKey },
|
{
|
||||||
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, thinkingConfig: { thinkingLevel: 'minimal' } },
|
generationConfig: { temperature: 0, thinkingConfig: { thinkingLevel: 'minimal' } },
|
||||||
}),
|
},
|
||||||
signal,
|
this.config.timeoutMs,
|
||||||
}
|
)) as GenerateContentResponse
|
||||||
|
|
||||||
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',
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Thinking models may send their reasoning as `thought` parts: only the answer counts.
|
// Thinking models may send their reasoning as `thought` parts: only the answer counts.
|
||||||
const text = (body.candidates?.[0]?.content?.parts ?? [])
|
const text = (body.candidates?.[0]?.content?.parts ?? [])
|
||||||
@@ -132,7 +76,7 @@ export class GeminiClient implements TextGenerator {
|
|||||||
.join('')
|
.join('')
|
||||||
.trim()
|
.trim()
|
||||||
|
|
||||||
if (!text) throw new GeminiError('empty-response')
|
if (!text) throw new ModelError('empty-response')
|
||||||
|
|
||||||
return text
|
return text
|
||||||
}
|
}
|
||||||
|
|||||||
79
apps/api/src/lib/groq.ts
Normal file
79
apps/api/src/lib/groq.ts
Normal 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
17
apps/api/src/lib/model.ts
Normal 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))
|
||||||
|
}
|
||||||
89
apps/api/src/lib/text-generator.ts
Normal file
89
apps/api/src/lib/text-generator.ts
Normal 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')
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import { VOICE_SPLIT_EXAMPLES } from '@superlist/shared'
|
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`. */
|
/** 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.
|
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. */
|
/** The conversation sent to the model: the few-shot examples, then the transcript. */
|
||||||
export function buildSplitPrompt(text: string): GenerateInput {
|
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: 'user' as const, text: said },
|
||||||
{ role: 'model' as const, text: JSON.stringify(items) },
|
{ role: 'model' as const, text: JSON.stringify(items) },
|
||||||
])
|
])
|
||||||
|
|||||||
@@ -52,6 +52,10 @@ beforeEach(() => {
|
|||||||
process.env.GEMINI_API_KEY = 'test-key'
|
process.env.GEMINI_API_KEY = 'test-key'
|
||||||
process.env.GEMINI_MODEL = 'gemma-test'
|
process.env.GEMINI_MODEL = 'gemma-test'
|
||||||
process.env.GEMINI_TIMEOUT_MS = '50'
|
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(() => {
|
afterEach(() => {
|
||||||
@@ -175,3 +179,67 @@ describe('POST /api/voice/split', () => {
|
|||||||
expect(sent.contents.at(-1).parts[0].text).toHaveLength(500)
|
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')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { Hono } from 'hono'
|
import { Hono } from 'hono'
|
||||||
|
|
||||||
import { requireSession } from '@/lib/auth-session'
|
import { requireSession } from '@/lib/auth-session'
|
||||||
import { GeminiClient } from '@/lib/gemini'
|
import { createTextGenerator } from '@/lib/model'
|
||||||
import { resultJson } from '@/lib/result-json'
|
import { resultJson } from '@/lib/result-json'
|
||||||
import { validate } from '@/lib/validate'
|
import { validate } from '@/lib/validate'
|
||||||
import type { AppEnv } from '@/types'
|
import type { AppEnv } from '@/types'
|
||||||
@@ -16,7 +16,9 @@ export const splitVoiceRoute = new Hono<AppEnv>().post(
|
|||||||
validate.json(SplitVoiceSchema),
|
validate.json(SplitVoiceSchema),
|
||||||
async (c) => {
|
async (c) => {
|
||||||
const { text } = c.req.valid('json')
|
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)
|
return resultJson(c, result)
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -6,8 +6,8 @@ import {
|
|||||||
type VoiceSplitResponse,
|
type VoiceSplitResponse,
|
||||||
} from '@superlist/shared'
|
} from '@superlist/shared'
|
||||||
|
|
||||||
import { GeminiError, type TextGenerator } from '@/lib/gemini'
|
|
||||||
import type { Logger } from '@/lib/logger'
|
import type { Logger } from '@/lib/logger'
|
||||||
|
import { ModelError, type TextGenerator } from '@/lib/text-generator'
|
||||||
|
|
||||||
import { cleanItems, fallbackSplit, parseModelItems } from './items'
|
import { cleanItems, fallbackSplit, parseModelItems } from './items'
|
||||||
import { buildSplitPrompt } from './prompt'
|
import { buildSplitPrompt } from './prompt'
|
||||||
@@ -36,7 +36,7 @@ export class SplitVoiceText {
|
|||||||
try {
|
try {
|
||||||
answer = await this.model.generate(buildSplitPrompt(text))
|
answer = await this.model.generate(buildSplitPrompt(text))
|
||||||
} catch (error) {
|
} 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)
|
const items = parseModelItems(answer)
|
||||||
|
|||||||
@@ -24,7 +24,11 @@ services:
|
|||||||
LOG_LEVEL: ${LOG_LEVEL:-}
|
LOG_LEVEL: ${LOG_LEVEL:-}
|
||||||
RESEND_API_KEY: ${RESEND_API_KEY:-}
|
RESEND_API_KEY: ${RESEND_API_KEY:-}
|
||||||
MAIL_FROM: ${MAIL_FROM:-}
|
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_API_KEY: ${GEMINI_API_KEY:-}
|
||||||
GEMINI_MODEL: ${GEMINI_MODEL:-gemma-4-26b-a4b-it}
|
GEMINI_MODEL: ${GEMINI_MODEL:-gemma-4-26b-a4b-it}
|
||||||
GEMINI_TIMEOUT_MS: ${GEMINI_TIMEOUT_MS:-8000}
|
GEMINI_TIMEOUT_MS: ${GEMINI_TIMEOUT_MS:-8000}
|
||||||
|
|||||||
@@ -21,7 +21,10 @@
|
|||||||
"WEB_APP_URL",
|
"WEB_APP_URL",
|
||||||
"GEMINI_API_KEY",
|
"GEMINI_API_KEY",
|
||||||
"GEMINI_MODEL",
|
"GEMINI_MODEL",
|
||||||
"GEMINI_TIMEOUT_MS"
|
"GEMINI_TIMEOUT_MS",
|
||||||
|
"GROQ_API_KEY",
|
||||||
|
"GROQ_MODEL",
|
||||||
|
"GROQ_TIMEOUT_MS"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"dev": {
|
"dev": {
|
||||||
@@ -40,6 +43,9 @@
|
|||||||
"GEMINI_API_KEY",
|
"GEMINI_API_KEY",
|
||||||
"GEMINI_MODEL",
|
"GEMINI_MODEL",
|
||||||
"GEMINI_TIMEOUT_MS",
|
"GEMINI_TIMEOUT_MS",
|
||||||
|
"GROQ_API_KEY",
|
||||||
|
"GROQ_MODEL",
|
||||||
|
"GROQ_TIMEOUT_MS",
|
||||||
"VITE_API_URL"
|
"VITE_API_URL"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
|||||||
Reference in New Issue
Block a user