HomeCase studiesContinuous LLM Evaluation, Hallucination Auditing, and Policy...

Case study · Zurich, Switzerland

Continuous LLM Evaluation, Hallucination Auditing, and Policy Gate Platform

Model Risk, Hallucination & Policy Audits

Regulated enterprises shipping generative AI features face mounting exposure when subtle prompt edits or foundation model upgrades quietly introduce hallucinations, PII leaks, or policy violations in production. We built an AI governance and evaluation platform powered by Python, FastAPI, and PostgreSQL. The system embeds deterministic PII/policy scanners, CI/CD regression evaluation suites, and claim-level faithfulness audits into a unified risk ledger so engineering and compliance teams govern model behavior with reproducible evidence.

Industry
Model Risk, Hallucination & Policy Audits
Solution
An enterprise AI governance, continuous evaluation, and policy auditing platform engineered with Python, FastAPI, and PostgreSQL for CI/CD release gates and production trace inspection.
Platforms
Web & API
Stack
Python · FastAPI · PostgreSQL · OpenTelemetry · Redis · Docker
Location
Zurich, Switzerland · delivered remotely
Role
Engineering, with the team behind for mobile and QA

Delivered remotely for a business based in Zurich, Switzerland. Names withheld by agreement.

Project Overview

Deploying generative AI inside financial, healthcare, or regulated enterprise workflows introduces an uncomfortable governance gap: traditional unit tests verify code syntax, yet minor prompt tweaks, vector index updates, or silent provider model weights shifts can abruptly trigger ungrounded claims, biased refusals, or leaked customer data. Without systematic measurement, teams discover regressions only when risk officers or end users complain.

We architected and delivered an AI governance and continuous evaluation platform anchored by Python, FastAPI, and PostgreSQL. The platform bridges developer CI/CD pipelines and enterprise risk compliance by automating pre-release regression suites, inline policy guardrails, and post-hoc hallucination auditing across every deployed model and prompt revision.

Why Model Governance Breaks in Production

Organizations scaling LLM applications beyond internal pilots confront recurring operational blind spots:

  • Silent behavioral drift: Foundation model updates and retrieval-pipeline changes alter output tone, refusal behavior, and citation accuracy without raising any HTTP errors.
  • Unreliable "vibe-check" QA: Manually spot-checking a handful of prompts before release fails to catch subtle edge-case hallucinations across multilingual inputs or complex policy rules.
  • Auditability deficits: Model risk committees require verifiable evidence showing which dataset, prompt version, and guardrail thresholds approved a system for production—information scattered across notebooks and chat logs.
  • Latency vs. safety tension: Running heavy LLM-as-judge checks inline on every user turn adds unacceptable wait times, yet skipping runtime inspection altogether leaves PII leakage and prompt injection unmitigated.

Architectural Strategy

We divided governance into two coordinated planes orchestrated by Python and FastAPI: a fast deterministic runtime gate and an asynchronous deep-evaluation pipeline, both anchored to an immutable PostgreSQL audit ledger.

At runtime, FastAPI evaluates lightweight deterministic policies—PII entity detection, toxicity boundaries, schema compliance, and jailbreak patterns—using cached rule bundles in Redis. Simultaneously, OpenTelemetry exporters stream production prompts, retrieved RAG chunks, and completions asynchronously to Python worker pools inside isolated Docker containers. Those workers compute claim-level faithfulness, answer relevance, and policy drift scores, storing structured evidence back into PostgreSQL alongside CI/CD release gates.

Core Capabilities

  • CI/CD Prompt & Model Release Gates: Triggers versioned golden dataset evaluations via FastAPI on every pull request, blocking promotion automatically when faithfulness, safety, or format metrics regress.
  • Claim-Level Hallucination Auditing: Breaks model responses into atomic statements verified against retrieved source chunks, highlighting exact ungrounded spans for engineers and auditors.
  • Inline PII & Policy Guardrails: Screens inputs and outputs at low latency for sensitive identifiers, restricted financial or medical advice, and adversarial prompt injections.
  • Immutable Model Risk Ledger: Links every production trace in PostgreSQL to exact prompt hashes, model endpoints, guardrail revisions, and risk-officer sign-offs.
  • Human Calibration & Adjudication: Routes low-confidence or disputed traces into a React review queue where domain experts label edge cases that automatically expand regression datasets.

Technical Architecture

Application services emit structured LLM telemetry over OpenTelemetry to a FastAPI ingestion gateway—or invoke FastAPI directly as a low-latency policy proxy. Redis holds compiled deterministic rule tables and dispatches asynchronous trace bundles to Docker-isolated Python scoring workers. Workers execute hybrid evaluators (NER/regex classifiers, deterministic schema checks, and calibrated judge models), persisting versioned scores, failure spans, and lineage links into PostgreSQL. A React governance console queries PostgreSQL views to render compliance scorecards, regression diffs, and exportable audit packages.

Flow: LLM Apps & CI/CD Pipelines → FastAPI Guardrail & Eval Gateway (Redis Rule Cache) → OpenTelemetry Trace Stream → Dockerized Python Scoring Workers → PostgreSQL Immutable Governance Ledger → React Risk & Audit Console

Running heavy scoring suites inside ephemeral Docker workers keeps evaluation dependencies reproducible while protecting the low-latency FastAPI proxy from CPU spikes.

Technology Stack

