How khokan/document-intelligence-service works
1. System shape
- This is a local PDF RAG backend built in Python around FastAPI, ChromaDB, and Ollama.
- The repository is organized as a pipeline: upload/ingest PDFs → extract and clean text → chunk → embed → store in vector DB → retrieve and generate answers.
- All major processing is local; there are no required cloud services.
2. Application entry and API boundary
- main.py is the runtime entrypoint for the FastAPI app.
- The HTTP layer lives under app/api/ and is split by concern: route definitions, dependency wiring, search, and RAG-related endpoints.
- The API exposes document lifecycle operations plus search/query operations, and acts as the only external interface to the core pipeline.
3. Document ingestion subsystem
- app/pdf/ handles file intake and text extraction.
- extractor.py is the PDF-to-text boundary, with cleaner.py normalizing extracted content before downstream processing.
- The README indicates the extractor prefers PdfPlumber and falls back to PyPDF, which matters because extraction quality and page-level source mapping are central to later citations.
4. Text segmentation subsystem
- app/chunking/ breaks cleaned text into retrieval units.
- splitter.py and strategies.py suggest the system supports chunking policies rather than a single hardcoded splitter.
- cache.py indicates chunk results may be reused, which helps avoid recomputing segmentation for repeated ingest or reindex operations.
- The documented target is 500-word chunks with 100-word overlap, which directly affects retrieval granularity and citation quality.
5. Embedding subsystem
- app/embeddings/ converts chunks and queries into vectors.
- client.py is the abstraction for embedding generation, while ollama_service.py shows the embedding model is served locally through Ollama.
- cache.py suggests repeated chunk embeddings are deduplicated or reused, which is important for reindexing and throughput.
- The README specifies nomic-embed-text as the embedding model and a 768-dimensional vector space.
6. Vector storage and persistence
- app/vector_store/ owns semantic storage in ChromaDB.
- chromadb_service.py is the integration point to the database, collection.py likely manages collection-level operations, and persistence.py handles disk-backed state.
- This layer is the persistent retrieval index for all uploaded documents and is the main boundary between ingestion and search.
7. RAG pipeline
- app/rag/ is the orchestration layer that turns a user question into an answer.
- retriever.py performs similarity search over ChromaDB, generator.py produces the natural-language response, and pipeline.py coordinates the full flow.
- This is where document chunks, query embeddings, metadata filters, and LLM output are assembled into a final answer with sources.
- The README’s cited behavior implies the pipeline returns both an answer and structured citations including document id, filename, page, and score.
8. Configuration and validation
- app/utils/ centralizes cross-cutting concerns: config.py loads runtime settings, logger.py sets application logging, and validators.py enforces file/input constraints.
- config.yaml and .env.example define the deployment/runtime knobs for model names, storage paths, chunk sizes, and server settings.
- This layer is important because it controls the boundaries around file size, allowed inputs, model endpoints, and persistence directories.
9. Data model boundary
- app/models/schemas.py contains the Pydantic contracts used by the API and likely by internal service boundaries.
- These schemas define the shape of upload responses, search requests/results, document metadata, and system stats, keeping the API and pipeline decoupled from raw Python dicts.
10. Operational storage and observability
- The repository includes logs/ for runtime logs and likely uploads//chroma_db/ as runtime data directories, even if they are not fully shown in the tree.
- Logging is a first-class concern because the app is meant to run as a local service and needs traceability for ingestion, indexing, retrieval, and LLM generation.
- The project also includes installation, completion, and status documents, which suggests active operational scaffolding around the codebase.
11. Test architecture
- tests/unit/ covers isolated behavior for PDF handling, chunking, embeddings, validators, vector store, and RAG pipeline logic.
- tests/integration/ exercises end-to-end flows such as API behavior, search, chunking, embeddings, and the RAG workflow.
- The presence of a sample PDF and dedicated integration tests indicates the architecture is validated primarily through pipeline-level correctness, not just component tests.
12. External/runtime dependencies that affect architecture
- The two material runtime services are Ollama for local model inference and ChromaDB for vector retrieval.
- The API is designed to run under FastAPI/Uvicorn, but the real architectural constraint is that both the embedding model and LLM are local and must be reachable from the app.
- This makes the system effectively an offline document intelligence service with local persistence and local model serving.
13. Primary end-to-end flow
- A PDF enters via the API upload path, is validated, extracted, cleaned, chunked, embedded, and stored in ChromaDB with metadata.
- A user query enters via the search/RAG path, is embedded, matched against stored vectors, filtered by metadata if provided, and passed to the LLM for answer synthesis.
- The response exits as structured JSON containing the answer and source evidence, which is the core architectural contract of the system.
Main entry points: pipeline.py RAG Pipeline · unit Unit Tests · rag.py RAG API · splitter.py Splitter
Components 25
Runtime
Entrypoint and external surface
- main.py · Bootstraps the service runtime and app startup
main.py - Routes · Top-level API route definitions
app/api/routes.py - Deps · Dependency injection and shared service wiring for endpoints
app/api/deps.py - Search API · Query and search-facing HTTP handlers
app/api/search.py - RAG API · Answer-generation HTTP handlers and document lifecycle integration
app/api/rag.py
Ingestion
PDF intake and text preparation
Indexing
Chunking, embeddings, and vector storage
- Splitter · Breaks cleaned text into retrieval chunks
app/chunking/splitter.py - Strategies · Chunking policy definitions and variants
app/chunking/strategies.py - Chunk Cache · Caches chunking results for repeat runs
app/chunking/cache.py - Embed Client · Creates embeddings for chunks and queries
app/embeddings/client.py - Ollama · Local Ollama-backed embedding service integration
app/embeddings/ollama_service.py - Embed Cache · Caches embedding results for throughput and deduplication
app/embeddings/cache.py - Chroma Service · ChromaDB integration for vector operations
app/vector_store/chromadb_service.py - Collection · Collection-level vector store operations
app/vector_store/collection.py - Persistence · Disk-backed vector store state and storage handling
app/vector_store/persistence.py
Query
Retrieval and answer generation
- Retriever · Finds relevant chunks from the vector store
app/rag/retriever.py - Generator · Produces natural-language answers from retrieved context
app/rag/generator.py - RAG Pipeline · Coordinates retrieval, ranking, and response assembly
app/rag/pipeline.py
Shared
Cross-cutting utilities and schemas
- Schemas · Shared API and service contracts
app/models/schemas.py - Config · Loads runtime configuration and environment settings
app/utils/config.py - Validators · Enforces file and request constraints
app/utils/validators.py - Logger · Application logging configuration
app/utils/logger.py
Tests
Unit and integration coverage
- Unit Tests · Isolated component tests
tests/unit - Integration Tests · End-to-end and API workflow tests
tests/integration
Connections 38
- main.py → Routes: serves · Mounts the HTTP API surface
- Routes → Deps: uses · Resolves shared dependencies for handlers
- Routes → Search API: exposes · Search-related endpoints
- Routes → RAG API: exposes · RAG and document lifecycle endpoints
- Search API → Schemas: returns · Uses shared request/response contracts
- RAG API → Schemas: returns · Uses structured API schemas
- RAG API → Validators: checks · Validates uploads and request inputs
- Deps → Config: loads · Injects configured services and paths
- Deps → Logger: configures · Shares application logging
- RAG API → Extractor: ingests · Starts PDF extraction for uploads
- Extractor → Cleaner: passes to · Cleans extracted text before indexing
- Cleaner → Splitter: feeds · Prepared text is segmented into chunks
- Splitter → Strategies: selects · Applies chunking policy variants
- Splitter → Chunk Cache: reuses · Avoids recomputing segmentation
- Splitter → Embed Client: outputs · Chunked text is sent for embedding
- Embed Client → Ollama: uses · Delegates vector generation to local Ollama
- Embed Client → Embed Cache: reuses · Caches repeated embedding work
- Embed Client → Chroma Service: stores in · Writes embeddings and metadata to ChromaDB
- Chroma Service → Collection: manages · Coordinates collection-level index operations
- Chroma Service → Persistence: persists · Backs the vector index on disk
- Search API → RAG Pipeline: queries · Search requests enter the RAG flow
- RAG API → RAG Pipeline: invokes · Answer requests execute the full pipeline
- RAG Pipeline → Retriever: retrieves · Finds relevant chunks for a question
- RAG Pipeline → Generator: generates · Synthesizes the final answer
- Retriever → Chroma Service: searches · Runs similarity search over the vector store
- RAG Pipeline → Schemas: formats · Produces structured answer and citation payloads
- RAG Pipeline → Config: reads · Uses runtime settings for model and store behavior
- Unit Tests → Extractor: covers · Validates PDF extraction behavior
- Unit Tests → Splitter: covers · Validates chunking logic
- Unit Tests → Embed Client: covers · Validates embedding behavior
- Unit Tests → RAG Pipeline: covers · Validates orchestration logic
- Unit Tests → Validators: covers · Validates input constraints
- Unit Tests → Chroma Service: covers · Validates vector store behavior
- Integration Tests → RAG API: covers · Exercises upload and answer endpoints
- Integration Tests → Search API: covers · Exercises search endpoints
- Integration Tests → RAG Pipeline: covers · Exercises the end-to-end RAG workflow
- Integration Tests → Splitter: covers · Exercises chunking integration behavior
- Integration Tests → Embed Client: covers · Exercises embedding integration behavior