925 Worker LTD

RAG System for Clinics and Patient Data Analysis, CRM and Scheduling Integration

Retrieval-augmented clinical question answering: every response is generated from retrieved literature, cites its sources, and is fact-checked against that same evidence before it reaches a clinician.

Role
AI / RAG Engineer / Knowledge Base Architect
Period
Nov 2024–Jan 2026

01 Problem What was actually hard

A language model that invents a dose is worse than no model at all. The design premise was therefore that the model is never the source of truth — the retrieved literature is, and the model's only job is to read it back accurately with citations attached. That has to happen inside a couple of seconds, over a corpus that spans drug interactions, comorbidities and rare presentations, with an audit trail good enough for a regulator.

02 Data Sourcing and preparation

Ingested 50,000+ clinical documents — PubMed abstracts, clinical summaries, ICD-10 codes, drug-interaction databases and society guidelines. Chunked on semantic boundaries at a maximum of 512 tokens with 50-token overlap, so a chunk never splits a dosing statement in half, giving roughly 125,000 chunks. Embedded with all-MiniLM-L6-v2 and indexed in Chroma. Built a 500-query evaluation set with expert-written answers and source citations, two reviewers per query, and used it to measure both retrieval recall and citation fidelity.

03 Models Evaluated, kept, cut

6 evaluated 4 kept 2 cut

Kept 4

  • Sentence Transformers (MiniLM)

    384-dim embeddings; retrieval in well under 100ms over the full corpus

  • Chroma

    Persistent vector store with no operational overhead

  • Llama 3.1 8B Instruct

    Fast path generator, open-weight, constrained to cite only retrieved evidence

  • GPT-4 Turbo

    Reserved for low-confidence queries and used as an independent fact-checker

Cut 2

  • BM25 keyword search

    Alone it misses medical synonyms and abbreviations; retained only as a hybrid recall booster

  • Pinecone

    Operational overhead not justified against Chroma at this corpus size

04 Architecture How it fits together

The query is embedded, Chroma returns the top-k passages, and the prompt handed to the generator contains those passages plus an instruction to answer only from them and to cite them. A separate fact-check pass asks whether the generated answer is actually entailed by the retrieved evidence — deliberately a different model from the one that wrote the answer, so it is not grading its own work. Below a confidence threshold, or on a failed fact-check, the response is routed to physician review instead of being shown as an answer. Common queries and their embeddings are cached in Redis, and cached answers are invalidated when the underlying guideline changes.

Architecture flow: Clinical question then Embed then Vector search then Generate with citations then Independent fact-check then Answer + sources 01 Clinical question 02 Embed MiniLM, 384-dim 03 Vector search top-k passages from Chroma 04 Generate with citations Llama 3.1 8B, answer constrained to retrieved evidence Physician review queue 05 Independent fact-check separate model checks entailment 06 Answer + sources

05 Production Deployment and operation

AWS Lambda with RDS behind React and iOS clients. Domain reviewers audit a weekly sample. Monitoring covers latency percentiles, cache hit ratio and an automatic hallucination flag for any response lacking citations or contradicting its evidence. Every query and response is written to an audit log. The system is positioned as decision support requiring physician review, never as a diagnostic device; no patient data is stored and transport is encrypted.

06 Deep dive The long version, in full

Problem

Medicine is unforgiving of errors. An LLM that hallucinates could recommend a contra-indicated drug, miss a critical drug interaction, or misstate a dosing protocol. Yet LLMs will hallucinate if trained only on general web text; medical knowledge requires both breadth (rare conditions) and precision (exact dosing).

The approach: Retrieval-Augmented Generation (RAG). Instead of asking the LLM to generate from memory, we:

  1. Retrieve relevant clinical evidence first
  2. Show the LLM the evidence (+ prompt it to cite sources)
  3. Have it generate grounded responses
  4. Fact-check the response against retrieved evidence

This dramatically reduces hallucinations and forces source attribution (critical for liability).

Data Preparation

We ingested diverse clinical sources:

  • PubMed abstracts (8M total; selected 12,000 relevant to common queries)
  • UpToDate articles (3,000 clinical summaries)
  • ICD-10 disease codes (15,000 conditions + descriptions)
  • Drug databases (20,000 medications + interactions from FDA, WHO)
  • Clinical guidelines (AHA, ACC, ADA, ACS recommendations)

Chunking strategy:

  • Semantic boundaries: split at sentence/paragraph level, not mid-concept
  • Max 512 tokens per chunk (leaves room in LLM context window for prompt + response)
  • Overlap: 50-token overlap between chunks (context continuity)
  • Result: 125,000 chunks, avg. 380 tokens each

Embeddings:

  • Model: Sentence Transformers (all-MiniLM-L6-v2), 384-dim vectors
  • Storage: Chroma (in-memory + persistent), with FAISS indexing for fast retrieval
  • Retrieval time: <100ms for top-5 similar documents

Evaluation set:

  • 500 medical queries covering common conditions, drug interactions, procedural questions
  • Ground-truth answers: written by medical experts (2 reviewers per query)
  • Source citations: each answer tagged with relevant PubMed/guideline references
  • Validation: automatic BLEU score vs expert answers; manual review for edge cases

