Upload PDF / DOCX / TXT files, ask questions, get answers grounded only in your documents with filename, page and verbatim excerpt citations. When the evidence isn't there, the answer is exactly Not in my documents.
Features
- Workspace UI — dark theme by default plus a light theme (Settings or the top-bar toggle), collapsible sidebar (workspace, recent documents, saved chats, settings), Chat / Study / Compare modes, skeleton loaders, keyboard focus states and reduced-motion support. Responsive: the document viewer sits beside the chat at ≥1100px; on tablets/phones it opens in a separate Document tab, and the sidebar becomes a slide-over menu.
- Interactive PDF viewer (pdf.js) — citations open the original PDF at the cited page with page navigation, zoom/fit-width and full-document search. The cited quote is highlighted using the page's real text coordinates only when it is found on that page; otherwise the viewer says so and shows the quote below. DOCX/TXT have no real pages, so their citations show the stored passage with the quote highlighted. Sources are resolved by stable
documentId, never by filename. - Study mode — structured summary (overview, key takeaways, definitions), multiple-choice quiz (selectable answers, explanations, final score), flashcards (reveal / previous / next, arrow keys) and important Q&A. Everything is generated from already-indexed chunks (no re-embedding); every item must cite a real chunk with a verbatim quote and pass the same support checks as chat answers, otherwise it is dropped. If too little is supported, the UI says so instead of inventing content.
- Compare documents — select 2–5 documents (or Syllabus vs notes: pick the syllabus) for a table of similarities, differences, contradictions and missing topics. Each cell must cite its own document; unverifiable cells show "Not supported by the source". Row types are derived from verified cells: a contradiction needs both conflicting statements cited, and "missing" is only reported after checking the other documents' full indexed text for the topic's terms (otherwise it is labelled "Only in one — absence not confirmed").
- Exam simulator — choose question count (5–30), difficulty, timer and optional negative marking; grounded MCQs with topic labels; question navigator, flag-for-review, clear answer, submit (auto-submits when time runs out); score, per-topic breakdown, explanations, citations and an incorrect-answer review; exportable results.
- Smart notes — chapter-wise key points, definitions, formulas and important derivations, each with citations. Formulas must appear verbatim in a cited passage; definitions must name a term found in the source. Export the full notes or a condensed revision sheet.
- Mind map — a central topic with connected concepts (up to two levels) and optional cross-links, built from indexed chunks. Select a concept (click or keyboard) to see its explanation, sources and related concepts.
- Answer verification — every chat answer has a Verify panel: how many proposed citations matched a retrieved passage word-for-word (rejected ones are counted and never shown), and each sentence of the answer marked Supported / Partly supported / Unsupported with the matching passage. No confidence scores are produced.
- Revision planner — add flashcards to a spaced-repetition deck (simplified SM-2: Again / Hard / Good / Easy). Shows today's due and overdue cards, new cards, reviews done today, mastered cards and the next 7 days; review sessions are recorded.
- AI tutor — Practice: problems with up to three progressive hints, a worked solution and answer, and sources; your typed answer is compared with the reference answer's key terms (a wording overlap, not a grade), then you self-assess (saved to mastery stats). Explain: a step-by-step explanation revealed one step at a time plus a check question. An optional topic targets retrieval via semantic search over existing vectors (one cached query embedding). Values a worked solution computes that aren't in the source are flagged.
- Audio overview — a two-speaker (host/guest) script: factual lines must cite a verified passage; short transitional lines may not state facts or numbers. Played with the browser's speech synthesis: play/pause/resume, previous/next line, click any line to play from it, speed 0.75×–2×, two voices when available, current line highlighted; script export.
- Search — Semantic (one cached query embedding + Qdrant vector search, similarity shown) and Exact phrase (case/punctuation-tolerant match over stored chunk text, no Gemini call, overlap duplicates removed). Results are grouped by document and open the source at its page with the passage highlighted.
- Workspaces — named project workspaces stored on the server with document associations; the active workspace filters the sidebar documents, selection, dashboard and saved chats; uploads made inside a workspace join it; chats started in a workspace are listed under it. Deleting a workspace never deletes documents; deleting a document removes it from workspaces.
- Learning dashboard — documents, completed sessions, quiz/exam scores, weak topics (≥2 attempted questions and <60% correct) and revision progress, all derived from saved records, with empty states when nothing has been recorded. Topic mastery table per topic (accuracy, last 3 attempts, trend, question counts by source, last practised) using a fixed, displayed rule (mastered ≥80% over ≥5 questions; developing ≥50%; under 3 questions = not enough data), and revision retention by document from real review grades.
- Chat extras — suggested questions (grounded in the selected documents, cached per selection), copy / regenerate (bypasses the answer cache) / export per answer, clear chat, and saved chats (stored in this browser's localStorage).
- Export — summaries, quizzes (with answer key), flashcards, Q&A, comparisons, single answers and whole chats as Markdown, plain text, or PDF via the browser's print dialog ("Save as PDF"; no PDF library needed).
- Multi-document chat — tick several documents and ask one question (typed or spoken); retrieval is filtered to exactly the selected ids, and each selected document with a relevant hit gets at least one excerpt, capped at
MAX_CONTEXT_CHUNKS. - Summary & key points — the Summary button on a document builds an overview, key points and terms from its already-indexed chunks (no re-embedding), in bounded batches for large files. Every point is validated against the chunks it cites; unsupported points are dropped, and page references appear only for PDFs and only from stored chunk metadata. Copy button included.
- Voice — microphone input (English/Hindi) and read-aloud, unchanged.
- Gemini quota handling — see Resilience & API usage.
Stack: React + Vite (JS) · Node.js + Express 5 · Google Gemini (gemini-embedding-001 embeddings, 768 dims + gemini-3.5-flash chat) · Qdrant · Multer · unpdf · Mammoth · Zod · Jest + Supertest.
┌──────────────── INGESTION ────────────────┐
Browser ── upload ──▶ Multer (size/type limit) → magic-byte check → extract text per page
(React) (unpdf / Mammoth / UTF-8) → chunk with overlap (never across pages)
→ embed in batches (Gemini) → upsert to Qdrant
payload {userId, documentId, filename, page, chunkIndex, text}
→ registry status: indexing → ready | failed (vectors rolled back)
┌──────────────── QUESTION ANSWERING ───────┐
Browser ── question ─▶ Zod validation → restrict to the user's own *ready* selected docs
→ embed question → Qdrant search filtered by userId + documentIds,
score ≥ SIMILARITY_THRESHOLD (no hits → fallback, LLM not called)
→ LLM (temp 0, strict system prompt, JSON schema output: status,
answer, citations[{chunk_id, quote}])
→ grounding validator (see below) (fails → fallback)
→ { answer, sources[{filename, page, excerpt, chunkId, score}] }
Hallucination safeguards (reasonable, not perfect):
- Similarity threshold before calling the LLM.
- System prompt: answer only from excerpts; excerpts are untrusted data; ignore instructions inside them; return
not_foundwhen unsure. - Structured JSON output; every claim needs a citation with a verbatim quote.
- Server-side validation — the model's output is never trusted directly:
- cited
chunk_idmust be one of the chunks actually retrieved for this question; - the quote must appear verbatim (case/whitespace-normalised) in that chunk;
- every number in the answer must appear in the cited chunks;
- ≥
MIN_SUPPORT_RATIOof the answer's key terms must appear in the cited chunks. Any failure → exactlyNot in my documents.Citations (filename, page) come from stored metadata, never from the model.
- cited
doc-rag-chatbot/
├── docker-compose.yml # local Qdrant
├── server/
│ ├── .env.example
│ ├── src/
│ │ ├── index.js # wiring + startup
│ │ ├── app.js # Express app from injected deps
│ │ ├── config.js # dotenv + Zod-validated config
│ │ ├── routes/index.js
│ │ ├── controllers/ # documentsController, chatController (+health)
│ │ ├── middleware/ # user id, upload limits, errors, 404
│ │ ├── validation/schemas.js
│ │ ├── lib/errors.js # AppError + JSON envelope
│ │ ├── lib/gemini.js # Gemini error classification, bounded retry, concurrency gate
│ │ ├── lib/cache.js # bounded LRU cache + in-flight dedupe
│ │ └── services/
│ │ ├── extractor.js # type detection + PDF/DOCX/TXT extraction
│ │ ├── chunker.js # page-aware overlapping chunker
│ │ ├── embeddings.js # Gemini batched embeddings (gemini-embedding-001, 768 dims)
│ │ ├── llm.js # system prompt, JSON schema, Gemini chat call
│ │ ├── grounding.js # post-generation validation
│ │ ├── qdrantStore.js # Qdrant vector store
│ │ ├── memoryStore.js # same interface, for unit tests
│ │ ├── documentRegistry.js # per-user document metadata (JSON file)
│ │ ├── ingestion.js # pipeline A (+ duplicate-upload reuse)
│ │ ├── qa.js # pipeline B (+ multi-doc context, answer cache)
│ │ ├── summary.js # batched, grounded document summaries
│ │ ├── study.js # quiz / flashcards / Q&A / suggestions / comparison (validated)
│ │ └── fileStore.js # original files for PDF page view
│ └── tests/
│ ├── helpers.js # offline fake embedder/LLM, PDF/DOCX fixtures
│ ├── unit/ # chunker, extractor, grounding, gemini errors/retry, embedder/LLM (mocked SDK)
│ ├── api/ # Supertest end-to-end against in-memory store (+ features, study, learning tests)
│ └── integration/ # real Qdrant (auto-skips if not running)
└── client/
├── vite.config.js # /api proxy → :4000
└── src/
├── api.js # fetch/XHR helpers, validation, user id
├── App.jsx
├── lib/ # hooks, saved chats, export, pdf text matching, store (localStorage),
│ # srs.js (spaced repetition), learning.js (exam scoring, stats, mind-map layout)
├── components/ # Sidebar, ChatPanel, ComparePanel, SettingsDialog, DocumentList, UploadZone, Drawer
│ ├── study/ # StudyPanel, Quiz, Flashcards
│ ├── viewer/ # SourcePane, PdfView (pdf.js)
│ └── ui/ # icons, citation chips, export menu, skeletons, error state
└── styles.css
Prerequisites: Node.js 20+, Docker, a Google Gemini API key (from Google AI Studio).
# 1. Qdrant
docker compose up -d # dashboard: http://localhost:6333/dashboard
# 2. Backend
cd server
cp .env.example .env # then set GEMINI_API_KEY=<your key> in .env
npm install
npm test # unit + API + Qdrant integration tests
npm run dev # http://localhost:4000
# 3. Frontend (new terminal)
cd client
npm install
npm test # unit tests for spaced repetition, exam scoring, stats, layout
npm run dev # http://localhost:5173
npm run build # production build → client/distTests need no Gemini key (paid calls are replaced by deterministic offline fakes). The integration test needs Qdrant running and skips itself otherwise.
| Setting | Value | Where |
|---|---|---|
| API key | GEMINI_API_KEY (in server/.env) |
server/src/config.js |
| Chat model | gemini-3.5-flash |
hard-coded in server/src/services/llm.js |
| Embedding model | gemini-embedding-001 |
hard-coded in server/src/services/embeddings.js |
| Embedding dimensions | 768 |
hard-coded in embeddings.js; Qdrant collection size comes from EMBEDDING_DIMENSIONS (default 768) |
The Qdrant collection must be created with 768-dimension vectors. If you previously indexed documents with OpenAI embeddings (1536 dims), drop the old doc_chunks collection and re-upload your documents.
All responses: { "ok": true, "data": … } or { "ok": false, "error": { "code", "message", "details?" } }.
Every route except /api/health requires header X-User-Id (8–64 chars [A-Za-z0-9_-]).
| Method | Path | Body | Success |
|---|---|---|---|
| GET | /api/health |
– | 200 {status:"ok", qdrant:"up"} · 503 if Qdrant down |
| POST | /api/documents/upload |
multipart field file |
201 {document} · 200 {document: {…, duplicate: true}} if the identical file is already indexed (no re-embedding) |
| GET | /api/documents |
– | 200 {documents:[…]} |
| GET | /api/documents/:documentId/file |
– | 200 original file (owner only) · 404 FILE_NOT_STORED for documents indexed before files were stored |
| POST | /api/documents/:documentId/summary |
– | 200 {overview, keyPoints[{text,pages,chunkIds}], terms[…], empty, coverage, cached} · 404 · 409 NOT_INDEXED |
| DELETE | /api/documents/:documentId |
– | 200 {deleted} · 404 if not yours |
| POST | /api/study |
{documentIds (1–5), mode: quiz|exam|flashcards|qa|suggestions, count? (≤30), difficulty?: easy|medium|hard, fresh?} |
200 {mode, items[…with citations], insufficient, message, droppedCount, documents, cached} |
| POST | /api/compare |
{documentIds (2–5), focus?: general|syllabus, syllabusId?, fresh?} |
200 {documents[{id,filename,label}], rows[{topic, kind, cells[{documentId, status: supported|unsupported|not_mentioned, statement, citations}]}], droppedRows} |
| POST | /api/tutor |
{documentIds (1–5), action?: practice|explain, topic?, count? (1–5), fresh?} |
200 {action, items[…], check?, insufficient} |
| POST | /api/audio-overview |
{documentIds (1–5), topic?, fresh?} |
200 {title, lines[{speaker, text, kind: fact|transition, citations}], insufficient} |
| POST | /api/search |
{query, mode?: semantic|exact, documentIds?, limit?} |
200 {results[{documentId, filename, page, chunkId, excerpt, context, similarity? / before, match, after}], total} |
| GET/POST | /api/workspaces |
{name, documentIds?} |
list · 201 {workspace} |
| PATCH/DELETE | /api/workspaces/:id |
{name?, documentIds?} |
200 {workspace} · 200 {deleted} |
| POST | /api/mindmap |
{documentIds (1–5), fresh?} |
200 {root, nodes[{id,label,parent,depth,summary,citations}], links[], insufficient} |
| POST | /api/notes |
{documentIds (1–5), fresh?} |
200 {sections[{title, points, definitions, formulas, derivations}], droppedCount, insufficient} |
| GET/POST | /api/library |
query q, kind, documentId, page, limit · body {kind: answer|citation|note|bookmark|highlight, title?, note?, documentId?, page?, chunkId?, quote?, color?, tags?, sources?} |
list · 201 {item} (quotes checked against the stored chunk → verified) · 409 LIBRARY_FULL |
| PATCH/DELETE | /api/library/:itemId |
{title?, note?, tags?, color?} |
200 {item} · 200 {deleted} |
| POST | /api/games |
{documentIds, game: blanks|truefalse|matching, count?, fresh?} |
200 {game, items[…with citations], insufficient} (blanks need no AI call) |
| POST | /api/formulas |
{documentIds} |
200 {formulas[{expression, documentId, page, chunkId}]} (deterministic, no AI) |
| POST | /api/formulas/explain |
{documentId, chunkId, expression, fresh?} |
200 {meaning, variables[{symbol, meaning, citations}], undefinedSymbols, citations} |
| POST | /api/evaluate |
{documentIds, question, answer} |
200 {score{earned, possible, rule}, points[{point, coverage, evidence, citations}], incorrect[…]} |
| POST | /api/translate |
{texts[1–30], target: hi|en} |
200 {texts[], warnings[]} |
| POST | /api/chat |
{question, documentIds?, fresh?} |
200 {answer, grounded, reason, sources[], cached} (omitted documentIds = all ready docs; [] = none → no_documents_selected, no Gemini call) |
Errors: 400 validation · 404 not found · 409 NOT_INDEXED · 413 file too large · 415 unsupported/mismatched file · 422 no extractable text · 429 app rate limit, GEMINI_RATE_LIMITED or GEMINI_QUOTA_EXHAUSTED (with Retry-After / details.retryAfterSeconds when known) · 503 GEMINI_UNAVAILABLE · 502 GEMINI_AUTH_FAILED / GEMINI_BAD_REQUEST / UPSTREAM_ERROR. Gemini error messages are never forwarded to the client.
U="X-User-Id: demo_user_01"
curl -H "$U" -F "[email protected]" http://localhost:4000/api/documents/upload
curl -H "$U" http://localhost:4000/api/documents
curl -H "$U" -H "Content-Type: application/json" \
-d '{"question":"What is the refund window?","documentIds":["<id>"]}' \
http://localhost:4000/api/chat
curl -H "$U" -X DELETE http://localhost:4000/api/documents/<id>Example chat response:
{ "ok": true, "data": {
"answer": "Customers may request a full refund within 30 days of booking.",
"grounded": true, "reason": "ok", "retrievedCount": 3,
"sources": [{ "chunkId": "6f2f…", "documentId": "2196…", "filename": "policy.pdf",
"page": 4, "excerpt": "Customers may request a full refund within 30 days of booking.", "score": 0.61,
"chunkIndex": 12, "type": "pdf", "hasFile": true, "context": "<full stored chunk text>" }] } }When unsupported: "answer": "Not in my documents.", "sources": [], and reason says why (below_similarity_threshold, model_reported_not_found, no_valid_citations, unsupported_numbers, low_support_ratio, no_documents_selected).
- Error classification (
server/src/lib/gemini.js):429daily quota →GEMINI_QUOTA_EXHAUSTED(no retry);429per-minute rate limit →GEMINI_RATE_LIMITED(serverretryDelaykept);503/504/network →GEMINI_UNAVAILABLE;500 INTERNAL→ transient server error (not quota); invalid key /401/403→GEMINI_AUTH_FAILED; other4xx→GEMINI_BAD_REQUEST. - One retry layer only: the server retries transient errors at most
GEMINI_MAX_RETRIEStimes with exponential backoff + jitter (non-blockingsetTimeout), honouring the server'sretryDelayup toGEMINI_MAX_RETRY_WAIT_MS; longer waits are returned to the user. The SDK's own retries are not enabled and the frontend never auto-resends — it shows a Retry button (with a countdown when a wait is known). Auth and bad-request errors are never retried. After a quota error, further calls short-circuit briefly instead of hitting Gemini again. - Fewer calls: embeddings are sent in batches (
EMBEDDING_BATCH_SIZE, one request per batch instead of one per chunk) and cached in a bounded LRU keyed by model + dimensions + text; re-uploading an identical file reuses its index (same user, verified vector count); identical concurrent requests share one in-flight call; at mostGEMINI_MAX_CONCURRENCYGemini calls run at once. - Answer cache (bounded, TTL
ANSWER_CACHE_TTL_SECONDS): keyed by user, question, the exact selected document ids and their content hashes/chunk counts, retrieval/grounding settings and model ids, so answers never leak across selections, users or changed documents. Errors are never cached. Summaries are cached per document content hash + model + summary settings. - All caches are in memory and reset on server restart.
Multi-user namespacing, single-tenant trust. The browser generates a random id (stored in localStorage) and sends it as X-User-Id. Every Qdrant search, count and delete is filtered by userId and documentId, and the registry only returns a user's own documents, so one id can never see another id's data (covered by tests).
This is not authentication: anyone who knows another user's id could impersonate them. Before exposing this publicly, put real auth (session/JWT/OAuth) in front and derive req.userId from the verified identity in middleware/index.js — nothing else needs to change.
Cosine scores depend on the embedding model and your documents; 0.3 is a starting point for gemini-embedding-001, not a universal truth. To calibrate: upload representative docs, ask ~20 answerable and ~20 unanswerable questions, and look at the top score in sources (temporarily set SIMILARITY_THRESHOLD=0 to see all). Pick a value between the two groups. The grounding validator still runs above the threshold, so a slightly low threshold costs an LLM call, not correctness.
- OCR for scanned PDFs uses the system
tesseractandpdftoppm(Poppler) binaries — no npm package. Install them withbrew install tesseract poppler(macOS) orapt install tesseract-ocr poppler-utils. Without them, image-only pages are rejected with a 422 that says so. Pages with under 20 characters of text are OCR'd, page numbers are kept and recorded inocrPages; OCR text can contain recognition errors, so citations from OCR'd pages are only as accurate as the scan. Settings:OCR_ENABLED(auto/false),OCR_LANGS(e.g.eng+hin, requires that language pack),OCR_MAX_PAGES(50). - Study rooms / collaboration are not implemented: the app has no authentication (
X-User-Idis namespacing only), so shared rooms with access control can't be made safe without adding real auth first. - Annotations attach to cited passages (highlight a quote you opened from a citation), whole pages (bookmark) or pages (note); free-hand text selection on the PDF is not supported. Library items live in
server/data/library.json(max 2000 per user); quotes not found in the stored chunk are saved but labelled unverified. - Offline: a service worker caches the app shell, your document/library/workspace lists and PDFs you explicitly mark available offline. Reading, saved chats, notes and highlights work offline; every AI feature needs a connection and says so.
- Translation (Hindi ↔ English) is machine translation by Gemini, labelled as such; citations and quotes stay in the original language, and numbers missing from the translation are flagged.
- Formula detection is rule-based (
=,≈,≤…) and can miss formulas written in words or images; explanations only use the formula's passage and its neighbours, and symbols not defined there are listed as undefined. - Answer evaluation is feedback against your documents, not a grade: a point counts as covered only if quoted evidence appears word-for-word in your answer.
- DOCX and TXT have no real pages: their citations open a text excerpt instead of a page view (TXT form-feeds are treated as page breaks).
- PDF page view needs the original file, which is now stored under
server/data/files/at upload. Documents indexed before this version have no stored file: their citations show the text panel with a note — upload the same file again to enable page view (the existing index is reused, nothing is re-embedded). - PDF highlighting is located from pdf.js text items; character offsets inside an item are measured with the item's font in a canvas. If the browser substitutes a different font than the PDF embeds, edges can still be slightly off. Rotated text is never highlighted. If a quote isn't found on its page (e.g. unusual text encoding), nothing is highlighted and the viewer says so.
- The viewer uses the
pdfjs-distlegacy build (includes polyfills) so it works in current stable browsers; pdf.js 6 needs a modern browser (recent Chrome, Edge, Firefox or Safari). - Quiz distractors (wrong options) are intentionally not in the source; the question, correct answer and explanation are checked against the cited text.
- Suggested questions and study content each cost one Gemini call per request (cached per document version on the server and per selection in the page).
- Saved chats, settings, study activity (exam/quiz scores, sessions) and the revision deck live in the browser's localStorage (the app's existing per-browser storage), so they don't sync across browsers or devices and are lost if site data is cleared. An in-progress exam is not saved if the page is refreshed.
- Answer verification and "missing topic" checks are lexical (key terms + numbers), so a correct paraphrase can show as "partly supported", and a topic described with entirely different wording could be reported as missing.
- Audio overview uses the browser's speech synthesis: available voices depend on the OS/browser, pause restarts the current line, and there is no downloadable audio file (the script can be exported).
- Tutor self-assessments are user-reported and labelled as such in mastery stats; the answer check is a key-term overlap, not grading.
- Saved chats remain in browser storage (tagged with their workspace); workspaces themselves are on the server.
- Weak topics depend on the model's topic labels for each question; slightly different labels for the same concept are counted separately (they are merged case-insensitively).
- The Inter font loads from Google Fonts; offline it falls back to the system font.
- Very large documents are summarized from evenly spaced passages once they exceed
SUMMARY_BATCH_CHARS × SUMMARY_MAX_BATCHES; the panel says so. - Indexing is synchronous inside the upload request; very large files take a while (progress bar shows upload %, then "Indexing…"). A job queue would be the next step.
- Document metadata lives in
server/data/documents.json(fine for one server; use a DB for multiple instances). - The grounding validator is lexical; it catches fabricated quotes, wrong numbers and off-topic answers, but cannot fully prove that a paraphrase is logically entailed. No RAG system eliminates hallucination entirely.
X-User-Idis not authentication (see above).
Ye project ek Document AI Chatbot hai jo RAG (Retrieval-Augmented Generation) use karta hai. User PDF, DOCX ya TXT upload karta hai. Backend us file ka text nikalta hai, page number yaad rakhta hai, aur text ko chhote overlapping chunks mein todta hai. Har chunk ka Gemini se embedding (numbers ki list jo meaning represent karti hai) banta hai aur Qdrant vector database mein save hota hai.
Jab user question poochta hai, us question ka bhi embedding banta hai aur Qdrant se sabse milte-julte chunks nikaale jaate hain — sirf usi user ke selected documents se. Agar koi chunk kaafi similar nahi hai, to seedha "Not in my documents." bol dete hain. Warna wo chunks LLM ko diye jaate hain, strict rule ke saath ki sirf inhi excerpts se answer do aur har baat ka exact quote do.
LLM ka answer aane ke baad server khud check karta hai: quote sach mein us chunk mein hai ya nahi, numbers document mein hain ya nahi, aur answer ke words source se match karte hain ya nahi. Check fail hua to answer reject karke "Not in my documents." dikhate hain. Is tarah chatbot bahar ki knowledge se baatein nahi banata, aur har answer ke saath file ka naam, page number aur excerpt dikhata hai.