# bhavjeetsingh/contractiq architecture

> Architecture diagram of the GitHub repository bhavjeetsingh/contractiq, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-06-15). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/bhavjeetsingh/contractiq
- Repository: https://github.com/bhavjeetsingh/contractiq

## Overview

1. **System shape**
   ContractIQ is a FastAPI-based document intelligence service with a thin HTML frontend. The browser-facing layer lives in `templates/` and `static/`, while almost all business logic sits under `src/`. The app is centered on contract PDFs and exposes analysis, comparison, and chat-style Q&A workflows.

2. **Request entry point**
   `api/main.py` is the main orchestration layer. It wires routes, file upload handling, template rendering, and health checks. From an architecture standpoint, this is the boundary between HTTP requests and the internal document-processing pipelines.

3. **Document ingestion boundary**
   `src/document_ingestion/` handles the first stage of every document workflow: saving uploaded files, reading PDF content page by page, and preparing content for downstream processing. This is the shared entry path for analysis, comparison, and chat indexing, so it acts as the normalization layer for all document inputs.

4. **Analysis pipeline**
   `src/document_analyzer/data_analysis.py` is responsible for extracting structured contract intelligence such as metadata, summary, sentiment/tone, and obligations. It uses LLM prompting plus structured output models from `model/models.py`, so the output is not just free text but schema-shaped data suitable for API responses.

5. **Comparison pipeline**
   `src/document_compare/document_comparator.py` compares two document versions, likely page-by-page or section-by-section, and asks the model to identify differences and meaningful changes. This is a separate pipeline from analysis because it consumes two inputs and produces a delta-oriented result rather than a single-document summary.

6. **Conversational RAG subsystem**
   `src/document_chat/` implements the multi-document Q&A flow. `retrieval.py` and `hybrid_retrieval.py` provide retrieval logic, while `sse_streaming.py` suggests optional streaming response support. The README indicates a session-scoped FAISS index, so chat is built around document indexing per session followed by retrieval-augmented generation on query.

7. **LLM and prompt layer**
   The model-agnostic orchestration is concentrated in `prompt/prompt_library.py`, `utils/model_loader.py`, and `config/config.yaml`. This layer configures the actual model providers described in the README: Groq-hosted LLMs for generation and Google Gemini embeddings for vectorization. LangChain is the integration framework connecting prompts, parsers, and model calls.

8. **Structured outputs and domain schemas**
   `model/models.py` defines the Pydantic schemas that constrain responses from analysis and related workflows. This is an important architectural boundary: unstructured LLM output is forced into typed application models before it reaches API consumers.

9. **Cross-cutting platform services**
   Logging, exceptions, and rate control are implemented as shared infrastructure rather than feature code. `logger/custom_logger.py` provides structured JSON logs, `exception/custom_exception.py` captures rich traceback context, and `utils/rate_limiter.py` suggests request throttling support. These apply across routes rather than inside one business feature.

10. **Session, auth, and caching hooks**
   `src/auth/jwt_handler.py` and `src/cache/redis_cache.py` indicate planned or partial supporting services for identity and response caching. Even if not central today, they define architectural seams for future user isolation, protected routes, and reduced LLM latency.

11. **Evaluation and tracing**
   `src/eval/ragas_evaluator.py`, `run_eval.py`, and `utils/langsmith_tracer.py` form the quality/observability lane. This is separate from production request handling and is used to score or inspect retrieval-generation quality, which matters for a contract-analysis product where answer fidelity is critical.

12. **Deployment and runtime**
   Production deployment is containerized with Docker and described in `infrastructure/document-portal-cf.yaml`. The repo also includes AWS ECS Fargate, ECR, Secrets Manager, and CloudWatch integration, so the runtime boundary is a managed container service with externalized secret management and centralized logs. GitHub Actions in `.github/workflows/ci.yaml` handles CI/CD.

13. **Frontend and UX boundary**
   The HTML templates (`templates/index.html`, `templates/login.html`) and `static/style.css` suggest a server-rendered UI rather than a separate SPA. The frontend’s role is primarily to submit PDFs, render results, and drive chat/comparison workflows against the FastAPI backend.

14. **Testing and validation**
   `tests/test_routes.py` and `tests/test_unit_cases.py` verify both API behavior and core utility logic. This shows the repo treats route correctness and internal processing as separate test surfaces, which is useful when diagramming trust boundaries around HTTP input and document-processing internals.

