Skip to main content
Back to Work

GenAI · RAG · AI Systems Engineering

Production-style evidence intelligence and policy RAG system.

Docker ComposeVerified local release

PolicyGPT Enterprise: Building an Evidence-Gated Policy RAG System

A production-style evidence intelligence and policy RAG system with traceable citations, calibrated answerability, measurable evaluation and release-like operations.

When a printed handbook conflicts with the approved repository, PolicyGPT identifies the controlling version and cites page 12 of the sample handbook.

Problem

Enterprise policy answers need to be traceable to the documents that support them. Retrieval similarity alone cannot establish that a passage directly answers a question, and weak evidence must not produce speculative prose.

The system also needs to keep provider outages distinct from unsupported questions. Reviewers must be able to inspect document lifecycle state, page-level evidence, evaluation results and operational readiness instead of trusting an opaque chat response.

Solution

PolicyGPT validates and registers policy PDFs with persistent identity, extracts page-aware text, creates metadata-rich chunks and indexes retrievable evidence in ChromaDB. Every question passes through an answerability gate before optional generation.

Supported results attach page-level citations and interpretable confidence diagnostics. Missing evidence produces a controlled unsupported response, while provider failure preserves answer-ready evidence through citation-only fallback. Evaluation artifacts and readiness views make quality and operational state inspectable.

I built PolicyGPT as an independent local engineering project for policy owners and reviewers who need to verify an answer against its source. The demo uses a fictional HR handbook.

Reliability needPolicyGPT Enterprise contract
Durable document identityPostgreSQL UUID, lifecycle record and SHA-256 identity
Evidence decisionAnswerability assessment before optional generation
Reviewable provenanceDocument, page, section, chunk and excerpt
Unsupported questionsControlled rejection with no unsupported generation
Provider failureCitation-only evidence with explicit degraded state
EvaluationVersioned 24-case holdout with case-level outcomes
OperationsMigrations, liveness, readiness, request IDs and release verification

Engineering milestones

MilestoneDelivered
Document ingestionValidated PDFs, deduplicated by SHA-256, and tracked indexing state in PostgreSQL.
Retrieval and answer gatingIndexed page-aware evidence in ChromaDB and assessed direct support before deciding whether to generate.
Evidence reviewBuilt the Next.js console to show cited passages, refusal reasons, and confidence diagnostics.
Reliability and evaluationAdded citation-only fallback for provider outages, Compose health checks, and read-only views over saved benchmark results.

Technology stack

API

FastAPIPydantic v2PythonSQLAlchemyAlembic

RAG

SentenceTransformersPyMuPDFVector SearchEvidence GatingConfidence Scoring

Persistence

PostgreSQLChromaDBAtomic Source Storage

Generation

GroqOpenAI-compatible APICitation-only Fallback

Frontend

Next.jsReactTypeScriptshadcn / Base UI

Operations

Docker ComposestructlogHealth ChecksNamed Volumes

Testing

pytestVitestRAG EvaluationRelease Verification

Primary skills demonstrated:

RAGLLM EngineeringFastAPINext.jsChromaDBPostgreSQLSentenceTransformersDocker ComposeRAG EvaluationObservability

Architecture flow

Architecture Flow

6 stages
  1. 01Stage

    Validate and register

    Bounded PDF checks, SHA-256 identity, PostgreSQL lifecycle and safe source storage

  2. 02Stage

    Extract and chunk

    Page-aware cleaning with document, page, section and chunk metadata

  3. 03Stage

    Embed and index

    Local SentenceTransformer embeddings persisted in ChromaDB

  4. 04Stage

    Retrieve evidence

    Candidate passages returned with page-level provenance and retrieval diagnostics

  5. 05Stage

    Gate answerability

    Evidence decision runs before optional provider generation

  6. 06Stage

    Return and observe

    Citations, safe fallback, evaluation artifacts, request IDs and readiness state

The ownership boundaries are explicit: PostgreSQL owns identity and lifecycle, source storage owns original PDFs, ChromaDB owns retrievable evidence, and the evaluation workflow owns completed benchmark artifacts.

RAG pipeline

01

Ingestion

Validate the PDF, calculate SHA-256, establish the PostgreSQL lifecycle record and store the source atomically.

02

Indexing

Extract and clean page-aware text, create metadata-rich chunks, embed locally and persist records in ChromaDB.

03

Retrieval

Embed the question and retrieve candidate passages with document, page, section, chunk and score metadata.

04

Answerability

Combine retrieval strength with coverage, numeric consistency, direct support and scope-risk checks.

05

Generation

Call the optional provider only when the evidence gate permits it; otherwise preserve a safe outcome.

06

Citation attachment

Return reviewable excerpts with document, page, section and retrieval diagnostics alongside the result.

Similarity is an engineering signal used inside this workflow. It is not a probability that an answer is correct.

Controlled upload workflow

Synchronous ingestion keeps lifecycle progress inspectable in the verified local release profile. The system validates the file and establishes durable identity before extraction or embedding work begins.

Controlled ingestion workflow

Controlled PDF-ingestion workflow connecting persistent metadata, source storage, extraction, embedding generation, and synchronous evidence indexing.

