Skip to main content

Query Processing Pipeline

The query processing pipeline is the central path of the search system. Following the retrieve-then-generate paradigm of Lewis et al. 2020, every user query traverses an orchestrated sequence of stages that progressively refine understanding, retrieve relevant information, and generate a grounded, safe response.

This page vs. Context Retrieval Architecture

This page is the end-to-end pipeline map (cache check, intent, retrieval, assembly, generation, quality gate). For a retrieval-focused companion view that numbers only the retrieval stages and goes deeper on the three channels and fusion, see Context Retrieval Architecture, which carries an explicit stage-number mapping back to this page.

Pipeline-level trade-offs​

DecisionChosenAlternatives consideredRejected because
Retrieval shapeHybrid: dense vector search (pgvector), sparse keyword search (BM25) and taxonomy lookupVector-only (@karpukhin2020dpr); BM25-only; a ColBERT late-interaction re-ranker only @khattab2020colbertVector-only loses recall on Dutch medical terms and doctor surnames that keyword search catches by exact match; BM25-only loses recall on cross-language and synonym queries that vectors capture; ColBERT-only requires re-encoding the entire corpus at every model change, which is operationally untenable. ColBERT survives as a feature-flagged re-ranker (ADR-0039), not the primary path.
Result fusionReciprocal Rank Fusion (RRF) with k=60Weighted linear combination of similarity scores; learned-to-rankScore scales differ across vector cosine, BM25 rank and taxonomy priority; weighted fusion needed hand-tuned coefficients that drifted with each embedding change. RRF uses ranks only, so it is stable across model migrations. See ADR-0020.
Intent classificationA language model (standard tier) with schema-validated structured outputA regular-expression or keyword classifier; a small fine-tuned BERT modelRegular expressions miss novel phrasings, especially in Turkish, Arabic or Romanian patient input; a fine-tuned classifier needs labelled corpora that do not exist at pilot scale. The structured-output helper validates the model's answer against a schema, retries on failure and raises a typed fallback error, replacing an earlier unvalidated parsing pattern.
Cross-category contamination preventionIntent-category affinity re-ranking (Stage 5b)A hard per-intent category filter; cross-encoder re-ranking onlyA hard filter excludes correct chunks when the intent is misclassified at a boundary (for example condition information versus treatment or examination information). A cross-encoder is cheap to add but does not address the wheelchair-versus-cardiology category leak observed in a regression: it ranks within the retrieved chunks and cannot rebalance categories. The affinity re-rank multiplies each score by an intent-by-category coefficient, a graded penalty that recovers when intent confidence is low.

Pipeline overview​

Pipeline stages in detail​

Stage 1: Semantic cache check (PostgreSQL + pgvector)​

Latency: 1-30 ms | Purpose: Avoid redundant language-model calls | ADR: ADR-0031

Before invoking any AI model, the pipeline checks the two-tier semantic query cache, stored in PostgreSQL (not Redis). The cache operates on reformulated queries: the intent classifier normalises language, spelling and word order before caching, which maximises hit rates across languages.

TierMechanismLatencyWhat it catches
Tier 1SHA-256 hash of the reformulated query textabout 1 msIdentical reformulations, including queries in other languages that normalise to the same Dutch form
Tier 2Cosine similarity through the HNSW index over 1,536-dimension text-embedding-3-large embeddings (ADR-0048, @openai2024embeddings; @pgvector_docs)about 30 msSemantically equivalent queries worded differently (for example two Dutch phrasings of "which doctors work in orthopedics?")

On a hit, the stored response and citations are returned immediately, skipping all later stages. Entries expire after 1 hour (configurable in the administration settings). See Storage Architecture for details.

Tier 2 safety guards​

Tier 2 uses two protections against cross-topic cache contamination, where structurally similar queries about different medical entities would return the wrong cached answer:

1. Intent filter. Tier 2 only considers cache entries with the same classified intent as the incoming query, so a doctor-lookup answer cannot be returned for a condition question. The filter is applied before similarity ranking.

