RAG
LangGraph
Medical AI
Python
Streamlit
Hybrid Architecture

Building a RAG-Powered Medical Web App: How I Engineered an AI Prescription Validator

December 9, 2025
8 min read
By Mohamed Fakhry, M.B.B.Ch.
Building a RAG-Powered Medical Web App: How I Engineered an AI Prescription Validator

I wasn’t meant to be coding enterprise workflows. By all accounts, I should be diagnosing patients.

My name is Mohamed Fakhry, and my career has been anything but predictable. I grew up in the glow of CRT monitors and Windows 98, tinkering with Access databases, Visual Basic forms, and FrontPage sites while imagining a future somewhere between Bill Gates and Nabil Farouk’s science fiction worlds. But in Egypt, ambition often bends to family expectation, so I traded my early fascination with code for a medical coat at Kasr Al-Ainy.

Inside, the coder never died. I spent years teaching digital marketing at the very college I was told I couldn’t attend. After graduation, I ran a government medical center in Cairo, learning a brutal truth:

Manual systems don’t just slow people down, but also create the cracks where waste and misconduct thrive. Resolve alone won’t fix it. You have to design the failure points out.

That lesson followed me into tech. At Boubyan Digital Factory, I’m now engineering AI agents and automated governance systems at enterprise scale. But recently, I wanted to solve a problem I’d seen firsthand: medical prescription validation.

This is the story of how I built a Hybrid Neuro-Symbolic Architecture that combines the semantic understanding of LLMs with the deterministic reliability of Python logic, validating insurance claims in seconds, not hours.

The Problem: Manual Prescription Validation is Broken

In my medical career, I saw the same pattern repeat: pharmacists manually parsing handwritten prescriptions, cross-referencing insurance policies, calculating dosages, and checking expiration dates. It was slow, error-prone, and frustrating.

The stakes are high. A single mistake can mean a denied claim, a patient without medication, or worse clinical harm. Yet the solution wasn’t just "more AI." It was smarter AI.

The Reality Check

Most AI wrappers ask the LLM to do everything: "Read this prescription, calculate the dosage, check if it's expired, and tell me if it's approved." Result: LLMs hallucinate math, fail at date comparisons, and ignore strict policy limits.

I needed a system that could understand natural language and enforce deterministic rules. That’s where Hybrid Neuro-Symbolic Architecture came in.

The Solution: LLMs for Understanding, Python for Rules

The critical design decision was to decouple extraction from logic. Here’s the philosophy:

  • →The LLM (Gemini 2.5 Flash): Acts purely as a Translator. Its only job is to convert messy unstructured text (Doctor’s notes) into structured JSON (Pydantic models). It does zero decision-making.
  • →The Code (Python): Acts as the Judge. Once the data is structured, standard Python functions handle the logic. Is 30 pills > 20 limit? Deterministic.

Result: A system with the flexibility of Generative AI but the reliability of a traditional Rule Engine.

The Architecture: A LangGraph State Machine

The application is orchestrated using LangGraph, creating a sequential workflow:

graph LR
    A[Input Text] --> B(Node 1: LLM Extractor);
    B --> C{Validation Gate};
    C --> D(Node 2: Admin Rules);
    D --> E(Node 3: Clinical Math);
    E --> F[Final Adjudication];

Here’s how it works:

Extractor Node (AI)

Parses "Take 1 tab 3x daily" into "frequency": 3 and flags Chronic diseases.

Admin Node (Python)

Validates Policy Type (Acute vs Chronic) and Expiry Dates.

Clinical Node (Python)

Calculates exact box quantity needed and compares against Payer Limits.

Core Stack Breakdown

  • Orchestration: LangChain & LangGraph
  • LLM Engine: Google Gemini 2.5 Flash (via OpenRouter)
  • Validation: Pydantic (Strict Schema Enforcement)
  • Frontend: Streamlit
  • Deployment: Docker

The Three-Stage Validation Pipeline

Stage 1: Extraction (AI-Powered)

The LLM receives the prescription text and extracts structured data using a Pydantic model:

class PrescriptionExtract(BaseModel):
    drug_name: str
    frequency_per_day: int
    duration_days: int
    diagnosis: str
    prescription_date: str  # YYYY-MM-DD
    is_chronic_diagnosis: bool

The AI determines if the diagnosis implies a CHRONIC condition (e.g., Hypertension, Diabetes = true) or ACUTE (e.g., Flu, Pain = false). This is critical for policy enforcement.

Stage 2: Administrative Validation (Python Logic)

Once the data is structured, Python takes over. The validate_admin_rules function checks:

  • Expiry Check: Is the prescription date before the policy form expiry?
  • Chronic Coverage Check: Does the policy allow chronic care for this diagnosis?