PostgreSQL document registry

PostgreSQL is the source of truth for safe document identity and lifecycle metadata:

  • document UUID
  • original and safe filename metadata
  • SHA-256 content identity
  • generated storage key
  • lifecycle status and processing stage
  • page, character and chunk counts
  • embedding model and Chroma collection metadata
  • safe failure details
  • created, updated, indexed and failure timestamps

Persistent document registry

Persistent document registry connecting PostgreSQL lifecycle metadata, original PDF storage, and ChromaDB evidence indexing.

PostgreSQL

Identity, lifecycle, counts and safe operational metadata.

Source storage

Original PDF assets stored separately under generated keys.

ChromaDB

Page-aware chunks, metadata and vector evidence.

Document lifecycle detail

Source files and vector evidence remain separate persisted assets. Together with PostgreSQL they form one logical ingestion record, so a future backup must coordinate all three.

Document lifecycle detail

Safe document-detail view showing persistent metadata, vector indexing configuration, and the complete ingestion lifecycle.

Citation and evidence design

Page-level evidence is the primary review object. Generated prose is useful only after the system has established direct support.

Citation 1

sample_hr_policy.pdf

Page 5

3. Remote and Hybrid Work

Employees approved for remote work must maintain a safe, private and reliable workspace. Approved ergonomic or productivity items may be reimbursed up to CAD 300 with receipts and prior approval.

Retrieval score

0.6217

A retrieval input—not guaranteed certainty.

Evidence and answerability diagnostics

The evidence view exposes the factors behind the answerability decision alongside the retrieved passages, so a reviewer can inspect both support quality and provenance.

Evidence and answerability diagnostics

Explainable answerability diagnostics showing retrieval strength, lexical coverage, direct support, scope risk, provider state, and page-level evidence.

Unsupported-answer safety

The same retrieval path can produce three intentionally different outcomes:

01 · Supported

Evidence passes, provider available

Generate an evidence-bound answer and attach page-level citations and diagnostics.

02 · Degraded

Evidence passes, provider unavailable

Return citation-only evidence and identify the provider failure without calling the question unsupported.

03 · Rejected

Evidence does not support the question

Block generation and return a controlled unsupported response instead of speculative prose.

This separation prevents weak evidence and provider outages from collapsing into the same ambiguous “no answer” state.

Unsupported-answer guardrail

PolicyGPT declined to name AtlasWorks’ approved password manager because the indexed passages did not support a product name.

Confidence design

Confidence is an interpretable answerability signal—not guaranteed certainty, an LLM self-rating or a claim that the generated answer is correct.

It is informed by:

  • top retrieval score
  • average retrieval score
  • retrieval margin
  • lexical coverage
  • numeric consistency
  • direct support
  • scope risk

The final decision uses these diagnostics to explain why evidence was accepted or rejected. A high similarity score alone cannot override numeric contradictions, missing direct support or an external-authority question outside the indexed documents.

Confidence scoring

Interpretable answerability diagnostics combining retrieval strength, policy-term coverage, direct support, numeric consistency, and scope-risk checks.

Final holdout evaluation

MeasureSaved local run
Benchmark cases passed23/24
Correct refusals4/4
Request errors0
Expected-page retrieval and answer-readiness accuracy100% each
Generated answers returned for answer-ready cases20/20

The one scored miss came from the keyword checker expecting “locked” when the generated answer said “lock.” The saved run retains that failure. This controlled holdout uses one fictional handbook and measures behavior on those 24 cases.

Final evaluation dashboard

Corrected Evaluation overview showing full run coverage, zero request errors, and the one benchmark case requiring review.

The Evaluation console reads saved JSON and CSV artifacts. A previous provider-disabled run exercised citation-only fallback independently of this generated-answer holdout.

Docker and operations

The v0.3.0 baseline is release-like local orchestration, not a production deployment.

Architecture Flow

4 stages
  1. 01Stage

    PostgreSQL healthy

    Database health gate passes

  2. 02Stage

    Alembic migration completes

    Schema authority exits successfully

  3. 03Stage

    FastAPI ready

    PostgreSQL and Chroma readiness checks pass

  4. 04Stage

    Next.js ready

    The server-side BFF confirms backend readiness

The local release profile includes:

  • non-root backend and frontend containers
  • stable named volumes for PostgreSQL, Chroma, source PDFs, logs and evaluation artifacts
  • request IDs returned in headers and included in structured completion logs
  • separate process liveness and dependency readiness
  • normalized API errors that exclude internal configuration and raw exceptions
  • conservative security headers and server-only upstream configuration
  • smoke testing, preflight checks and release verification

The optional generation provider does not gate readiness because retrieval and citation review remain useful in citation-only mode.

System readiness

System readiness

Repository capture
Dependency-aware system status separating process liveness, PostgreSQL and ChromaDB readiness, provider configuration, and honest production boundaries.

UI/UX

The Next.js enterprise console is organized around four product areas:

Documents

Upload PDFs, inspect registry records, lifecycle state, duplicate handling and document details.

Ask

Compose a policy question and review answerability, answer state, evidence, citations and diagnostics.