2. Jaccard keyword guard. Even within one intent, embedding similarity alone is not enough. "Which cardiologists work at the hospital?" and "Who are the orthopedists at the hospital?" have cosine similarity above 0.97 because their sentence structure is identical; only the specialty differs. The guard computes the Jaccard similarity coefficient (intersection over union) of the queries' content words. Content words are tokens of four or more characters after removing Dutch stop words and generic medical terms (such as "artsen", "werken", "afdeling"). If the Jaccard similarity is below 0.5, the hit is rejected.

New queryCached queryContent wordsJaccardVerdict
Which orthopedists at the hospital?Which cardiologists at the hospital?{orthopedics} vs {cardiology}0.00Rejected
How much does parking cost?What does parking at the hospital cost?{parking, cost} vs {parking, cost}1.00Accepted
"borst onderzoek" (breast examination, two words)"borstonderzoek" (one word){borstonderzoek} vs {borstonderzoek}1.00Accepted

This two-layer defence (intent plus Jaccard) ensures Tier 2 hits are both semantically close and topically aligned, without sacrificing cache effectiveness for legitimate reformulations.

Stage 2: Intent classification​

Latency: about 400 ms (combined classify-and-rewrite call when conversation history exists; not yet measured at p95 on the pilot) | Model: standard tier | Purpose: route, guard and detect follow-ups

Intent classification is the most consequential stage. It determines both the retrieval strategy (which data sources to query) and whether the query is safe to process at all. It also detects whether the query is a follow-up to an earlier turn, which affects filtering and boosting. Each query is mapped to one of twelve intent types.

Implementation note. The classifier calls the language model through the project's thin structured-output helper, which validates the response against a schema (intent, entities, confidence, follow-up flag), retries on validation failure and raises a typed error only when the model still cannot satisfy the schema. This helper replaced an agent framework on 2026-05-12 after production telemetry showed the framework added about 720 ms per call without any capability the helper lacks.

Intent routing strategy​

IntentRetrieval strategyRationale
Doctor lookupHYBRIDDoctor entities exist in the taxonomy; vector search is the fallback when specific entities are missing
Department or service lookupHYBRIDDepartment and service data is in the taxonomy, supplemented by vector search for descriptions
Condition informationHYBRIDConditions map to departments through "handles" relationships; vector search retrieves brochure content
Treatment or exam informationHYBRIDTreatments and examinations have "offers" and "performs" relationships; vector search retrieves procedural details
Navigation or practical infoHYBRIDPractical information is mostly textual but benefits from campus and facility context
Booking or contactHYBRIDMay need both contact entities and procedural text
Ambiguous symptom descriptionHYBRIDSymptoms map to conditions (vector) and departments (taxonomy) through alias resolution
UnknownHYBRIDFallback uses both sources for maximum coverage
Medical adviceBLOCKEDNot answered: the user receives a refusal with a link to the relevant validated brochure (see Safety overview)
Off topicBLOCKEDQuery unrelated to the hospital; immediate redirection
Other hospitalBLOCKEDQuery about another hospital; polite refusal with the pilot hospital's contact information
Vague inputBLOCKEDInsufficient input; request for clarification
Hybrid-everywhere strategy

All non-blocked intents default to HYBRID retrieval, which runs vector and taxonomy search sequentially. This reflects the observation that taxonomy context improves response quality even for intents first classified as vector-only (condition information benefits from traversing "handles" relationships, for instance). Vector-only and taxonomy-only strategies remain available for future use, but production maps every safe intent to HYBRID.

Query reformulation: canonical templates​

Every query, whatever its language, is reformulated into a well-formed Dutch search query during intent classification, for three purposes:

  1. Cross-language normalisation: queries in English, Turkish, Romanian and other languages are translated to Dutch clinical language.
  2. Cache effectiveness: consistent reformulations maximise semantic cache hit rates (see ADR-0031).
  3. Retrieval quality: well-formed Dutch queries match the indexed Dutch content more precisely.