Models Evaluated

Component Model Result Rationale
Embeddings Sentence Transformers (MiniLM) Kept Fast (10ms/query), medical domain-aware, small model (22M params)
Retrieval Chroma + FAISS Kept Sub-100ms retrieval, easy deployment, no external deps
Generation (fast path) Llama 3.1 8B Kept 80ms inference, 95% accuracy, open-weight
Generation (hard cases) GPT-4 Turbo Kept 98% accuracy, reserved for low-confidence queries
Fact-checking GPT-4 (separate) Kept Validates if response matches retrieved evidence; catches hallucinations
Vector DB Pinecone (alt) Cut Operational overhead; Chroma sufficient + cheaper
Keyword search BM25 Cut Poor for medical queries (synonyms, abbreviations); semantic search necessary
Quantization int8 (Llama) Kept 40% smaller model, minimal accuracy loss

Architecture

Request flow:

User: "Drug interactions with warfarin + ibuprofen?"
  v
1. Embed query (Sentence Transformers, <10ms)
2. Vector search (Chroma, top-5 documents, <100ms)
   Retrieved: PubMed abstract on warfarin-NSAID interactions,
              FDA warning on GI bleed risk, drug interaction database
  v
3. Build LLM prompt:
   "Evidence: [retrieved docs...] \n Question: [user query]\n Answer:"
  v
4. Generate response (Llama 3.1 8B, <80ms)
   Response: "Warfarin + ibuprofen has significant interaction risk (GI bleed, INR elevation).
              Recommend acetaminophen instead. Source: [PubMed:123456]"
  v
5. Fact-check (async, GPT-4):
   "Does response match retrieved evidence?" -> Yes / No / Partial
  v
6. If confidence < 70% or fact-check flags issue:
   -> Escalate to physician review
   -> User sees: "High-confidence AI response" vs "Requires physician review"

Caching:

  • Query cache (Redis): common questions cached with TTL 5h
  • Embedding cache: pre-computed for 5,000 frequent queries
  • Response versioning: track when clinical guidelines change; invalidate stale cached answers

Safety layers:

  • Confidence scoring: LLM outputs confidence; low-confidence answers routed to physician
  • Fact-check failure: if GPT-4 fact-check says “hallucinated,” response flagged for review
  • Source attribution: user can click sources to read full documents
  • Audit log: every query + response stored (PostgreSQL) for regulatory review

Production & Scale

Timeline:

  • Nov 2024: System deployed to beta (100 users, medical staff)
  • Dec 2024: Scaled to 1,000 users; integrated iOS app
  • Jan 2026: 12,000+ queries/month; 99.2% uptime

Metrics:

  • Factual accuracy: 95% (Llama) / 98% (GPT-4)
  • Hallucination rate: 2.1% detected by fact-check model
  • Average latency: <2s (retrieval + generation + fact-check)
  • Physician review rate: 3.2% (only edge cases + low confidence)
  • User satisfaction: 4.7/5 (cite: “responses are evidence-based and helpful”)

Monitoring:

  • CloudWatch: latency percentiles, error rates, embedding cache hit ratio
  • Custom: hallucination detection (automatic flag if response lacks citations or contradicts evidence)
  • Weekly review: domain experts audit 5% sample of responses

Regulatory:

  • FDA classification: decision support tool (not diagnostic)
  • HIPAA compliance: no patient data stored; encrypted transit; audit trail
  • Liability: clear disclaimers (“consult physician; not a substitute for medical advice”)

Cost structure:

  • Infrastructure: $800/month (Lambda + RDS + cache)
  • LLM inference: $0.02 per Llama query; $0.20 per GPT-4 fact-check
  • Data: PubMed/UpToDate subscriptions amortized across users
  • Per-user cost: ~$2/month (at 12k queries/month)

Challenges & lessons:

  1. Retrieval relevance: Initial vector DB had low recall (missing relevant docs)
    • Solution: Multi-step retrieval (BM25 + semantic) improved recall from 65% -> 92%
  2. Fact-check cost: GPT-4 for every query was expensive
    • Solution: Only fact-check low-confidence answers (confidence < 80%); saves 70% cost
  3. Citation accuracy: LLM sometimes cited documents that weren’t actually used
    • Solution: Constrain LLM to cite only from retrieved evidence; enforce in prompt

Result: A medical Q&A system with 95% factual accuracy, sub-2s latency, and transparent sourcing. Physicians can trust the system for decision support because every answer is grounded in clinical evidence.

corpus indexed
125,000 chunks from 50,000+ clinical documents
end-to-end latency
under 2s including retrieval and generation

Stack

  1. Models & inference What does the thinking
    • Llama 3.1 8B Instruct
    • GPT-4 Turbo (fact-check path)
    • Sentence Transformers (all-MiniLM-L6-v2)
  2. Runtime & services What holds the connection open
    • Python (FastAPI, asyncio)
  3. Data & state What is remembered
    • Chroma (vector database)
    • Redis
    • PostgreSQL (audit log)
  4. Cloud & delivery What it runs on
    • AWS (Lambda, RDS, CloudWatch)
  5. Interfaces & integrations What people and other systems touch
    • React / iOS