Main entry points: [`api/main.py`](https://github.com/bhavjeetsingh/contractiq/blob/main/api/main.py) (API app), [`src/document_chat/retrieval.py`](https://github.com/bhavjeetsingh/contractiq/blob/main/src/document_chat/retrieval.py) (Chat RAG), [`src/document_analyzer/data_analysis.py`](https://github.com/bhavjeetsingh/contractiq/blob/main/src/document_analyzer/data_analysis.py) (Analysis), [`src/document_ingestion/data_ingestion.py`](https://github.com/bhavjeetsingh/contractiq/blob/main/src/document_ingestion/data_ingestion.py) (Ingestion)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_group_api["HTTP App"]
  node_api_main["API app<br/>fastapi entrypoint<br/>[main.py]"]
  node_templates_ui["UI templates<br/>server-rendered views<br/>[index.html]"]
  node_static_ui["Styles<br/>frontend assets<br/>[style.css]"]
end

subgraph group_group_core["Core Pipelines"]
  node_ingestion["Ingestion<br/>pdf intake<br/>[data_ingestion.py]"]
  node_analysis["Analysis<br/>[data_analysis.py]"]
  node_comparison["Compare docs<br/>diff pipeline"]
  node_chat["Chat RAG<br/>document Q&A<br/>[retrieval.py]"]
  node_hybrid_retrieval["Hybrid search<br/>retrieval engine"]
  node_streaming["SSE stream<br/>response streaming<br/>[sse_streaming.py]"]
end

subgraph group_group_llm["LLM Layer"]
  node_prompts["Prompt library<br/>prompt orchestration<br/>[prompt_library.py]"]
  node_model_loader["Model loader<br/>provider config<br/>[model_loader.py]"]
  node_schemas["Schemas<br/>pydantic models<br/>[models.py]"]
  node_config["Config<br/>runtime settings<br/>[config.yaml]"]
end

subgraph group_group_platform["Platform Services"]
  node_logging["Logging<br/>structured logs<br/>[custom_logger.py]"]
  node_exceptions["Exceptions<br/>error handling"]
  node_auth["JWT auth<br/>auth helper<br/>[jwt_handler.py]"]
  node_cache["Redis cache<br/>cache layer<br/>[redis_cache.py]"]
  node_rate_limit["Rate limit<br/>throttle<br/>[rate_limiter.py]"]
end

subgraph group_group_ops["Ops & Quality"]
  node_eval["RAG eval<br/>quality scoring<br/>[ragas_evaluator.py]"]
  node_tracing["Tracing<br/>observability"]
  node_deployment["Deploy<br/>infra config"]
  node_ci["CI/CD<br/>automation<br/>[ci.yaml]"]
end

node_api_main -->|"uploads"| node_ingestion
node_api_main -->|"analyzes"| node_analysis
node_api_main -->|"compares"| node_comparison
node_api_main -->|"serves chat"| node_chat
node_api_main -->|"renders"| node_templates_ui
node_templates_ui -.->|"styles"| node_static_ui
node_ingestion -->|"feeds"| node_analysis
node_ingestion -->|"feeds"| node_comparison
node_ingestion -->|"indexes"| node_chat
node_chat -->|"retrieves"| node_hybrid_retrieval
node_chat -.->|"streams"| node_streaming
node_analysis -->|"uses"| node_prompts
node_analysis -->|"returns"| node_schemas
node_comparison -->|"uses"| node_prompts
node_chat -->|"uses"| node_prompts
node_prompts -->|"executes on"| node_model_loader
node_model_loader -->|"reads"| node_config
node_analysis -.->|"logs"| node_logging
node_api_main -.->|"handles errors"| node_exceptions
node_api_main -.->|"protects"| node_auth
node_api_main -.->|"caches"| node_cache
node_api_main -.->|"throttles"| node_rate_limit
node_eval -.->|"evaluates"| node_chat
node_tracing -.->|"observes"| node_chat
node_deployment -->|"runs"| node_api_main
node_ci -.->|"delivers"| node_deployment

click node_api_main "https://github.com/bhavjeetsingh/contractiq/blob/main/api/main.py"
click node_templates_ui "https://github.com/bhavjeetsingh/contractiq/blob/main/templates/index.html"
click node_static_ui "https://github.com/bhavjeetsingh/contractiq/blob/main/static/style.css"
click node_ingestion "https://github.com/bhavjeetsingh/contractiq/blob/main/src/document_ingestion/data_ingestion.py"
click node_analysis "https://github.com/bhavjeetsingh/contractiq/blob/main/src/document_analyzer/data_analysis.py"
click node_comparison "https://github.com/bhavjeetsingh/contractiq/blob/main/src/document_compare/document_comparator.py"
click node_chat "https://github.com/bhavjeetsingh/contractiq/blob/main/src/document_chat/retrieval.py"
click node_hybrid_retrieval "https://github.com/bhavjeetsingh/contractiq/blob/main/src/document_chat/hybrid_retrieval.py"
click node_streaming "https://github.com/bhavjeetsingh/contractiq/blob/main/src/document_chat/sse_streaming.py"
click node_prompts "https://github.com/bhavjeetsingh/contractiq/blob/main/prompt/prompt_library.py"
click node_model_loader "https://github.com/bhavjeetsingh/contractiq/blob/main/utils/model_loader.py"
click node_schemas "https://github.com/bhavjeetsingh/contractiq/blob/main/model/models.py"
click node_config "https://github.com/bhavjeetsingh/contractiq/blob/main/config/config.yaml"
click node_logging "https://github.com/bhavjeetsingh/contractiq/blob/main/logger/custom_logger.py"
click node_exceptions "https://github.com/bhavjeetsingh/contractiq/blob/main/exception/custom_exception.py"
click node_auth "https://github.com/bhavjeetsingh/contractiq/blob/main/src/auth/jwt_handler.py"
click node_cache "https://github.com/bhavjeetsingh/contractiq/blob/main/src/cache/redis_cache.py"
click node_rate_limit "https://github.com/bhavjeetsingh/contractiq/blob/main/utils/rate_limiter.py"
click node_eval "https://github.com/bhavjeetsingh/contractiq/blob/main/src/eval/ragas_evaluator.py"
click node_tracing "https://github.com/bhavjeetsingh/contractiq/blob/main/utils/langsmith_tracer.py"
click node_deployment "https://github.com/bhavjeetsingh/contractiq/blob/main/infrastructure/document-portal-cf.yaml"
click node_ci "https://github.com/bhavjeetsingh/contractiq/blob/main/.github/workflows/ci.yaml"

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_api_main,node_templates_ui,node_static_ui toneBlue
class node_ingestion,node_analysis,node_comparison,node_chat,node_hybrid_retrieval,node_streaming toneAmber
class node_prompts,node_model_loader,node_schemas,node_config toneMint
class node_logging,node_exceptions,node_auth,node_cache,node_rate_limit toneRose
class node_eval,node_tracing,node_deployment,node_ci toneIndigo
```

## Components

### HTTP App

FastAPI entrypoint, routes, and browser-facing templates/static assets.

- [API app](https://github.com/bhavjeetsingh/contractiq/blob/main/api/main.py): fastapi entrypoint · Wires HTTP routes, uploads, templates, and health checks. · `api/main.py`
- [UI templates](https://github.com/bhavjeetsingh/contractiq/blob/main/templates/index.html): server-rendered views · Thin HTML frontend for landing, login, and workflow pages. · `templates/index.html`
- [Styles](https://github.com/bhavjeetsingh/contractiq/blob/main/static/style.css): frontend assets · Static browser assets for the rendered UI. · `static/style.css`

### Core Pipelines

Document ingestion and the main contract intelligence workflows.

- [Ingestion](https://github.com/bhavjeetsingh/contractiq/blob/main/src/document_ingestion/data_ingestion.py): pdf intake · Saves uploads and reads PDF content into normalized document data. · `src/document_ingestion/data_ingestion.py`
- [Analysis](https://github.com/bhavjeetsingh/contractiq/blob/main/src/document_analyzer/data_analysis.py): contract analysis · Extracts metadata, summary, tone, and obligations from a single contract. · `src/document_analyzer/data_analysis.py`
- [Compare docs](https://github.com/bhavjeetsingh/contractiq/blob/main/src/document_compare/document_comparator.py): diff pipeline · Compares two document versions and identifies meaningful changes. · `src/document_compare/document_comparator.py`
- [Chat RAG](https://github.com/bhavjeetsingh/contractiq/blob/main/src/document_chat/retrieval.py): document Q&A · Coordinates session-scoped retrieval and answer generation over documents. · `src/document_chat/retrieval.py`
- [Hybrid search](https://github.com/bhavjeetsingh/contractiq/blob/main/src/document_chat/hybrid_retrieval.py): retrieval engine · Combines retrieval strategies for better context selection. · `src/document_chat/hybrid_retrieval.py`
- [SSE stream](https://github.com/bhavjeetsingh/contractiq/blob/main/src/document_chat/sse_streaming.py): response streaming · Streams chat or generation responses to the client. · `src/document_chat/sse_streaming.py`

### LLM Layer

Prompting, model loading, and structured output schemas.

- [Prompt library](https://github.com/bhavjeetsingh/contractiq/blob/main/prompt/prompt_library.py): prompt orchestration · Centralizes model prompts used across analysis and chat workflows. · `prompt/prompt_library.py`
- [Model loader](https://github.com/bhavjeetsingh/contractiq/blob/main/utils/model_loader.py): provider config · Initializes configured LLM and embedding providers from app settings. · `utils/model_loader.py`
- [Schemas](https://github.com/bhavjeetsingh/contractiq/blob/main/model/models.py): pydantic models · Defines typed outputs for analysis and other structured responses. · `model/models.py`
- [Config](https://github.com/bhavjeetsingh/contractiq/blob/main/config/config.yaml): runtime settings · Holds model and application configuration values. · `config/config.yaml`

### Platform Services

Shared infrastructure, auth, cache, logging, and rate control.

- [Logging](https://github.com/bhavjeetsingh/contractiq/blob/main/logger/custom_logger.py): structured logs · Shared JSON logging for application events and errors. · `logger/custom_logger.py`
- [Exceptions](https://github.com/bhavjeetsingh/contractiq/blob/main/exception/custom_exception.py): error handling · Wraps failures with rich traceback and application context. · `exception/custom_exception.py`
- [JWT auth](https://github.com/bhavjeetsingh/contractiq/blob/main/src/auth/jwt_handler.py): auth helper · Handles token-based identity and route protection hooks. · `src/auth/jwt_handler.py`
- [Redis cache](https://github.com/bhavjeetsingh/contractiq/blob/main/src/cache/redis_cache.py): cache layer · Provides shared caching for responses or session data. · `src/cache/redis_cache.py`
- [Rate limit](https://github.com/bhavjeetsingh/contractiq/blob/main/utils/rate_limiter.py): throttle · Applies request throttling across API surfaces. · `utils/rate_limiter.py`

### Ops & Quality

Evaluation, tracing, deployment, and CI/CD.

- [RAG eval](https://github.com/bhavjeetsingh/contractiq/blob/main/src/eval/ragas_evaluator.py): quality scoring · Scores retrieval and generation quality for experiments and regression checks. · `src/eval/ragas_evaluator.py`
- [Tracing](https://github.com/bhavjeetsingh/contractiq/blob/main/utils/langsmith_tracer.py): observability · Connects runs to LangSmith-style tracing and inspection. · `utils/langsmith_tracer.py`
- [Deploy](https://github.com/bhavjeetsingh/contractiq/blob/main/infrastructure/document-portal-cf.yaml): infra config · Container and cloud deployment definitions for runtime execution. · `infrastructure/document-portal-cf.yaml`
- [CI/CD](https://github.com/bhavjeetsingh/contractiq/blob/main/.github/workflows/ci.yaml): automation · Continuous integration workflow for validation and delivery. · `.github/workflows/ci.yaml`

## Connections

- API app → Ingestion: uploads · HTTP file uploads enter the ingestion boundary.
- API app → Analysis: analyzes · Routes invoke the single-document analysis pipeline.
- API app → Compare docs: compares · Routes trigger document-to-document comparison.
- API app → Chat RAG: serves chat · API exposes conversational document Q&A.
- API app → UI templates: renders · Server-side HTML is rendered from FastAPI handlers.
- UI templates → Styles: styles · Templates are paired with static browser assets.
- Ingestion → Analysis: feeds · Normalized documents are passed into analysis.
- Ingestion → Compare docs: feeds · Both versions are prepared by ingestion before diffing.
- Ingestion → Chat RAG: indexes · Ingested content is indexed for retrieval and Q&A.
- Chat RAG → Hybrid search: retrieves · Chat uses retrieval logic to select relevant context.
- Chat RAG → SSE stream: streams · Chat responses can be emitted incrementally.
- Analysis → Prompt library: uses · Analysis relies on prompt templates and instructions.
- Analysis → Schemas: returns · Model output is constrained to structured application schemas.
- Compare docs → Prompt library: uses · Comparison prompts the model to identify deltas.
- Chat RAG → Prompt library: uses · RAG answers are generated with shared prompt assets.
- Prompt library → Model loader: executes on · Prompts are run through configured model providers.
- Model loader → Config: reads · Provider and model settings come from configuration.
- Analysis → Logging: logs · Analysis pipeline emits structured logs.
- API app → Exceptions: handles errors · Request failures are wrapped in application exceptions.
- API app → JWT auth: protects · JWT hooks can guard authenticated workflows.
- API app → Redis cache: caches · Shared cache support sits behind request workflows.
- API app → Rate limit: throttles · API traffic can be rate limited at the boundary.
- RAG eval → Chat RAG: evaluates · Quality tooling measures retrieval-generation behavior.
- Tracing → Chat RAG: observes · Tracing inspects chat and model execution.
- Deploy → API app: runs · Deployment targets the FastAPI application runtime.
- CI/CD → Deploy: delivers · CI/CD supports build and deployment workflows.