To make reformulations deterministic, the classification prompt includes canonical templates, one fixed sentence pattern per intent type, for example "Which doctors work in department X of the hospital?", "What does department X do and what care does it offer?", "How does examination X proceed?" and "Which departments treat symptom X?" (all in Dutch in the actual prompt). The templates enforce two rules: always use the short hospital name, and always use the "department X" form rather than "X-specialist doctors".

Why canonical templates matter

Without templates the model varies vocabulary and structure freely. In one test, "who are the orthopedic doctors?" was reformulated with the hospital's full name and a different sentence shape, which gave only 0.746 cosine similarity to the canonical Dutch equivalent. That defeated the cache and degraded retrieval (4 doctors returned instead of 12). Canonical templates remove this variance.

Stage 3: Query rewriting and follow-up detection​

Latency: about 0 ms extra (combined with intent classification) | Model: standard tier | Purpose: conversational context resolution

When conversation history exists, intent classification and query rewriting run in a single combined model call, which removes a separate rewriting step. Without history, only classification runs (the canonical-template reformulation still applies). Follow-up queries often contain references that are meaningless in isolation; rewriting resolves them:

  • Turn 1: "Welke dokters zijn er bij orthopedie?" (Which doctors are in orthopedics?)
  • Turn 2: "Wanneer heeft hij consultatie?" (When does he have consultation?)
  • Rewritten: "Wanneer heeft de orthopedisch arts consultatie?" (When does the orthopedic doctor have consultation?)

Enhanced history with citation context​

The history passed to the rewrite prompt includes the titles of the sources cited in earlier turns, presented as a "topic" for each turn. Titles are cleaned (extension removed, separators replaced by spaces) to give the model natural topic context for resolving ambiguous references.

Follow-up detection heuristics​

  1. Model detection (primary): when classification succeeds with confidence of at least 0.1, the model's follow-up flag is trusted.
  2. Short-query heuristic (fallback): when the model fails (unknown intent with confidence below 0.1), queries of fewer than six words with existing conversation history are treated as follow-ups. This catches patterns such as "and the costs?" or "which campus?".

Stage 4: Metadata filtering​

Latency: under 5 ms | Purpose: narrow the search scope

The classified intent maps to metadata filters that constrain the search space. For example, a condition-information intent filters for documents in the conditions category, preventing irrelevant administrative content from being retrieved.

Auto-filter bypass for follow-up queries​

When a query is a follow-up, intent-based category filtering is skipped, because follow-up conversations often cross category boundaries: a patient may ask about a doctor and then about preparation for a treatment. Applying the second query's category filter would exclude the doctor-related content from the first turn, which may still matter.

Filtering priority:

  1. Explicit categories in the request always apply.
  2. Follow-up queries skip category filtering.
  3. New queries apply the intent-to-category mapping when automatic filtering is enabled.

Stage 5: Sequential hybrid retrieval​

Latency: about 800 ms | Purpose: gather evidence from several sources

Sequential execution

Vector and taxonomy search run sequentially because the database driver allows only one active operation per session. This adds about 50 ms but guarantees both complete reliably.

Three retrieval mechanisms run in turn, each contributing complementary results:

  • Vector search (pgvector): cosine similarity against 1,536-dimension embeddings (ADR-0048, @openai2024embeddings; the dense retrieval pattern follows @karpukhin2020dpr), returning the top-k most similar chunks.
  • BM25 keyword search (PostgreSQL full-text search): term matching with the query terms joined by OR and ranked by term frequency. OR logic works better than AND for natural-language Dutch queries. It catches exact terms (a doctor surname, a procedure name such as "cardioversie") that vector search may rank lower. See ADR-007.
  • Taxonomy search (PostgreSQL): entity lookups against the taxonomy tables, routed by the entities the intent-classification call extracted (see ADR-0030).

