Bỏ qua, tới nội dung chính

Kiến trúc · ADR 0027

`packages/ai` as the LLM core; `packages/domain` for pure domain logic

Trạng thái
accepted
Ngày
2026-09-29
Người quyết định
SmartLearn team

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 like packages/shared (tsup ESM + CJS, zod as a peer). An AiProvider does one HTTP round trip (generateText, generateObject, embed). Adapters: Gemini, OpenAI, and a deterministic FakeProvider for tests and keyless local dev (LLM_PROVIDER=fake).
  • AiClient owns everything else: a per-attempt AbortController timeout; at most AI_MAX_RETRIES retries on 429/5xx/408/network only, with exponential backoff and jitter, honouring Retry-After up to 30 s; a per-call output ceiling plus a BudgetStore that 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-in CacheStore keyed by a SHA-256 of provider, model and the normalised request (embeddings cached by default, generation only with cache: true); Zod validation of every generateObject result; a vector-size check against EMBEDDING_DIMENSIONS; and an onEvent hook with usage, latency and outcome — never a key, and no prompt or output unless logContent is 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 gets thinkingConfig.thinkingBudget from GEMINI_THINKING_BUDGET (default 0): 2.5-flash thinks by default and those tokens come out of maxOutputTokens. _Amended 2026-11-22 (#165):_ Gemini 3.x and later get thinkingConfig.thinkingLevel from GEMINI_THINKING_LEVEL (default minimal, raised to the lowest level a model supports) and never thinkingBudget, 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 is gemini-3.6-flash; gemini-3.5-flash is deprecated and billed as 3.6.
  • Env is one Zod shape (aiEnvShape) spread into the api's config/env.ts and the worker's env.ts. Keys are optional: an app boots without them and the first real call fails with AiError('config') naming the variable.
  • api: modules/ai exports AiService, built from ConfigService, events to the Nest Logger. No routes (rule 5). worker: src/runtime.ts builds Redis, a PrismaClient and an AiClient once; processors receive (data, { prisma, ai }); shutdown drains workers, then $disconnects Prisma and quits Redis.
  • packages/domain will 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. shared stays 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.