Category Technology detail
Evaluation & Policy API FastAPI asynchronous service orchestrating guardrail checks and CI/CD eval runs
Scoring & Audit Workers Python pipelines running deterministic regex/NER detectors and claim-grounding scorers
Governance Ledger PostgreSQL storing versioned prompt registries, dataset baselines, and immutable audit trails
Trace Ingestion OpenTelemetry collectors capturing production prompts, retrieved chunks, and model outputs
Low-Latency Policy Cache Redis caching compiled guardrail rules, deduplicated trace hashes, and eval job queues
Isolated Eval Sandboxes Docker containers executing reproducible benchmark suites and custom Python assertions
Risk & Audit Console React interface displaying regression diffs, faithfulness heatmaps, and compliance exports
CI/CD Integration Signed webhook and CLI gates blocking prompt or model promotions on threshold failures

Engineering Trade-offs & Solutions

Engineering Challenge Solution & Trade-off
Avoiding unacceptable user latency while performing thorough hallucination audits Separated fast deterministic PII/policy scans (inline via FastAPI/Redis) from multi-step RAG faithfulness judges (asynchronous over sampled OpenTelemetry traces); protects chat responsiveness while maintaining continuous oversight.
Ensuring LLM-as-judge evaluations produce repeatable results across releases Pinned deterministic judge prompts, temperature-zero configs, and human-labeled calibration anchors inside versioned Docker evaluator images; adds maintenance overhead when upgrading judges while preserving longitudinal trend integrity.
Preventing governance telemetry from becoming an unencrypted PII liability Applied deterministic NER and regex masking in FastAPI prior to PostgreSQL persistence and separated raw trace retention TTLs from anonymized aggregate metrics; limits forensic raw-text replay after retention expiry in exchange for strict privacy compliance.
Keeping CI/CD evaluation suites fast enough for active pull-request workflows Partitioned datasets into fast PR smoke tiers (high-risk adversarial and core policy tests) and comprehensive nightly regression sweeps; gives developers rapid merge feedback without sacrificing deep audit coverage.

Security & Reliability

A governance platform sits at the intersection of sensitive user prompts, proprietary system instructions, and compliance records. FastAPI enforces strict RBAC and tenant partitioning on every dataset, prompt registry, and audit export, isolating customer traces logically via PostgreSQL row-level security.

Evaluation workers execute custom Python assertion scripts inside non-privileged, network-restricted Docker containers so untrusted evaluation definitions cannot probe internal infrastructure. To guarantee audit integrity, signed evaluation reports and model sign-off records in PostgreSQL are append-only, preserving historical compliance baselines even when prompt templates evolve.

Performance & Scale

Production AI traffic fluctuates sharply across business hours and batch ingestion cycles. FastAPI utilizes asynchronous I/O and Redis deduplication hashes so identical system prompts and repeated golden test cases reuse cached guardrail verdicts without redundant compute.

Asynchronous scoring workers scale horizontally off Redis queues, prioritizing CI/CD release-blocking evaluations ahead of background production trace sampling. In PostgreSQL, time-partitioned trace tables and materialized compliance rollups ensure the React risk console loads multi-week drift trendlines and audit evidence packs swiftly.

Operational Outcomes

Consolidating fragmented spreadsheets, ad-hoc test scripts, and manual risk reviews into a Python, FastAPI, and PostgreSQL governance engine improved both release velocity and compliance confidence:

  • Evidence-backed release confidence: Engineering teams merge prompt and retrieval updates with automated pass/fail regression diffs rather than guessing impact.
  • Proactive hallucination containment: Claim-level grounding audits pinpoint failing retrieval chunks or weak prompt instructions before systemic errors escalate.
  • Streamlined regulatory audits: Risk officers generate reproducible lineage reports linking production behavior to versioned test suites and policy sign-offs in minutes.
  • Continuous dataset maturity: Production anomalies triaged by reviewers convert directly into permanent regression test cases, steadily hardening system reliability.

01 — Questions

asked about this kind of project

How does the platform distinguish genuine RAG hallucinations from acceptable paraphrasing?

Scoring workers decompose generated answers into atomic factual claims and evaluate each claim strictly against retrieved source chunks using calibrated NLI and judge ensembles, pinpointing exact unsupported assertions rather than relying on opaque overall scores.

Can FastAPI run compliance checks synchronously without hurting live chatbot latency?

Fast deterministic guardrails—PII entity redaction, prohibited-topic regex/classifiers, and prompt-injection heuristics—run inline within tight latency budgets backed by Redis rule caches, while heavier LLM-as-judge faithfulness audits run asynchronously over sampled production traces.

Why store prompt versions, retrieved context, and evaluation scores in PostgreSQL?

Regulated model risk reviews require immutable, queryable lineage linking every production answer to its exact prompt template, model weight identifier, guardrail version, and test-suite sign-off—relational integrity in PostgreSQL makes audit exports reproducible.

How do teams prevent judge-model drift from skewing historical regression comparisons?

Evaluation suites pin judge models, temperature zero settings, and calibrated golden anchor datasets inside versioned Docker runner images, validating judge consistency against human-labeled calibration sets before adopting new scoring versions.

How are sensitive customer inputs protected inside the governance and telemetry store?

FastAPI redacts or tokenizes PII fields at ingestion before writing traces to PostgreSQL, applies strict tenant-scoped access controls, and enforces configurable retention windows so compliance auditing never creates an unguarded PII shadow lake.

How does the platform integrate with existing developer workflows rather than becoming an ivory-tower portal?

Teams commit prompt templates and golden test cases in Git; CI pipelines trigger the FastAPI evaluation gate automatically on pull requests, posting side-by-side metric regressions directly onto developer PR comments.

03 — Similar project?

describe what is different about yours

Build yours.

Tell me what exists, what you need and the deadline. Fixed price for a defined scope, or $55/day (8–9 hours work) with a written plan first.

Solitaire Corporate Park, Makarba, Ahmedabad, Gujarat 380015, India · IST (UTC+5:30) · --:-- IST · Mon–Fri 09:00–18:00 IST · US & EU overlap daily

No newsletter, no CRM. Just a reply.