Results are merged with Reciprocal Rank Fusion (RRF) with k=60. For a document at rank r in a result list, the score contribution is 1/(k + r + 1); a document appearing in several lists (vector and keyword) has its contributions summed. Because RRF uses ranks only, it avoids hand-tuned score weights. See ADR-0020. Taxonomy results are placed first in priority order (typed entity results, then vector chunks, then semantic taxonomy results).

Stage 6: Metadata boosting​

Latency: under 5 ms | Purpose: re-rank results by relevance signals

Retrieved results are re-scored with nine metadata boost signals applied multiplicatively. They use enriched document metadata populated during ingestion (see Document Ingestion Pipeline).

#Boost signalMultiplierCondition
1Category matchx1.20The intent's category matches the document's category
2Recencyx1.15Recent content preferred, the document is time-sensitive and under 7 days old
3Section header matchx1.10A query term appears in the chunk's section header
4Entity type matchx1.10The document's entity types overlap the intent's categories
5Campus matchx1.10Query tokens overlap with the document's campus names
6Conversation contextx1.25Follow-ups only: the document was cited in the previous turn
7Content keyword matchx1.05 to x1.40Discriminating query terms (four or more characters) appear in the chunk; per-term increment of +5% (4-5 characters), +10% (6-7) or +20% (8 or more), capped at +40%
8Authority dampeningx authority scoreOnly when the document's authority score is below 1.0; no boost otherwise
9URL tier boostx1.15 / x1.05Tier 1 URL paths x1.15; tier 2 x1.05; tier 3 (default) x1.0

Final score: the similarity multiplied by all applicable multipliers, capped at 1.0.

The conversation-context boost is the strongest single signal. It applies only to follow-ups: document identifiers are taken from the previous turn's citations. When a patient asks "and the costs?", the parking documents cited in the previous turn are prioritised over unrelated cost-related content.

Category-aware authority boosting for navigational queries​

For navigational intents (doctor lookup, department or service lookup, booking or contact, location or directions, practical navigation), the category boost adds an intent-aware authority differential on top of the standard match. It prevents informational brochures from outranking authoritative directory pages when a user is navigating to a department or looking up a doctor.

Document categoryNavigational multiplierCombined with base (x1.20)
Department, Doctor, Contact, Location, Appointmentx1.50 (authority up)x1.80 effective
Brochure, News, Miscellaneousx0.70 (authority down)x0.84 effective (x0.70 if no base match)
All other categoriesx1.00 (no change)x1.20 if base match, x1.00 otherwise

Non-navigational intents are unaffected; only the standard x1.20 category match applies.

Stage 5b: Intent-category affinity re-rank​

Latency: about 2 ms in process | Telemetry: one record per non-cached query, feeding the operations dashboard

Stage 5b runs after the metadata-boost re-scoring and before context assembly. It prevents cross-category contamination: chunks from a wrong-category document outranking correct-category chunks because their similarity score was high in isolation. The motivating case is a regression in which a query about wheelchair access surfaced cardiology brochures, because cardiology chunks had high vector similarity to the word for "wheelchair" through incidental co-occurrence in shared paragraphs, although the user's intent was practical navigation (where clinical-information chunks should be down-weighted).

Algorithm​

Each retrieved chunk is classified into one of six content categories:

CategoryExamples
PracticalVisiting hours, parking, route descriptions, building numbers
AppointmentsBooking instructions, contact numbers, online forms
GeneralNeutral hospital-level descriptions, mission statements
Legal and administrativePatient rights, complaints procedure, identity documents
Clinical informationCondition descriptions, treatment details, recovery guidance
RegulatoryPrivacy policy, billing, insurance, data-subject rights

The classified intent selects a row of category multipliers. For the practical-navigation intent, practical content is boosted (x1.30), appointments slightly (x1.05), general content left unchanged, legal and administrative content reduced (x0.85), and clinical (x0.65) and regulatory (x0.55) content penalised.