Evaluation

Inspect the latest validated benchmark, case outcomes, confidence factors and provider reliability.

System

Review frontend, backend, PostgreSQL, Chroma and optional-provider readiness without exposing internal URLs.

The interface distinguishes processing, ready, failed, unsupported, provider unavailable and dependency unavailable states. This prevents a loading state, ingestion failure, evidence rejection and optional-provider outage from appearing equivalent.

Built vs planned

Built

FastAPI evidence APINext.js enterprise consolePostgreSQL document metadataLocal source PDF storageChromaDB evidence indexingPage-level citationsEvidence gate and unsupported fallbackInterpretable confidence diagnosticsControlled evaluation benchmarkProvider-failure diagnosticsStructured logging and request IDsDocker Compose release profileLiveness and readiness checks

Planned

Authentication and authorizationTenant isolationManaged secretsHosted monitoringBackups and TLS terminationBackground ingestion workersMulti-replica coordinationManaged cloud deployment

Testing and validation

The verified repository baseline includes:

230

Backend tests

128

Frontend tests

23/24

Final holdout cases passed

Passed

Frontend lint

Passed

Production build

Verified

Docker Compose health and release workflow

Validation also covers dataset schema, duplicate-upload behaviour, provider fallback, non-root images, health-gated startup, persistence across a safe Compose restart, smoke testing and release verification.

These are repository validation facts. They are not customer metrics, production usage, a service-level claim or proof of commercial adoption.

Engineering challenges

Challenge

Preserving page provenance during PDF cleaning

Solution

Keep extraction and cleanup page-aware so document, page, section and chunk identity survive indexing.

Challenge

Duplicate prevention before embedding

Solution

Hash the complete file and enforce PostgreSQL uniqueness before extraction and vector writes.

Challenge

Partial ingestion failures

Solution

Persist visible lifecycle stages, compensate for incomplete work and expose safe failure details.

Challenge

Answerability versus similarity

Solution

Add lexical, numeric, direct-support and scope-risk checks rather than treating one vector score as truth.

Challenge

Provider failure

Solution

Retry transient failures, then return citation-only evidence without hiding valid retrieval.

Challenge

Multiple persistence owners

Solution

Assign identity to PostgreSQL, sources to file storage, evidence to Chroma and results to evaluation storage.

Challenge

Dependency-aware startup

Solution

Gate migrations, backend readiness and frontend readiness in explicit order while keeping liveness lightweight.

Engineering decisions

Why gate evidence before calling the provider?

Generation is optional and runs only after retrieved evidence passes the answerability decision. This keeps weak evidence from becoming fluent but unsupported prose.

Why separate PostgreSQL from ChromaDB?

Document identity, lifecycle and operational metadata have different responsibilities from vector retrieval evidence. Keeping those ownership boundaries explicit makes ingestion state, duplicate prevention and recovery easier to reason about.

Why separate provider failure from unsupported evidence?

A provider outage does not erase valid retrieved evidence. When evidence remains answer-ready, citation-only fallback preserves a useful and honest result instead of misclassifying the question as unsupported.

Why is confidence not an LLM self-rating?

The confidence signal is derived from observable retrieval and evidence diagnostics, including strength, coverage, numeric consistency, direct support and scope risk. It does not ask a language model to grade its own answer.

Current limitations and roadmap

PolicyGPT Enterprise is not a finished production platform. Current limitations are intentionally visible:

  • no cloud deployment
  • no authentication or authorization
  • no tenant isolation
  • synchronous ingestion
  • embedded single-instance Chroma
  • local source storage
  • no malware scanning
  • no managed secrets
  • no managed backups
  • no hosted monitoring
  • no document deletion or reindexing
  • no production usage claim

Additional production work would require TLS termination, retention and governance controls, recovery testing, broader domain validation and formal security review.

The next work is ordered by risk and operational dependency:

  1. authentication, authorization and tenant isolation
  2. object storage and malware scanning
  3. asynchronous ingestion
  4. deletion and reindexing
  5. managed PostgreSQL and backups
  6. telemetry and alerting
  7. hybrid search and reranking
  8. larger human-reviewed evaluation
  9. multi-document comparison
  10. compliance-report workflows
  11. query routing or LangGraph only when justified

Agentic orchestration comes after identity, evaluation, observability and recovery controls—not before them.

What this project demonstrates

I designed and implemented PolicyGPT Enterprise end to end. The project demonstrates production-style RAG architecture, evidence gating, page-level citation provenance, PostgreSQL and vector-store coordination, interpretable confidence diagnostics, safe unsupported and provider-failure fallbacks, versioned evaluation design, request-level observability and Docker Compose deployment engineering.

The strongest engineering result is the explicit system boundary: it is a verified local release profile with inspectable evidence and evaluation—not a commercial SaaS product, a cloud production deployment or proof of real-company adoption.

Inspect the implementation

Evidence, evaluation and release engineering—open for review.

Inspect the source code, evaluation framework, operational documentation and verified local release workflow.

Chintan Patel

Applied AI Engineer · ML · RAG · Full-Stack AI Systems

Privacy