Context
Retrieval for the AI Tutor ranked chunks by pgvector cosine only, although DocumentChunk.contentTsv and its GIN index had existed since migration m3. Exact terms (class names, SQL keywords, course codes) were easy to miss. tools/eval-runner carried its own copy of the retrieval SQL and of the prompt, so its scores did not describe production. When nothing matched, the Tutor silently answered from general knowledge, which contradicts both the RAG guidance we follow and our own UNANSWERABLE evaluation cases.
Decision
- Hybrid retrieval. One SQL round trip returns candidates from a vector channel and a full-text channel (
simpleconfig;to_tsquerybuilt from content words with stop words removed, plus(a <-> b)phrases for adjacent words). The two rankings are fused with Reciprocal Rank Fusion (k = 60), then capped at two chunks per source. A keyword-only candidate needs cosine ≥minScore − 0.10, so a stray word cannot pull in an off-topic chunk. The returnedscorekeeps its meaning (boosted cosine). - One implementation.
searchCourseKnowledgelives in@smartlearn/database(src/knowledge-search.ts), next to the Prisma client it needs; the API'sDocumentsSearchServiceand the evaluation runner both call it, with sharedTUTOR_RETRIEVAL_LIMIT/TUTOR_MIN_SCORE.packages/aistays Prisma-free (ADR-0027). - Retrieval metrics. The runner records Hit@k, MRR and Context Precision per case and their means in
summary.jsonand the report. - Abstain by default. In
COURSE_ONLYmode with no evidence, the Tutor returns a fixed "not in the course material" answer (NOT_IN_MATERIAL, no LLM call, no citations). The grounded prompt no longer fills gaps from general knowledge. The learner opts in with a "Giải thích bằng kiến thức mở rộng" button that re-asks inGENERAL_KNOWLEDGEmode.
Alternatives considered
- External reranker (Cohere/Voyage) or LLM reranking — extra cost and latency per question; revisit if the new metrics show ranking, not recall, is the gap.
- A
tsvectorcolumn + GIN index onLessonChunknow — needs a migration while CI (and with it automatic migrations) is off; lesson chunks are per-course and small, so the vector is computed in the query. Add the column when a course outgrows that. - Keep the general-knowledge fallback — friendlier, but unsourced answers are exactly what the mentors questioned, and they cannot be told apart from grounded ones at a glance.
Consequences
- Better recall on exact terms; one more
to_tsvectorper lesson chunk per query (cheap at current size). - Evaluation runs now exercise production retrieval, including the
minScorefloor the old copy skipped, so pass rates may move; compare runs made after this change only. - More questions end in "not in the material"; the button keeps the general path one click away.
minScoreis still uncalibrated: tune it with the new metrics. - Vietnamese has no stemming in
simple; phrases partly compensate.