Each chunk's score is multiplied by the matching coefficient and clamped to the range 0 to 1; chunks are then re-sorted. Chunks with no readable score pass through to the bottom unchanged. An unknown intent produces a neutral pass-through (multiplier 1.0 for every category), so the re-rank is designed not to make a result list worse than before.

Telemetry​

After the re-rank, the pipeline writes one telemetry record per non-cached query: the classified intent, the dominant category among the top results, the mismatch rate (the fraction of top results whose category is outside the intent's preferred set), the counts behind that rate, and the first 200 characters of the query for operator review. The category mismatch chart on the operations dashboard plots the rate over time per hospital; spikes indicate that retrieval steering needs retuning.

Stage 5c: Synthetic department doctor-list injection​

Latency: about 5 ms (one indexed taxonomy query when triggered)

Stage 5c fires only when all three conditions hold:

  1. The classified intent is a doctor lookup or a department or service lookup.
  2. The query contains a list-signal phrase ("all", "which doctors", "who works", in several languages).
  3. A department or specialty hint can be resolved, either from the entities the classifier extracted or from a pattern match on the rewritten query.

When they hold, the stage queries the taxonomy for all doctors associated with the resolved department, builds a synthetic chunk listing them, and inserts it into the retrieved set before context assembly. This gives the language model the full roster, so the system prompt's "list all members" exception can apply faithfully.

It was introduced as a regression fix after a six-turn voice conversation about dermatologists on 2026-05-09 stalled at the same two names, because vector retrieval surfaced individual doctor pages without the shared department roster. When any condition is unmet (for example a lookup of a single doctor), Stage 5c does nothing and adds no latency.

Stage 6b: Context assembly and citation building​

Latency: about 50 ms | Purpose: expand retrieved snippets into coherent text blocks and build aligned citations

A key insight of retrieval-augmented generation is that what you retrieve is not what the model reads. Retrieved chunks are 350-token fragments; context assembly turns them into coherent reading material. The 8,000-token budget and chunk ordering are informed by Liu et al. 2024, "Lost in the Middle", which showed that language models under-attend to mid-context tokens: the most relevant document stays at the top, low-relevance trailing blocks are dropped first, and critical evidence is not placed in the middle of a long context. See Context Assembly.

  1. Expand: for each retrieved chunk, fetch one adjacent chunk on each side from the same document (one batched query per document).
  2. De-duplicate: strip the roughly 70-token overlap between consecutive chunks.
  3. Group: merge chunks of the same document into coherent blocks in document order.
  4. Budget: cap total context at 8,000 tokens, dropping the lowest-relevance blocks first (@liu2024lostinmiddle).
  5. Build citations from the post-assembly chunk order.
Citation ordering fix

Citations are built after context assembly, not before. Assembly reorders and groups chunks by document; if citations were built from the pre-assembly order, the [1], [2] numbering in the model's answer would not match the citation list shown to the user. The pipeline enforces the order: assemble context first, then build citations.

Stage 7: Response generation​

Latency: about 3,000 ms | Model: standard tier through the direct OpenAI API (both standard and full mode) | Purpose: synthesise a grounded response

The generator receives the ranked results as context and writes a natural-language answer. The prompt enforces strict grounding: every claim must be traceable to a retrieved source. Answers are streamed, giving progressive rendering in the chat interface. Full mode uses the same model as standard mode, with always-on re-ranking and a higher output limit. See LLM Stack.

Stage 8: Hybrid quality evaluation​

Latency: about 600 ms blocking plus asynchronous background work | Purpose: validate response quality

  1. Fast quality gate (about 600 ms, blocking): a weighted average of embedding cosine similarities, 0.7 times the answer-to-context similarity plus 0.3 times the question-to-answer similarity. The blended score must exceed 50% for the response to pass. The threshold was raised from 0.40 to 0.50 on 2026-05-10 after an empirical recalibration.
  2. Background analytics (40-60 s, non-blocking): runs asynchronously after the response is delivered, using DeepEval metrics (faithfulness, answer relevancy) for quality monitoring, with results feeding long-term metrics. Note that the DeepEval grounding scores recorded after mid-May 2026 are not valid, because the judge was silently not running.

Timing breakdown​

The chart below shows a representative query timing. It is not a measured p50 or p95. Stage durations are estimates based on the dominant cost of each stage; per-stage measurements are recorded in the pipeline telemetry and shown on the operations dashboard (see Feedback Dashboard Metrics). Per-stage p50 and p95 values are still "not yet measured" rather than invented.

Performance insight

Total blocking latency is roughly 5.5 seconds in this representative breakdown. Intent classification and rewriting share one model call (about 400 ms). Vector, keyword and taxonomy search run sequentially, adding about 800 ms. The affinity re-rank and conditional doctor-list injection add about 2 ms and at most 5 ms. Context assembly adds about 65 ms. The most expensive step remains response generation (about 3 s), mitigated by streaming. Background analytics run off the critical path and are designed not to affect the user experience. Real p50 and p95 measurements are pending; see the End-to-End Latency Budgets table.

Follow-up suggestion generation​

Latency: about 200 ms (asynchronous, non-blocking) | Model: fast tier | Purpose: guide the user toward relevant next questions

After the response is streamed, the pipeline generates three contextual follow-up questions in Dutch that a patient or visitor would logically ask next. They appear as clickable suggestions below the response, reducing cognitive load and encouraging exploration of the hospital's services.

Why a separate lightweight model?​

Follow-up suggestions are a convenience feature, not a safety-critical stage. A dedicated fast-tier model has three benefits:

CriterionMain modelFollow-up model (fast tier)
CostHigher per input tokenSeveral times cheaper per input token
Latency1-5 secondsabout 200 ms
Output formatFree-form text and reasoningStrict list of three strings
Failure impactCritical (no response)Graceful (empty suggestions)

The follow-up model is configured separately in the administration settings and defaults to the fast tier. This keeps reasoning models, whose internal thinking tokens break structured-output parsing, away from structured-output tasks.

Fault tolerance​

Follow-up generation is wrapped in an error guard. If the model returns unparseable output or the call fails, an empty suggestion list is returned; the response is designed not to be delayed or degraded by suggestion failures.

Error handling​

Each stage fails safe:

  • Cache failure: proceed without the cache (log a warning).
  • Intent classification failure: default to the HYBRID retrieval strategy.
  • Retrieval failure: return partial results from whichever source succeeded.
  • Generation failure: return a polite error message with general navigation links.
  • Evaluation failure: deliver the response but flag it for manual review.

Real-time pipeline visibility​

Every stage emits structured progress data over the streaming connection, so the front end can show technical information during query execution. This supports academic evaluation, where each architectural decision must be demonstrable.

Progress emissions​

StageEmitted data
UnderstandingIntent type, confidence, retrieval strategy, query rewriting details
SearchingDocument count, search method (hybrid or vector-only), keyword match count, canonical-question matches
AnalysingChunks retrieved versus chunks after context expansion
GeneratingProgress percentage
EvaluatingFaithfulness and relevancy percentages, overall score with an A-F grade, quality-gate pass or fail

Administration debug view​

The administration interface renders these emissions as colour-coded badges in the chat interface, with document detail metadata and an analytics reset. It is an internal developer and examiner tool.

Example: what an examiner sees​

During a live query the debug view shows, progressively:

  1. Understanding: a "medical question 92%" badge, HYBRID, and the search method used
  2. Searching: 8 documents, 3 keyword matches, 5 canonical-question matches
  3. Analysing: 8 chunks expanded to 12
  4. Generating: a progress bar filling
  5. Evaluating: overall score 78% (grade B), faithfulness 82%, relevancy 74%

These values are an illustrative example, not a measured result.