A documentation chat assistant where every claim is cited, and clicking a citation jumps straight to the exact retrieved passage it came from. Built on from-scratch BM25 retrieval (no vector DB) and the Vercel AI SDK.
"Chat with your docs" is the single most commonly requested AI feature on Upwork, and the difference between a toy and something a client can actually ship is grounding: an answer nobody can verify against the source is a liability, not a feature. This implements retrieval-augmented generation with the citation trail intact end to end — the client UI, not just a log file, so a user can always check exactly what the assistant based its answer on.
src/
lib/
bm25.ts From-scratch BM25 ranking (real IDF/TF math, no library)
corpus.ts A demo knowledge base — a fictional SaaS product's pricing,
refund policy, onboarding, API, and security docs
scriptedModel.ts Deterministic extractive "model" for the zero-cost demo (see below)
app/
api/chat/route.ts Retrieves the top-k chunks for the question, injects them into the
system prompt as numbered context, streams the answer + sends the
retrieved chunks to the client via the AI SDK's StreamData channel
components/
ChatWindow.tsx Two-pane layout: chat on the left, retrieved passages on the right
ChatMessage.tsx Parses [n] markers in the answer into clickable citation badges
SourcePanel.tsx Highlights + scrolls to the cited passage when a badge is clicked
Same zero-cost-demo pattern as my other AI SDK projects: scriptedModel.ts implements the AI SDK's real LanguageModelV1 interface via MockLanguageModelV1 (from ai/test), so the exact same streamText → StreamData → useChat pipeline runs whether or not OPENAI_API_KEY is set. In demo mode the "answer" is extractive — the retrieved passages themselves, concatenated with citation markers — rather than LLM-paraphrased, but the retrieval, citation-linking, and UI are all real.
npm install
npm run dev # demo mode, no API key neededTry: "What's the refund policy?", "What are the API rate limits?", "How does onboarding work?" — then click any citation number.
npm test7 tests: BM25 ranking correctness (including that irrelevant documents score zero and get excluded), and the scripted model's citation-formatting and streaming behavior.