def validate_admin_rules(state: AgentState) -> ValidationResult:
    # 1. Date Check
    pres_date = datetime.strptime(extract.prescription_date, "%Y-%m-%d").date()
    expiry_date = datetime.strptime(policy.form_expiry_date, "%Y-%m-%d").date()
    today = datetime.now().date()
    
    if today > expiry_date:
        return ValidationResult(
            status="Rejected", 
            reason=f"Policy Form Expired. Expiry: {expiry_date}, Today: {today}"
        )
    
    # 2. Chronic Coverage Check
    if extract.is_chronic_diagnosis and not policy.allows_chronic:
        return ValidationResult(
            status="Rejected",
            reason=f"Policy excludes Chronic Care, but Diagnosis '{extract.diagnosis}' is Chronic."
        )
    
    return ValidationResult(status="Approved", reason="Administrative Checks Passed")

Stage 3: Clinical Calculation (Python Math)

The final stage calculates the exact quantity needed and compares it against the payer’s box limit:

def calculate_clinical_dosage(state: AgentState) -> ValidationResult:
    total_pills_needed = extract.frequency_per_day * extract.duration_days
    boxes_needed = math.ceil(total_pills_needed / box_size)
    
    detail_msg = (
        f"Prescribed: {extract.frequency_per_day}/day for {extract.duration_days} days. "
        f"Total Tabs: {total_pills_needed}. Box Size: {box_size}. "
        f"Boxes Required: {boxes_needed}."
    )
    
    # Validation against Max Limit
    if boxes_needed > policy.max_box_limit:
        return ValidationResult(
            status="Rejected",
            reason=f"Calculated needs ({boxes_needed} boxes) exceed Policy Limit ({policy.max_box_limit} boxes).",
            calculation_detail=detail_msg
        )
        
    return ValidationResult(
        status="Approved",
        reason="Dosage within clinical and policy limits.",
        calculation_detail=detail_msg
    )

Real-World Testing Scenarios

The Streamlit frontend allows users to simulate different policy contexts and test the validation logic.

Scenario A: The "Happy Path" (Approval)

Context: Policy = "Includes Chronic", Limit = 2 Boxes.

Input: "Patient needs Concor (Hypertension). 1 tab daily for 30 days."

Logic:

  • Diagnosis is Chronic → Allowed.
  • Math: 30 tabs / 20 per box = 1.5 → Rounds to 2 Boxes.
  • 2 Boxes <= Limit 2

Result: ✅ APPROVED

Scenario B: Policy Mismatch (Logic Guardrail)

Context: Policy = "Acute Only".

Input: "Patient needs Concor for Hypertension."

Logic:

  • AI extracts: is_chronic_diagnosis: True.
  • Python Check: policy.allows_chronic (False) vs diagnosis.is_chronic (True).

Result: ❌ REJECTED (Reason: Policy excludes Chronic Care)

Scenario C: Quantity Over-Limit (Math Guardrail)

Context: Limit = 1 Box.

Input: "2 tabs, 3 times daily for 5 days." (Total 30 tabs).

Logic:

  • Math: 30 tabs / 20 per box = 2 Boxes.
  • Python Check: Needs (2) > Limit (1).

Result: ❌ REJECTED (Reason: Exceeds Policy Box Limit)

Why This Architecture Matters

This project demonstrates a critical lesson in AI engineering: not all problems require end-to-end neural networks. Sometimes, the best solution is a hybrid approach that leverages the strengths of both worlds.

LLMs Excel At:

  • Understanding natural language
  • Extracting structured data from unstructured text
  • Handling ambiguity and variation

Python Excels At:

  • Deterministic calculations
  • Date comparisons
  • Enforcing strict business rules

By combining these strengths, we create a system that’s both flexible and reliable, perfect for high-stakes applications like healthcare.

Future Improvements

This is just the beginning. Here’s what’s next:

  • Computer Vision: Integrate Gemini Vision to read handwritten prescriptions from images.
  • RAG Integration: Instead of manual sidebar inputs, use RAG to retrieve policy limits from a 50-page PDF insurance contract.
  • FHIR Standards: Map the JSON output to HL7 FHIR standards for EHR interoperability.
  • Real-Time Integration: Connect to pharmacy management systems for seamless claim processing.

The Hardest Lesson: Trust Through Design

In healthcare, trust isn’t earned, but engineered. Every line of code, every validation rule, every fallback mechanism is a promise to the patient.

The most critical API in any medical system isn’t OpenAI. It’s reliability.

Lasting solutions aren’t born from control or supervision. If you want a problem gone for good, don’t maintain it. Design it out.

Let’s Build Something Autonomous Together

Currently engineering AI agents and automated governance systems at enterprise scale. If you’re rethinking operations with code, RAG, or autonomous agents, let’s talk.

Building clinical AI that has to be right?

I'm Mohamed Fakhry, a physician-engineer (M.B.B.Ch., Cairo University) working on clinical AI architecture, engineering and reliability. I help HealthTech teams find and fix reliability problems in RAG, evaluation, and safety before they reach clinicians.

Mohamed Fakhry

Physician-Engineer working on clinical AI architecture, engineering and reliability, and on healthcare software that has to hold up in real-world use.

Physician-Engineer (M.B.B.Ch.) • Clinical AI Engineering • Former CEO

Connect

Building reliable, production-grade healthcare AI systems.

© 2026 Mohamed Fakhry. All rights reserved.

Built with care using modern web technologies