# AI Document Analyser
A modular backend and interface for uploading, processing, and querying documents using a Retrieval-Augmented Generation (RAG) pipeline built with FastAPI, ChromaDB, Ollama, and OpenRouter.
---
## Architecture & Data Flow
### Production Ingestion & Storage
User Document (PDF / TXT)
│
▼
[ POST /upload ] ──► Save to Disk (uploads/) & Metadata to SQLite (database.py)
│
▼
Text Extraction (pdf_upload.py via PyMuPDF)
│
▼
Chunking (ingestion.py via RecursiveCharacterTextSplitter)
│
▼
Embeddings Generation (Ollama: nomic-embed-text)
│
▼
Vector Storage (ChromaDB: chroma_db/)
### Production Query & Retrieval
User Query
│
▼
[ POST /ask ] ──► Embed Query (Ollama: nomic-embed-text)
│
▼
Vector Search (retrieval.py against ChromaDB chroma_db/)
│
▼
Context Assembly + Prompt Construction (rag_service.py)
│
▼
LLM Inference (OpenRouter API)
│
▼
Answer + Sources Response
---
## Environment & Test Isolation
The codebase maintains strict isolation between **Production** and **Test** environments to prevent tests from mutating active application state.
```text
Production
├── Production SQLite DB (`database.py` -> default `db_path=None`)
└── Production ChromaDB (`chroma_db/`)
Tests
├── Test SQLite DB (`test_db_path` injected via config/tests)
└── Test ChromaDB (`test_directory` injected via config/tests)
- Database Isolation: Helper functions in
database.pysupport an optionaldb_pathparameter. When omitted, operations target production. Tests explicitly providetest_db_path. - Vector Isolation:
ingestion.pyandretrieval.pyaccept a configurablepersist_directory. Tests direct vector embeddings to a dedicated temporary/test Chroma directory.
| File / Directory | Responsibility |
|---|---|
src/main.py |
App setup, lifespan, router registration, and /ask and /health endpoints. |
src/routes/documents.py |
Document and vector-store endpoints. |
rag_service.py |
Orchestration layer connecting ingestion, querying, and LLM communication. |
ingestion.py |
Handles text chunking, embedding generation, and ChromaDB persistence (accepts persist_directory). |
retrieval.py |
Vector retrieval logic, similarity search, and prompt template construction. |
pdf_upload.py |
Document extraction utilities (PDF and raw text processing via PyMuPDF). |
database.py |
SQLite schema initialization and metadata CRUD helper functions (accepts optional db_path). |
config/settings.py |
Centralized project configuration (model names, chunk sizes, storage and test paths). |
frontend/app.py |
Streamlit web interface ("The Reading Room") for manual testing. |
tests/ |
Automated unit tests (test_ingestion.py) and verification scripts (test_retrieval.py). |
uploads/ |
Local storage destination for uploaded physical files. |
chroma_db/ |
Directory where ChromaDB stores persistent production vector embeddings. |
- Framework: FastAPI, Uvicorn
- Language: Python 3.12+
- Document Processing: PyMuPDF (
fitz), LangChain Text Splitters - Embeddings: Ollama (
nomic-embed-text) - Vector Database: ChromaDB
- LLM Provider: OpenRouter API
- Relational Metadata: SQLite
- Frontend / Inspection: Streamlit
# Clone the repository
git clone <your-repo-url>
cd "AI Document Analyser"
# Install dependencies
uv sync
# Or using pip: pip install -e .
# Start Ollama service
ollama serve
# Pull required embedding model
ollama pull nomic-embed-textCreate a .env file in the project root:
OPENROUTER_API_KEY=your_openrouter_api_key_here# Start FastAPI backend
uv run uvicorn main:app --reload
# Start Streamlit UI (optional)
uv run streamlit run frontend/app.py- Swagger UI:
http://localhost:8000/docs - ReDoc:
http://localhost:8000/redoc - Health Check:
http://localhost:8000/health
# Run isolated ingestion test suite
uv run pytest tests/test_ingestion.py
# Run interactive retrieval test
uv run python tests/test_retrieval.pyGET /health
Response (200 OK):
{
"status": "ok"
}POST /upload
Content-Type: multipart/form-data
Response (200 OK):
{
"id": 1,
"filename": "sample.pdf",
"content_type": "application/pdf",
"size": 1048576,
"saved_to": "uploads/sample.pdf",
"ingestion_status": "ingested",
"chunk_count": 8
}POST /ask
Content-Type: application/json
Request Body:
{
"question": "What is the primary conclusion of the report?"
}Response (200 OK):
{
"answer": "The report concludes that...",
"sources": [
"Excerpt from chunk 1...",
"Excerpt from chunk 2..."
]
}GET /documents
Response (200 OK):
[
{
"id": 1,
"filename": "sample.pdf",
"content_type": "application/pdf",
"file_path": "uploads/sample.pdf",
"size": 1048576,
"uploaded_at": "2026-08-19 14:00:00"
}
]AI Document Analyser/
├── .github/
│ └── copilot-instructions.md # Symlink to ../AGENTS.md
├── .env # Environment secrets (ignored in git)
├── .gitignore # Git ignore rules
├── pyproject.toml # Dependencies and build configuration
├── AGENTS.md # Canonical coding and mentoring instructions
├── README.md # Project architecture, data flows & repository map
├── src/
│ ├── database.py
│ ├── ingestion.py
│ ├── main.py
│ ├── pdf_upload.py
│ ├── rag_service.py
│ ├── retrieval.py
│ ├── vector_store_diagnostics.py
│ ├── models.py
│ └── routes/
│ ├── __init__.py
│ └── documents.py # Document and vector-store endpoints
├── config/
│ └── settings.py # Central application configuration & paths
├── frontend/
│ └── app.py # Streamlit visual interface
├── tests/
│ ├── files/ # Sample mock files for testing
│ ├── test_ingestion.py # Ingestion & chunking test suite (targets test Chroma & SQLite)
│ └── test_retrieval.py # Retrieval validation test suite (targets test Chroma & SQLite)
├── chroma_db/ # Local Chroma vector database directory (production)
└── uploads/ # Local storage for raw uploaded files
- Document-aware chunk metadata and source attribution – I learned to attach a stable
document_idto every chunk before storing it in ChromaDB. After retrieval, I use this metadata to keep chunks from different files distinct, format the retrieved context with explicit document boundaries, and group the source chunks bydocument_id. This allows the application to filter searches to selected documents, compare multiple files without merging their content, and map retrieved evidence back to the correct SQLite document record and filename.
-
Slow inference
-
Upload folder sync & clear endpoint – Solved the out‑of‑sync upload state by implementing a
GET /uploadsendpoint to enumerate files inUPLOADS_DIRand aPOST /uploads/clearendpoint that callsdatabase.clear_uploaded_files()to delete both the physical files and their metadata rows. The Streamlit UI now calls these endpoints, keeping the document list current and providing a single “Clear upload folder” button. -
Multi‑document retrieval – Solved the issue where only the first document’s chunks were retrieved by refactoring
retrieval.pyto perform a Chroma similarity search across all supplieddocument_idsand preserving each chunk’smetadata["source"]. This aggregates relevant chunks from every selected document.
These solutions ensure the RAG pipeline now ingests, stores, and retrieves information from every uploaded document correctly.