Context
AGENTS.md rule 4 promised an ai/ module owning caching, budget, retries and logging, but it only named an api module, and rule 5 puts the heavy AI work (explanations, embeddings, generated questions) in the worker, which cannot import a Nest module. The worker also had no database client. Architecture review, item 7.
Decision
packages/ai(@smartlearn/ai) is the framework-agnostic core, built likepackages/shared(tsup ESM + CJS, zod as a peer). AnAiProviderdoes one HTTP round trip (generateText,generateObject,embed). Adapters: Gemini, OpenAI, and a deterministicFakeProviderfor tests and keyless local dev (LLM_PROVIDER=fake).AiClientowns everything else: a per-attemptAbortControllertimeout; at mostAI_MAX_RETRIESretries on 429/5xx/408/network only, with exponential backoff and jitter, honouringRetry-Afterup to 30 s; a per-call output ceiling plus aBudgetStorethat atomically reserves the worst case (input estimate + output ceiling) before sending and settles to what was billed after — including 200s the adapter then rejects (cut-off JSON, block, refusal) and, as an input estimate, attempts abandoned at the timeout; an opt-inCacheStorekeyed by a SHA-256 of provider, model and the normalised request (embeddings cached by default, generation only withcache: true); Zod validation of everygenerateObjectresult; a vector-size check againstEMBEDDING_DIMENSIONS; and anonEventhook with usage, latency and outcome — never a key, and no prompt or output unlesslogContentis set.- Plain
fetch, no SDKs. Three endpoints per provider do not justify two SDKs with their own retry and timeout logic that would fight ours. Keys travel in headers only and are redacted from error text. Gemini getsthinkingConfig.thinkingBudgetfromGEMINI_THINKING_BUDGET(default 0): 2.5-flash thinks by default and those tokens come out ofmaxOutputTokens. _Amended 2026-11-22 (#165):_ Gemini 3.x and later getthinkingConfig.thinkingLevelfromGEMINI_THINKING_LEVEL(defaultminimal, raised to the lowest level a model supports) and neverthinkingBudget, which is legacy there and a 400 when sent with a level (<https://aistudio.google.com/docs/thinking.md?generate-content=true>). The default text model isgemini-3.6-flash;gemini-3.5-flashis deprecated and billed as 3.6. - Env is one Zod shape (
aiEnvShape) spread into the api'sconfig/env.tsand the worker'senv.ts. Keys are optional: an app boots without them and the first real call fails withAiError('config')naming the variable. - api:
modules/aiexportsAiService, built fromConfigService, events to the NestLogger. No routes (rule 5). worker:src/runtime.tsbuilds Redis, aPrismaClientand anAiClientonce; processors receive(data, { prisma, ai }); shutdown drains workers, then$disconnects Prisma and quits Redis. packages/domainwill hold pure domain logic that is not a schema (mastery, credits ledger, scoring): no Nest, no HTTP, no Prisma client, importable by api and worker. It is not created now; the first such code creates it.sharedstays schemas/types/constants only.
Alternatives considered
- Nest module only — the worker could not use it; the precompute pipeline would duplicate it.
- Vercel AI SDK / provider SDKs — heavier, and hides retry/timeout behaviour we must control.
Consequences
Budget and cache stores are in-memory per process today, so the limit multiplies by instance count. Redis-backed stores behind the same interfaces are the follow-up (reserve is a short Lua script, record an INCRBY); the reserve-then-settle contract already makes them atomic. _Done for the budget in ADR-0050 (#164): one Redis counter per ICT day shared by every process._ Model names (gemini-2.5-flash, gemini-embedding-001, gpt-4.1-mini, text-embedding-3-small) are env-overridable defaults and were not exercised against the live APIs.