System Architecture
This documentation describes a PXL University College "AI Technology Architect" graduation project, authored by SOFT4U BV and the project team. It describes a pilot built for Ziekenhuis Oost-Limburg (ZOL). It is not an official ZOL publication and is not endorsed by ZOL.
This page describes the architecture of a working retrieval-augmented generation (RAG) system. If you are new to the project, start with Core Concepts, and keep the Glossary open for any unfamiliar term.
The system implements retrieval-augmented generation Lewis et al. 2020 over hospital content: instead of letting a language model answer from memory, the system first retrieves relevant passages from the hospital's own pages and brochures, then asks the model to answer using only those passages and to cite them. It has two input channels, a web chat and a voice (telephone) channel, which share the same retrieval backend.
The architecture is layered: each layer has a distinct responsibility and talks to its neighbours through well-defined interfaces. This makes substitutions tractable. When the embedding model was migrated from BGE-M3 to OpenAI text-embedding-3-large (see ADR-0048, @openai2024embeddings), the change touched a single layer without cascading through retrieval, generation or evaluation.
Components at a glance
| Component | Responsibility | Technology |
|---|---|---|
| Chat front end | Conversational web interface; shows progress while an answer is produced and streams the answer as it is written | React, TypeScript |
| Application server | Entry point for all requests: authentication, abuse protection, request logging, orchestration of the steps below | Python, FastAPI |
| Safety layer | Classifies every question before retrieval; refuses medical-advice questions; checks the generated answer afterwards | Language-model classifiers plus rule-based checks |
| Retrieval pipeline | Rewrites the question using conversation context, searches by meaning and by keyword, looks up structured entities (departments, specialties), re-ranks and assembles context | Python services |
| Knowledge store | Document chunks with embeddings, structured hospital taxonomy, query caches | PostgreSQL with pgvector |
| Supporting stores | Short-lived state (sessions, rate limits, optional intent cache) and raw document storage | Redis, MinIO |
| Identity provider | Sign-in and role-based access for staff users | Keycloak (OpenID Connect) |
| Voice channel | Telephone calls in four languages: speech-to-text, an agentic language-model orchestrator with tool-grounded retrieval, text-to-speech | Twilio, LiveKit, Deepgram, ElevenLabs |
| Language-model provider | Answer generation, classification and embeddings | OpenAI |
| Monitoring | Structured logs, per-stage timing, quality and safety dashboards | structlog, Prometheus-style metrics |
Architectural trade-offs
Three foundational decisions define the system shape; each is captured in an Architecture Decision Record (ADR) with the alternatives that were considered and rejected.
| Decision | Chosen | Alternatives considered | Rejected because |
|---|---|---|---|
| Vector store | PostgreSQL + pgvector (@pgvector_docs) | Dedicated vector databases (Pinecone, Weaviate, Qdrant); in-process FAISS (@johnson2017faiss) | A dedicated vector database adds a second operational system, a separate access-control plane and a synchronisation surface against the relational tenant and taxonomy data. FAISS lacks transactional guarantees and persistent storage at this project's scale (about ten thousand chunks). pgvector keeps embeddings, taxonomy and tenant metadata in one transactional database with one backup story. |
| Knowledge representation | Structured taxonomy tables in PostgreSQL (see the Neo4j removal decision in the ADR register; it supersedes the earlier Neo4j adoption) | A Neo4j graph database with graph algorithms (@neo4j_gds_manual); embedding graph structure into chunk text | Neo4j was removed. It added an operational service for queries that were already expressible as joins over typed entity tables, and its graph algorithms (PageRank, community detection) were never load-bearing in retrieval. Embedding the graph into chunks lost the structured lookup used for doctor, department and specialty questions. |
| Language-model call boundary | A thin in-house helper over the raw OpenAI client that validates structured output and retries | A Pydantic AI agent layer (@pydantic_ai_docs); unvalidated JSON parsing; LangChain wrappers | The agent layer was adopted on 2026-05-09 across eight call sites and removed on 2026-05-12 after production telemetry showed it added roughly 720 ms per call. The thin helper keeps schema validation and retries without that latency cost. |
Further per-decision rationale lives in each ADR; this page summarises them so a reader can orient before reading the deeper component pages.
Architecture layers
The diagram shows the web chat channel. The voice channel joins at the pipeline orchestrator, adds upstream stages (telephone gateway, real-time audio room, speech-to-text and text-to-speech services) and a downstream answer-shaping step that removes inline citation markers and keeps spoken answers short. See Voice Architecture for the voice-specific sequence. OpenRouter is a configurable alternative language-model route but is not the default; see LLM Stack.
Layer responsibilities
Chat front end
A React + TypeScript single-page application provides the conversational interface. Questions are sent over a streaming connection, which lets the interface show real-time progress as the question moves through the pipeline ("Understanding your question...", "Searching knowledge base...", "Generating response...") and display the answer as it is written.
Application server
FastAPI serves as the entry point, chosen for native asynchronous support, automatic API documentation and schema-based request validation. Security is enforced before any business logic runs:
| Control | Purpose |
|---|---|
| Identity verification | Staff sign in through an external identity provider (Keycloak, OpenID Connect) and requests carry signed tokens |
| Cross-site request forgery protection | Prevents forged requests from other websites |
| Rate limiting | Abuse prevention, with stricter limits on sign-in than on queries |
| Cross-origin policy | Configured per environment |
| Structured request logging | JSON logs in production, readable console output in development |
| Graceful shutdown | In-flight requests are allowed to finish; new requests receive a "try again" response while the server stops |
Safety layer
The safety layer implements the safety-first principle. Every question is classified for intent before any retrieval or generation occurs. Questions identified as requests for medical advice (dosing, self-medication, diagnosis, treatment choice) are not answered; the user receives a refusal with a link to the relevant validated hospital brochure (see Safety overview). After an answer is generated, a second check validates it, and a quality gate checks that the answer meets a minimum confidence threshold.
The layer operates on a deny-by-default model: a question must pass each safety checkpoint to receive an answer, and any single checkpoint can halt the pipeline and return a safe fallback message. The target is zero medical-advice incidents; the design history, including a failure in June 2026, is documented in the Safety overview.
Retrieval pipeline and generation
The pipeline orchestrator coordinates the retrieve-then-generate sequence established by Lewis et al. 2020: rewriting the question using conversation context, semantic (vector), keyword (BM25) and taxonomy retrieval, a re-ranking step that demotes passages from a category that does not fit the classified intent, answer generation with source grounding, and a hybrid quality evaluation. Each service is independently testable and replaceable.
Intent-category re-ranking runs between retrieval and context assembly. It multiplies each passage's relevance score by a coefficient reflecting how well the passage's content category matches the classified intent, so that, for example, a wheelchair-related passage does not outrank a cardiology passage for a cardiology question. The mechanism is hospital-agnostic: it reads passage text and intent class only, never hospital-specific facts. See Query Pipeline for the algorithm and rationale.
Language-model calls for classification, decomposition, feedback analysis and evaluation all go through one thin helper that enforces schema-valid structured output, retries on validation failure and raises a typed fallback only when the model still cannot satisfy the schema.
Knowledge store
| Store | Technology | Purpose |
|---|---|---|
| Vector store | PostgreSQL + pgvector | Semantic similarity search over document chunks |
| Taxonomy | PostgreSQL | Structured entities (departments, specialties, doctors) and their relationships; replaces the former graph database |
| Semantic query cache | PostgreSQL + pgvector | Two-tier result cache (exact match and embedding similarity), see ADR-0031 |
| Intent classification cache | Memory or Redis | Caches intent results per hospital, question and language, skipping a slow language-model call on repeat questions. See ADR-0054 |
| Sessions and rate limits | Redis | Session management, rate limiting, token revocation |
| Object storage | MinIO | Raw document storage (markdown, HTML) |
External services
The system uses a single external language-model provider. OpenAI supplies the language models (a smaller model for classification, entity extraction, evaluation and canonical questions; a larger one for generation in full mode) and the embeddings (text-embedding-3-large, per ADR-0048).
The configuration allows a local model runtime (Ollama) as a last-resort fallback. On the pilot it is not deployed and the fallback path has never been validated end to end; only mock unit tests exist. Treat it as vestigial until it is deployed and tested, or removed.
Technology rationale
- Right tool for the right job: pgvector for vectors (@pgvector_docs), PostgreSQL taxonomy tables for entity relationships, Redis for ephemeral state.
- Cloud-first: embeddings and language-model calls use the OpenAI API (single provider in production).
- Standards-based: FastAPI (OpenAPI), PostgreSQL (SQL) and WebSocket (RFC 6455) support interoperability and long-term maintainability.
Deployment architecture
Infrastructure components run as Docker containers orchestrated with Docker Compose, which gives reproducible local development and straightforward deployment. PostgreSQL serves as both the vector store and the entity taxonomy store. Keycloak provides OIDC-based authentication with signed tokens.
Channels: web and voice
The system serves two production input channels that share the retrieval backend but diverge at the language-model call:
| Channel | Entry path | Response shape |
|---|---|---|
| Web chat | Streaming connection from the React interface | Streamed Markdown with a citation list |
| Voice (telephony) | Telephone network, SIP trunk, real-time audio room, voice agent worker | Text-to-speech (@elevenlabs_multilingual_v2); shaped for spoken delivery, with no inline citation markers |
The channel is chosen at request time from a field on the request. The voice path uses a single agentic orchestrator with tool-grounded retrieval per ADR-0051. A deterministic "thin" pipeline (rule-based pre-filter, then a frequently-asked-questions tool, then RAG as fallback; ADR-0049) was in production from 2026-05-02 and was superseded by ADR-0051 on 2026-05-07 after pilot calls showed it was too rigid for language switching and unintelligible input; an earlier eight-stage orchestrator had been removed on 2026-05-02 because its cache-hit rate did not justify its complexity. Speech-to-text uses Deepgram Nova-3 with the language locked at the first utterance per ADR-0052.
Both channels share the same retrieval pipeline, the same intent re-ranking, the same safety and disclaimer policy (the medical-advice barrier sits before retrieval on both) and the same evaluation surface. What differs is the answer-shaping step on voice, which strips Markdown, fits the response to a target length for speech latency, and carries citation context in separate metadata instead of inline markers.
Multi-tenancy
The system supports per-hospital configuration stored in the database and loaded at runtime: crawl rules, content-extraction rules, URL patterns and the identity used in prompts. Adding a hospital does not require code changes. Two configuration planes coexist: a web/RAG plane (crawl behaviour, high-value extraction targets, parameterised prompt identity) and a voice plane (per-hospital frequently asked questions, speech-recognition recovery rules and answer renderers). All taxonomy data, documents and cache keys are scoped by hospital. See Multi-Tenancy for the full design.
Monitoring
Structured logging
The backend uses structlog with environment-aware output: coloured console output in development and one JSON object per log entry in production, for machine parsing. Entries carry request correlation identifiers, timestamps and structured metadata, and request/response pairs are logged with timing.
Health checks
A public liveness check confirms the database, cache and object store respond. A deeper readiness check additionally reports the state of the language-model circuit breaker (closed, open or half-open), so a language-model outage can be detected automatically without authenticated access.
Graceful shutdown
On a termination signal the application sets a shutdown flag, answers new requests with HTTP 503 and a retry hint, lets in-flight requests finish within a configured timeout (recommended 30 seconds), and keeps the health checks available for orchestrator polling.
End-to-end latency budgets
Latency depends on cache state and channel. Figures below are for the web channel.
| Stage | Web p50 | Web p95 | Note |
|---|---|---|---|
| Cache hit (exact match) | about 1 ms | about 3 ms | Measured from pipeline telemetry |
| Cache hit (embedding similarity) | about 30 ms | not yet measured | Characteristic of the pgvector index |
| Intent classification | about 2.4 s (language-model dominated) | not yet measured | Dropped by about 720 ms per call after the agent layer was removed |
| Hybrid retrieval | not yet measured | not yet measured | Steps run sequentially (single database session constraint) |
| Context assembly | about 50 ms | not yet measured | Includes neighbouring-chunk expansion and de-duplication |
| Response generation (streaming) | about 3 s | not yet measured | Dominant cost on a cache miss; mitigated by streaming |
| Fast quality gate | about 600 ms | not yet measured | Embedding-similarity blend |
| Background analytics (DeepEval) | 40-60 s | n/a | Non-blocking, runs after the response is delivered. Note: DeepEval grounding scores after mid-May 2026 are not valid because the judge was silently not running |
Each stage records its duration per conversation, and the operations dashboard renders percentiles from that data (see Feedback Dashboard Metrics). Missing p95 values are left as "not yet measured" rather than estimated; treat the 5.5-second blocking total in Query Pipeline as a working estimate, not a contract.
Data-protection support
An authenticated administrative erasure function exists to honour GDPR Article 17 requests: it deletes a user's conversations, messages, analytics and audit records, and returns a summary of what was removed.
Prompt versioning
All prompts carry a version identifier that is logged with every evaluation result, so prompt changes can be correlated with quality regressions.
Architectural changes since 2026-04-09
| Date | Change |
|---|---|
| 2026-04-22 | Nightly automatic ingestion went live on the pilot, with an audit record per run; see Document Ingestion. |
| 2026-04-30 | Embedding model migrated from BGE-M3 to OpenAI text-embedding-3-large (ADR-0048) |
| 2026-05-02 | Earlier eight-stage voice orchestrator removed; deterministic thin pipeline became production (ADR-0049) |
| 2026-05-07 | Thin voice pipeline superseded by the agentic-only orchestrator (ADR-0051) |
| 2026-03-07 / 2026-05-02 | Neo4j graph database removed (primary removal 2026-03-07, cleanup completed 2026-05-02); entity relationships consolidated into PostgreSQL taxonomy tables (ADR-0053) |
| 2026-05-04 | Voice per-hospital overlay system shipped (FAQ, speech-recovery rules, answer renderers); see Multi-Tenancy |
| 2026-05-09 | Intent-category re-ranking productised, with telemetry for the operations dashboard; see Query Pipeline |
| 2026-05-09 to 2026-05-12 | Agent layer adopted then removed after telemetry showed +720 ms per call; replaced by the thin helper |
| 2026-05-22 | LLM-first agentic voice pipeline accepted (native streaming with tools, one call per tool decision) |
| 2026-05-23 | Voice quality refit: no repeated clarifications, deterministic temperature, expanded speech-recovery vocabulary, session rate limit, voice trace/replay/SLO tooling; see Voice Architecture |