An AI-powered enterprise search system that understands natural language queries and delivers accurate, context-aware answers from internal company documents using Retrieval-Augmented Generation (RAG).
FindX is an enterprise agentic RAG prototype with a FastAPI backend and a React frontend. It combines JWT authentication, MongoDB-based user storage, ChromaDB vector search, sentence-transformer embeddings, and Groq-powered answer generation.
Supplementary root guides:
PROJECT_PRESENTATION_GUIDE.mdfor presentation framingFULL_SYSTEM_TEST_GUIDE.mdfor end-to-end validation
The current system focuses on:
- secure login with roles
- role-based access control at the API layer
- role-based search inside retrieval
- grounded answers with evidence snippets
- streamed chat responses from the backend
- synchronous document ingestion with batched indexing and terminal progress logs
- a minimal ChatGPT-style dark frontend
FindX lets authenticated users search only the documents they are allowed to access.
There are three roles:
AdminHRDeveloper
The main behavior is:
- A user logs in and receives a JWT token.
- The backend reads the role from the token.
- The role is mapped to allowed document categories.
- ChromaDB retrieval is filtered so unauthorized chunks are never sent to the LLM.
- Groq generates an answer only from authorized retrieved context.
- The frontend shows the answer plus evidence snippets in a right-hand sidebar.
- FastAPI
- MongoDB
- ChromaDB
- sentence-transformers
- LangChain Groq integration
- PyMuPDF
- PyJWT
- python-docx
- openpyxl
- React
- Vite
- Tailwind CSS v4
- Embedding model:
sentence-transformers/all-mpnet-base-v2 - LLM provider: Groq
- Default LLM:
llama-3.3-70b-versatile
- JWT authentication
- seeded demo users
- RBAC for upload and query endpoints
- RBS through category-based Chroma filters
- follow-up query rewriting for underspecified chat turns
- multi-attempt retrieval planning and evidence merging
- verifier-backed final answers with one safe refinement round
- grounded answer generation
- source snippets returned to the UI
- query logging in MongoDB
- shorthand document resolution such as
ITC pdf - exact-page retrieval when a query targets a specific page in a resolved document
- legacy per-workspace compatibility search
- simple ChatGPT-inspired dark UI
- evidence viewer sidebar
- collapsible history and ingest sidebar
- optional browser microphone input
Current level:
- retrieval-focused enterprise agentic RAG with verifier-backed grounding
Old or earlier baseline in this repo:
- secure single-pass RAG over role-filtered chunks
- answer generation immediately after retrieval
- weaker handling of follow-up ambiguity
- no exact-page-first route for page-targeted questions
- no explicit draft-answer verification loop before final output
New or current behavior:
- rewrites short follow-up questions into clearer retrieval queries
- plans multiple retrieval attempts and merges ranked evidence
- resolves shorthand document mentions to accessible enterprise documents
- routes page-specific questions to exact-page retrieval when the document can be resolved
- generates a draft answer, verifies grounding, and can refine retrieval once before finalizing
- returns insufficiency when evidence cannot be verified safely instead of speculating
- streams the verified final answer rather than an unverified draft
- keeps legacy workspace retrieval only as a compatibility fallback
React UI
-> login / upload / streamed chat requests
FastAPI
-> auth validation
-> RBAC enforcement
-> synchronous batched document ingestion with terminal progress logging
-> agentic retrieval planning and evidence selection
MongoDB
-> users
-> document records
-> query logs
ChromaDB
-> vector chunks with metadata
Groq LLM
-> query rewriting, routing, grounding verification, answer generation, and response streaming
- Frontend sends
query,chat_id, andchat_history. - FastAPI validates the JWT.
- Backend resolves the user scope.
- Backend maps role to allowed categories.
- The backend agent decides whether the request is conversational or document-grounded.
- If the request names a document and a page number, the backend first tries to resolve the document and fetch the exact indexed chunks for that page.
- Otherwise, for document-grounded questions, it can rewrite short follow-ups into standalone retrieval queries.
- ChromaDB is queried with category and visibility filters, and multiple retrieval attempts are merged and ranked.
- If enterprise chunks are unavailable, the backend may use the legacy workspace store as a compatibility fallback.
- The LLM first generates a draft answer from the selected authorized context.
- A verifier pass checks grounding, can request one focused retrieval refinement, and rejects unsupported drafts.
- Backend returns a verified normal JSON response on
/api/chat, or NDJSON token/final events on/api/chat/stream.
Standard response shape:
{
"answer": "string",
"explanation": "string",
"sources": [
{
"document": "string",
"snippet": "string",
"page": 1,
"confidence": "50%"
}
]
}- Frontend sends a multipart upload with the file and visibility metadata.
- FastAPI validates the JWT and enforces
Adminaccess. - The backend stores the raw source file in
Backend/downloads/. - If the file is a PowerPoint, it is converted to PDF first.
- The backend extracts text page-by-page.
- The extracted text is chunked page-by-page.
- Chunks are embedded and written to ChromaDB in batches instead of one large write.
- The backend prints upload and ingestion progress in the terminal for
Upload,EXTRACT,CHUNK,INDEX, andDONE. - The API returns only after indexing completes, so the current upload path is still synchronous even though indexing is now tracked and batched.
FindX/
|- Backend/
| |- main.py
| |- server.py
| |- auth.py
| |- db.py
| |- rag.py
| |- pdf_chroma_ingest.py
| |- pdf_ppt_extract.py
| |- process_ppt.py
| |- orchestrate.py
| |- orchestarte.py
| |- downloads/
| |- jsons/
| `- chroma_db_storage/
|- Frontend/
| |- src/
| | |- App.jsx
| | |- index.css
| | |- main.jsx
| | |- lib/api.js
| | |- config/api.js
| | |- data/mockData.js
| | `- components/
| `- package.json
|- requirements.txt
|- FULL_SYSTEM_TEST_GUIDE.md
`- README.md
Primary FastAPI entrypoint.
Responsibilities:
- bootstraps the database
- creates the RAG service
- exposes auth, upload, query, and health endpoints
- enforces role checks
- resolves query scope for authenticated users
- streams chat responses over NDJSON
- logs upload lifecycle events in the terminal
Main routes:
POST /loginPOST /api/auth/loginGET /meGET /api/auth/mePOST /uploadPOST /api/upload/filePOST /queryPOST /api/chatPOST /api/chat/streamGET /health
Compatibility entrypoint:
from main import appUse this if you want to keep older run commands such as:
uvicorn server:app --reloadAuthentication and authorization layer.
Responsibilities:
- password hashing with PBKDF2
- password verification
- JWT token creation
- JWT decoding
- current-user dependency
- reusable role guard with
require_roles(...)
Defined roles:
AdminHRDeveloper
MongoDB integration layer.
Collections:
usersdocumentsquery_logs
Responsibilities:
- create indexes
- migrate legacy user records
- seed demo users
- store uploaded document records
- log all search queries
Main enterprise agentic RAG service.
Responsibilities:
- validate document categories
- validate upload visibility scopes
- map roles to allowed categories
- map roles to allowed visibility scopes
- route conversational requests away from retrieval when appropriate
- rewrite underspecified follow-up questions into standalone search queries
- extract, chunk, and embed uploaded PDFs, PowerPoints, Word files, spreadsheets, and text-like files
- process long uploads in tracked stages with batched Chroma writes
- print terminal progress for extract, chunk, and index stages
- store enterprise chunks in ChromaDB
- query enterprise chunks using category filters
- query enterprise chunks using visibility filters
- resolve shorthand document mentions such as
ITC pdfto a concrete accessible document when possible - short-circuit to exact-page retrieval when a query targets a specific page in a resolved document
- run multiple retrieval attempts and merge ranked evidence
- verify draft answers against authorized context
- optionally run one focused refinement retrieval round
- return insufficiency when evidence cannot be verified safely
- batch large Chroma metadata updates and deletes to stay under collection limits
- call Groq with authorized context only
- stream verified grounded answer tokens
- return structured answer, explanation, and sources
Legacy workspace retrieval support.
Responsibilities:
- read JSON-extracted PDF text
- store per-workspace chunks in a legacy Chroma collection
- rank and return chunks from older collections
- recover readable source names
- recover page numbers from legacy metadata
- expand heading-only matches into richer page-level snippets
This module is useful because some older uploaded data exists in collections such as chat_hr-user.
Legacy PDF-to-JSON extractor using PyMuPDF and Pillow.
Responsibilities:
- read each page
- extract text
- extract images
- save JSON to
Backend/jsons/ - save images to
Backend/jsons/ExtractedImages/
Important note:
- this is not the main enterprise upload path used by
POST /api/upload/file - it remains in the repo for older extraction and compatibility utilities
Converts PowerPoint files to PDF using Aspose Slides before chunking and ingestion.
Older orchestration code paths kept in the repo for legacy use and compatibility. The current enterprise backend path is centered on:
main.pyauth.pydb.pyrag.py
The frontend is a single-page React app with a dark minimal UI inspired by ChatGPT.
Application shell and state manager.
Responsibilities:
- restores auth state from local storage
- handles login/logout
- stores frontend chat history per user
- submits streaming chat requests to the backend
- opens and closes both sidebars
- normalizes returned sources
- controls upload state and document state
Frontend API client wrapper.
Responsibilities:
- builds backend URLs
- stores JWT in local storage
- calls login
- fetches current user
- sends standard and streaming chat messages
- uploads files
API base URL configuration:
export const API_BASE_URL =
import.meta.env.VITE_API_BASE_URL ?? 'http://localhost:8000'Simple login screen with:
- email field
- password field
- sign-in button
- demo email buttons
Minimal top bar with:
New chatLogout
Left sidebar.
Contains:
- conversation history
+ New chat- content ingest panel
- close button
Right sidebar for evidence.
Displays:
- document title
- page
- confidence
- retrieved snippet
Centered message area with:
- user and assistant messages
- citations
- suggested queries
- typing indicator
Composer with:
- textarea
- send button
- microphone icon
- browser speech-recognition support if available
Admin-only document management screen.
Supports:
- listing files
- upload controls
- visibility changes
- deletion
- basic file stats
Frontend helper data used for:
- demo account shortcuts
- visibility labels
- initial local document list
- suggested questions
- welcome chat seed
- local-only chat history behavior
Important note:
- The actual answer generation now comes from the backend.
- Some UI document state is still partially mocked/local for convenience.
RBAC is enforced before request processing.
Admin- can upload documents
- can query documents
- can view all categories
HR- cannot upload through the protected backend endpoint
- can query allowed categories
Developer- cannot upload through the protected backend endpoint
- can query allowed categories
| Endpoint | Access |
|---|---|
POST /login and POST /api/auth/login |
public |
GET /me and GET /api/auth/me |
authenticated |
POST /upload and POST /api/upload/file |
admin only |
POST /query and POST /api/chat |
authenticated |
POST /api/chat/stream |
authenticated |
RBAC is implemented with:
get_current_user()require_roles(...)
Unauthorized requests return:
401for missing or invalid token403for forbidden access
RBS is the data-level security layer inside retrieval.
| Role | Allowed Categories |
|---|---|
Admin |
HR, TECH, FINANCE, GENERAL |
HR |
HR, GENERAL |
Developer |
TECH, GENERAL |
Each enterprise chunk stores metadata shaped like:
{
"document_id": "uuid",
"document": "Benefits_Handbook.pdf",
"category": "HR",
"sensitivity": "confidential",
"visibility_scope": "hr",
"page": 6,
"uploaded_by": "admin"
}The backend filters ChromaDB with:
where = {
"$and": [
{"category": {"$in": allowed_categories}},
{"visibility_scope": {"$in": allowed_visibility_scopes}}
]
}- unauthorized categories are excluded before ranking
- unauthorized visibility scopes are excluded before ranking
- unauthorized chunks are never sent to the LLM
- if nothing useful is found, the user gets a safe fallback
Safe fallback:
No accessible data found for your role
This project currently supports two retrieval paths:
- collection:
enterprise_chunks - category-aware
- preferred path
- collections like
chat_hr-user - older workspace-based chunk storage
- used only when enterprise chunks are missing for a query scope
This was added so existing indexed content does not instantly break while the system moves to the enterprise RBAC/RBS design.
The backend prompt strategy in Backend/rag.py is intentionally strict even though the overall flow is now agentic:
- answer only from retrieved context
- say clearly when context is insufficient
- do not invent policy details
- keep answers concise
In practice, the LLM is given:
- the user question
- only the authorized retrieved snippets
- instructions to ground the answer entirely in those snippets
The frontend was shaped around a simple, minimal, ChatGPT-like brief:
Create a black, minimal chat UI similar in feel to ChatGPT.
Keep the login screen very simple with only email and password.
Show demo email shortcuts.
On the chat page, keep only New chat and Logout in the navbar.
Use a left sidebar for history and content ingest.
Use a right sidebar for evidence.
Make both sidebars collapsible.
Keep the center focused on the conversation.
Replace the Mic text with a microphone icon.
Avoid clutter, large dashboard cards, and extra control boxes.
This prompt explains the current frontend direction:
- dark theme
- low visual noise
- centered chat
- evidence-first explainability
- minimal actions
- dark theme
- background
#212121 - card surfaces around
#171717and#212121 - simple rounded panels
- minimal chrome
- no marketing-style hero sections
- top navbar
- left collapsible sidebar for history and ingest
- centered chat conversation
- right collapsible evidence viewer
- simple form
- clear demo entry points
- direct error message display
- user message bubble on the right
- assistant messages stream into the main feed
- citation chips below assistant response
- explanation text below answer
- evidence opens in the right sidebar
- page-specific questions can return evidence from the exact requested page when the document is resolved
- document list
- upload
- visibility changes
- delete action
- summary cards for file counts
Request:
{
"email": "[email protected]",
"password": "hr123"
}Response:
{
"access_token": "jwt-token",
"token_type": "bearer",
"user": {
"id": "hr-user",
"username": "hr",
"role": "HR",
"email": "[email protected]"
}
}Headers:
Authorization: Bearer <token>
Response:
{
"id": "hr-user",
"username": "hr",
"role": "HR",
"email": "[email protected]"
}Admin only.
Multipart form fields:
filecategorysensitivityvisibility_scopesession_id
Supported file formats:
pdfpptpptxdocxxlsxtxtmdcsvjson
Response:
{
"message": "Document uploaded and indexed successfully",
"document_id": "uuid",
"document": "Benefits_Handbook.pdf",
"category": "HR",
"sensitivity": "confidential",
"chunks_indexed": 24
}Behavior notes:
- the request returns only after indexing completes
- the backend prints stage progress in the server terminal during extraction, chunking, and indexing
Request:
{
"query": "Summarize the maternity leave eligibility rule.",
"chat_id": "hr-user",
"doc_uuid": null,
"chat_history": []
}Response:
{
"answer": "string",
"explanation": "string",
"sources": [
{
"document": "Benefits_Handbook.pdf",
"snippet": "Maternity leave is available...",
"page": 6,
"confidence": "94%"
}
]
}Behavior notes:
- if a question targets a specific page in a resolved document, the backend prefers exact-page retrieval over general semantic search
- shorthand references such as
ITC pdfmay resolve to a matching accessible document without requiring the full filename - if the requested page exists in the document record but has no indexed text, the backend returns a direct insufficiency message for that page
Authenticated NDJSON streaming endpoint. The frontend currently prefers this route for chat.
Event examples:
{"type":"token","delta":"Maternity leave "}
{"type":"token","delta":"is available ..."}
{"type":"final","answer":"Maternity leave is available ...","explanation":"string","sources":[{"document":"Benefits_Handbook.pdf","snippet":"...","page":6,"confidence":"94%"}]}Response:
{
"status": "ok",
"message": "Backend is running"
}- Python 3.11+ or 3.12
- Node.js 18+
- MongoDB running locally or remotely
- Groq API key
From the repo root:
python -m venv .venvWindows PowerShell:
.\.venv\Scripts\Activate.ps1Install dependencies:
pip install -r requirements.txtCreate Backend/.env based on:
GROQ_API_KEY=replace-with-your-groq-key
MONGODB_URI=mongodb://127.0.0.1:27017
MONGODB_DB_NAME=findx
JWT_SECRET=replace-with-a-long-random-secret
JWT_ALGORITHM=HS256
JWT_EXPIRE_MINUTES=60Run the backend:
cd Backend
uvicorn main:app --host 0.0.0.0 --port 8000 --reloadCompatibility run command:
cd Backend
uvicorn server:app --host 0.0.0.0 --port 8000 --reloadcd Frontend
npm install
npm run devOptional frontend API override:
VITE_API_BASE_URL=http://localhost:8000cd Frontend
npm run buildThe backend seeds these users automatically if they do not exist:
| Role | Password | |
|---|---|---|
| Admin | [email protected] |
admin123 |
| HR | [email protected] |
hr123 |
| Developer | [email protected] |
developer123 |
Used for:
- users
- document records
- query logs
Used for:
- enterprise chunk embeddings
- legacy workspace chunk embeddings
Used for:
- uploaded source files in
Backend/downloads/ - ChromaDB storage in
Backend/chroma_db_storage/
Legacy or compatibility utilities may also write:
- extracted JSON in
Backend/jsons/ - extracted images in
Backend/jsons/ExtractedImages/
Every query is recorded in MongoDB as:
{
"username": "hr",
"role": "HR",
"query": "Summarize the maternity leave eligibility rule.",
"timestamp": "UTC datetime"
}Upload and ingestion progress is also printed in the backend terminal. Typical stages are:
Uploadfor request receipt, completion, rejection, or failureEXTRACTfor page-level PDF text extraction progressCHUNKfor page-level chunk preparation progressINDEXfor batched embedding and Chroma write progressDONEfor final ingestion summary
- The enterprise RBAC/RBS backend is the main path.
- Some frontend document management behavior still uses local mock state for convenience.
- The upload UI does not yet fully expose backend category selection in an enterprise-perfect way.
- The current upload route is synchronous: the API responds only after ingestion completes.
- Large uploads are now processed in tracked stages with batched indexing and terminal progress logs.
- Page-specific document questions now use exact-page lookup when the document can be resolved from the request.
- Large visibility updates and deletes are batched to stay within Chroma collection limits.
- Legacy content can still be searched if enterprise chunks are unavailable.
- If the indexed data itself is unrelated, retrieval will still return "No accessible data found for your role."
- frontend document state is not fully backend-driven
- legacy and enterprise retrieval coexist during migration
- upload flow needs stronger category wiring from the frontend
- live ingestion progress is only visible in the backend terminal, not yet in the browser UI
- very large uploads still hold the request open because ingestion is synchronous
- exact-page lookup depends on the document being resolvable from the request or explicitly provided as
doc_uuid - there is no full admin user-management panel yet
- document deletion currently affects frontend state, not a full backend governance lifecycle
- source confidence is a retrieval heuristic, not a calibrated probability
- wire category and sensitivity controls directly into the upload API from the frontend
- replace local document state with real backend document CRUD
- add reranking
- add document ownership and delete APIs in the backend
- add admin user management endpoints
- surface ingestion progress in the UI or move large-document indexing to background jobs
- add audit views for query logs
- add tests for auth, RBAC, and retrieval filters
Useful commands used during development:
python -m py_compile Backend/main.py Backend/rag.py Backend/auth.py Backend/db.py Backend/pdf_chroma_ingest.pycd Frontend
npm run build- never commit a real
GROQ_API_KEY - use a strong random
JWT_SECRET - rotate any exposed key immediately
- keep
.envout of version control - enforce RBAC before processing uploads or queries
- enforce RBS before sending any context to the LLM
Old level:
- secure role-aware RAG prototype
- grounded retrieval with evidence snippets
- streaming chat and admin upload flow
New current level:
- retrieval-focused enterprise agentic RAG
- follow-up rewrite and multi-attempt retrieval planning
- shorthand document resolution and exact-page retrieval
- verifier-backed answer finalization with one refinement round
- safe insufficiency behavior for unsupported questions
- admin upload flow with batched indexing progress in the backend terminal
- batched Chroma visibility updates and deletes
- query logging and evidence display
The best next milestone is to finish the migration from partially local frontend document state to a fully backend-driven document lifecycle.
79fd667 (Bibin, refined rag approach with chatgpt clean theme)