# khokan/document-intelligence-service architecture

> Architecture diagram of the GitHub repository khokan/document-intelligence-service, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-07-10). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/khokan/document-intelligence-service
- Repository: https://github.com/khokan/document-intelligence-service

## Overview

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: [`app/rag/pipeline.py`](https://github.com/khokan/document-intelligence-service/blob/main/app/rag/pipeline.py) (RAG Pipeline), [`tests/unit`](https://github.com/khokan/document-intelligence-service/tree/main/tests/unit) (Unit Tests), [`app/api/rag.py`](https://github.com/khokan/document-intelligence-service/blob/main/app/api/rag.py) (RAG API), [`app/chunking/splitter.py`](https://github.com/khokan/document-intelligence-service/blob/main/app/chunking/splitter.py) (Splitter)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_runtime["Runtime"]
  node_main["main.py<br/>FastAPI entrypoint<br/>[main.py]"]
  node_api_routes["Routes<br/>[routes.py]"]
  node_api_deps["Deps<br/>DI wiring<br/>[deps.py]"]
  node_api_search["Search API<br/>search endpoints<br/>[search.py]"]
  node_api_rag["RAG API<br/>rag endpoints<br/>[rag.py]"]
end

subgraph group_ingest["Ingestion"]
  node_pdf_extractor["Extractor<br/>pdf-to-text<br/>[extractor.py]"]
  node_pdf_cleaner["Cleaner<br/>text normalization<br/>[cleaner.py]"]
end

subgraph group_indexing["Indexing"]
  node_chunk_splitter["Splitter<br/>chunking engine<br/>[splitter.py]"]
  node_chunk_strategies["Strategies<br/>chunk policies<br/>[strategies.py]"]
  node_chunk_cache["Chunk Cache<br/>reuse cache<br/>[cache.py]"]
  node_embed_client["Embed Client<br/>embedding facade<br/>[client.py]"]
  node_ollama_service["Ollama<br/>local embed model<br/>[ollama_service.py]"]
  node_embed_cache["Embed Cache<br/>reuse cache<br/>[cache.py]"]
  node_chromadb_service[("Chroma Service<br/>vector DB adapter")]
  node_collection["Collection<br/>index management<br/>[collection.py]"]
  node_persistence["Persistence<br/>disk state<br/>[persistence.py]"]
end

subgraph group_query["Query"]
  node_retriever["Retriever<br/>similarity search<br/>[retriever.py]"]
  node_generator["Generator<br/>answer synthesis<br/>[generator.py]"]
  node_rag_pipeline["RAG Pipeline<br/>orchestration<br/>[pipeline.py]"]
end

subgraph group_shared["Shared"]
  node_schemas["Schemas<br/>pydantic models<br/>[schemas.py]"]
  node_config["Config<br/>runtime settings<br/>[config.py]"]
  node_validators["Validators<br/>input validation<br/>[validators.py]"]
  node_logger["Logger<br/>logging setup<br/>[logger.py]"]
end

subgraph group_tests["Tests"]
  node_unit_tests["Unit Tests<br/>test suite"]
  node_integration_tests["Integration Tests<br/>test suite"]
end

node_main -->|"serves"| node_api_routes
node_api_routes -->|"uses"| node_api_deps
node_api_routes -->|"exposes"| node_api_search
node_api_routes -->|"exposes"| node_api_rag
node_api_search -->|"returns"| node_schemas
node_api_rag -->|"returns"| node_schemas
node_api_rag -->|"checks"| node_validators
node_api_deps -->|"loads"| node_config
node_api_deps -->|"configures"| node_logger
node_api_rag -->|"ingests"| node_pdf_extractor
node_pdf_extractor -->|"passes to"| node_pdf_cleaner
node_pdf_cleaner -->|"feeds"| node_chunk_splitter
node_chunk_splitter -->|"selects"| node_chunk_strategies
node_chunk_splitter -->|"reuses"| node_chunk_cache
node_chunk_splitter -->|"outputs"| node_embed_client
node_embed_client -->|"uses"| node_ollama_service
node_embed_client -->|"reuses"| node_embed_cache
node_embed_client -->|"stores in"| node_chromadb_service
node_chromadb_service -->|"manages"| node_collection
node_chromadb_service -->|"persists"| node_persistence
node_api_search -->|"queries"| node_rag_pipeline
node_api_rag -->|"invokes"| node_rag_pipeline
node_rag_pipeline -->|"retrieves"| node_retriever
node_rag_pipeline -->|"generates"| node_generator
node_retriever -->|"searches"| node_chromadb_service
node_rag_pipeline -->|"formats"| node_schemas
node_rag_pipeline -->|"reads"| node_config
node_unit_tests -.->|"covers"| node_pdf_extractor
node_unit_tests -.->|"covers"| node_chunk_splitter
node_unit_tests -.->|"covers"| node_embed_client
node_unit_tests -.->|"covers"| node_rag_pipeline
node_unit_tests -.->|"covers"| node_validators
node_unit_tests -.->|"covers"| node_chromadb_service
node_integration_tests -.->|"covers"| node_api_rag
node_integration_tests -.->|"covers"| node_api_search
node_integration_tests -.->|"covers"| node_rag_pipeline
node_integration_tests -.->|"covers"| node_chunk_splitter
node_integration_tests -.->|"covers"| node_embed_client

click node_main "https://github.com/khokan/document-intelligence-service/blob/main/main.py"
click node_api_routes "https://github.com/khokan/document-intelligence-service/blob/main/app/api/routes.py"
click node_api_deps "https://github.com/khokan/document-intelligence-service/blob/main/app/api/deps.py"
click node_api_search "https://github.com/khokan/document-intelligence-service/blob/main/app/api/search.py"
click node_api_rag "https://github.com/khokan/document-intelligence-service/blob/main/app/api/rag.py"
click node_pdf_extractor "https://github.com/khokan/document-intelligence-service/blob/main/app/pdf/extractor.py"
click node_pdf_cleaner "https://github.com/khokan/document-intelligence-service/blob/main/app/pdf/cleaner.py"
click node_chunk_splitter "https://github.com/khokan/document-intelligence-service/blob/main/app/chunking/splitter.py"
click node_chunk_strategies "https://github.com/khokan/document-intelligence-service/blob/main/app/chunking/strategies.py"
click node_chunk_cache "https://github.com/khokan/document-intelligence-service/blob/main/app/chunking/cache.py"
click node_embed_client "https://github.com/khokan/document-intelligence-service/blob/main/app/embeddings/client.py"
click node_ollama_service "https://github.com/khokan/document-intelligence-service/blob/main/app/embeddings/ollama_service.py"
click node_embed_cache "https://github.com/khokan/document-intelligence-service/blob/main/app/embeddings/cache.py"
click node_chromadb_service "https://github.com/khokan/document-intelligence-service/blob/main/app/vector_store/chromadb_service.py"
click node_collection "https://github.com/khokan/document-intelligence-service/blob/main/app/vector_store/collection.py"
click node_persistence "https://github.com/khokan/document-intelligence-service/blob/main/app/vector_store/persistence.py"
click node_retriever "https://github.com/khokan/document-intelligence-service/blob/main/app/rag/retriever.py"
click node_generator "https://github.com/khokan/document-intelligence-service/blob/main/app/rag/generator.py"
click node_rag_pipeline "https://github.com/khokan/document-intelligence-service/blob/main/app/rag/pipeline.py"
click node_schemas "https://github.com/khokan/document-intelligence-service/blob/main/app/models/schemas.py"
click node_config "https://github.com/khokan/document-intelligence-service/blob/main/app/utils/config.py"
click node_validators "https://github.com/khokan/document-intelligence-service/blob/main/app/utils/validators.py"
click node_logger "https://github.com/khokan/document-intelligence-service/blob/main/app/utils/logger.py"
click node_unit_tests "https://github.com/khokan/document-intelligence-service/tree/main/tests/unit"
click node_integration_tests "https://github.com/khokan/document-intelligence-service/tree/main/tests/integration"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_main,node_api_routes,node_api_deps,node_api_search,node_api_rag toneBlue
class node_pdf_extractor,node_pdf_cleaner toneAmber
class node_chunk_splitter,node_chunk_strategies,node_chunk_cache,node_embed_client,node_ollama_service,node_embed_cache,node_chromadb_service,node_collection,node_persistence toneMint
class node_retriever,node_generator,node_rag_pipeline toneRose
class node_schemas,node_config,node_validators,node_logger toneIndigo
class node_unit_tests,node_integration_tests toneTeal
```

## Components

### Runtime

Entrypoint and external surface

- [main.py](https://github.com/khokan/document-intelligence-service/blob/main/main.py): FastAPI entrypoint · Bootstraps the service runtime and app startup · `main.py`
- [Routes](https://github.com/khokan/document-intelligence-service/blob/main/app/api/routes.py): HTTP routes · Top-level API route definitions · `app/api/routes.py`
- [Deps](https://github.com/khokan/document-intelligence-service/blob/main/app/api/deps.py): DI wiring · Dependency injection and shared service wiring for endpoints · `app/api/deps.py`
- [Search API](https://github.com/khokan/document-intelligence-service/blob/main/app/api/search.py): search endpoints · Query and search-facing HTTP handlers · `app/api/search.py`
- [RAG API](https://github.com/khokan/document-intelligence-service/blob/main/app/api/rag.py): rag endpoints · Answer-generation HTTP handlers and document lifecycle integration · `app/api/rag.py`

### Ingestion

PDF intake and text preparation

- [Extractor](https://github.com/khokan/document-intelligence-service/blob/main/app/pdf/extractor.py): pdf-to-text · PDF extraction boundary with page-aware text output · `app/pdf/extractor.py`
- [Cleaner](https://github.com/khokan/document-intelligence-service/blob/main/app/pdf/cleaner.py): text normalization · Cleans extracted PDF text before segmentation · `app/pdf/cleaner.py`

### Indexing

Chunking, embeddings, and vector storage

- [Splitter](https://github.com/khokan/document-intelligence-service/blob/main/app/chunking/splitter.py): chunking engine · Breaks cleaned text into retrieval chunks · `app/chunking/splitter.py`
- [Strategies](https://github.com/khokan/document-intelligence-service/blob/main/app/chunking/strategies.py): chunk policies · Chunking policy definitions and variants · `app/chunking/strategies.py`
- [Chunk Cache](https://github.com/khokan/document-intelligence-service/blob/main/app/chunking/cache.py): reuse cache · Caches chunking results for repeat runs · `app/chunking/cache.py`
- [Embed Client](https://github.com/khokan/document-intelligence-service/blob/main/app/embeddings/client.py): embedding facade · Creates embeddings for chunks and queries · `app/embeddings/client.py`
- [Ollama](https://github.com/khokan/document-intelligence-service/blob/main/app/embeddings/ollama_service.py): local embed model · Local Ollama-backed embedding service integration · `app/embeddings/ollama_service.py`
- [Embed Cache](https://github.com/khokan/document-intelligence-service/blob/main/app/embeddings/cache.py): reuse cache · Caches embedding results for throughput and deduplication · `app/embeddings/cache.py`
- [Chroma Service](https://github.com/khokan/document-intelligence-service/blob/main/app/vector_store/chromadb_service.py): vector DB adapter · ChromaDB integration for vector operations · `app/vector_store/chromadb_service.py`
- [Collection](https://github.com/khokan/document-intelligence-service/blob/main/app/vector_store/collection.py): index management · Collection-level vector store operations · `app/vector_store/collection.py`
- [Persistence](https://github.com/khokan/document-intelligence-service/blob/main/app/vector_store/persistence.py): disk state · Disk-backed vector store state and storage handling · `app/vector_store/persistence.py`

### Query

Retrieval and answer generation

- [Retriever](https://github.com/khokan/document-intelligence-service/blob/main/app/rag/retriever.py): similarity search · Finds relevant chunks from the vector store · `app/rag/retriever.py`
- [Generator](https://github.com/khokan/document-intelligence-service/blob/main/app/rag/generator.py): answer synthesis · Produces natural-language answers from retrieved context · `app/rag/generator.py`
- [RAG Pipeline](https://github.com/khokan/document-intelligence-service/blob/main/app/rag/pipeline.py): orchestration · Coordinates retrieval, ranking, and response assembly · `app/rag/pipeline.py`

### Shared

Cross-cutting utilities and schemas

- [Schemas](https://github.com/khokan/document-intelligence-service/blob/main/app/models/schemas.py): pydantic models · Shared API and service contracts · `app/models/schemas.py`
- [Config](https://github.com/khokan/document-intelligence-service/blob/main/app/utils/config.py): runtime settings · Loads runtime configuration and environment settings · `app/utils/config.py`
- [Validators](https://github.com/khokan/document-intelligence-service/blob/main/app/utils/validators.py): input validation · Enforces file and request constraints · `app/utils/validators.py`
- [Logger](https://github.com/khokan/document-intelligence-service/blob/main/app/utils/logger.py): logging setup · Application logging configuration · `app/utils/logger.py`

### Tests

Unit and integration coverage

- [Unit Tests](https://github.com/khokan/document-intelligence-service/tree/main/tests/unit): test suite · Isolated component tests · `tests/unit`
- [Integration Tests](https://github.com/khokan/document-intelligence-service/tree/main/tests/integration): test suite · End-to-end and API workflow tests · `tests/integration`

## Connections

- 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
