8000 GitHub - gitInfinity/FileChat: FileChat — AI-Powered Document Q&A System Built a Retrieval-Augmented Generation (RAG) system that enables users to upload documents and interact with them through natural-language queries. Developed a FastAPI backend for document ingestion, text extraction, chunking, embedding generation, and semantic retrieval using PyMuPDF, Ollama, and ChromaDB · GitHub
[go: up one dir, main page]

Skip to content
gitInfinityPublic

About

FileChat — AI-Powered Document Q&A System Built a Retrieval-Augmented Generation (RAG) system that enables users to upload documents and interact with them through natural-language queries. Developed a FastAPI backend for document ingestion, text extraction, chunking, embedding generation, and semantic retrieval using PyMuPDF, Ollama, and ChromaDB

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

# 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.py support an optional db_path parameter. When omitted, operations target production. Tests explicitly provide test_db_path.
  • Vector Isolation: ingestion.py and retrieval.py accept a configurable persist_directory. Tests direct vector embeddings to a dedicated temporary/test Chroma directory.

Key Files & Responsibilities

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.

Technology Stack

  • 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

Setup & Installation

1. Prerequisites

  • Python 3.12+
  • uv (recommended) or pip
  • Ollama installed and running

2. Local Environment Setup

# 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-text

3. Environment Variables

Create a .env file in the project root:

OPENROUTER_API_KEY=your_openrouter_api_key_here

4. Running the Application

# 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

5. Running Tests

# Run isolated ingestion test suite
uv run pytest tests/test_ingestion.py

# Run interactive retrieval test
uv run python tests/test_retrieval.py

API Reference

Health Check

GET /health

Response (200 OK):

{
  "status": "ok"
}

Upload Document

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
}

Ask Question (RAG)

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..."
  ]
}

List Documents

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"
  }
]

Project Structure

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

What I Learned

  • Document-aware chunk metadata and source attribution – I learned to attach a stable document_id to 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 by document_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.

Problems I Solved

  • Slow inference

  • Upload folder sync & clear endpoint – Solved the out‑of‑sync upload state by implementing a GET /uploads endpoint to enumerate files in UPLOADS_DIR and a POST /uploads/clear endpoint that calls database.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.py to perform a Chroma similarity search across all supplied document_ids and preserving each chunk’s metadata["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.

About

FileChat — AI-Powered Document Q&A System Built a Retrieval-Augmented Generation (RAG) system that enables users to upload documents and interact with them through natural-language queries. Developed a FastAPI backend for document ingestion, text extraction, chunking, embedding generation, and semantic retrieval using PyMuPDF, Ollama, and ChromaDB

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

0