# Solution Architecture — Milestone 1
## AI-Guided Cardio Thoracic Surgery Patient Intake System

**Version:** 1.0
**Date:** 2026-05-09
**Status:** Draft
**Audience:** PTL, AI Team Lead, Product Stakeholders

---

## 1. The Problem This System Solves

Cardio Thoracic Surgery departments face a structural documentation problem. Junior medical staff conduct patient intake informally — no standard protocol, inconsistent documentation, missed clinical details. By the time a Cardiothoracic Surgeon walks into the consultation room, they often lack a complete patient picture and spend their limited 2–3 minute window re-collecting information instead of making clinical decisions.

**This system closes that gap** by replacing informal intake with an AI-guided, protocol-driven conversation that ends with a clean, structured patient summary ready for the surgeon before they walk in.

---

## 2. Solution at a Glance

```
                    ┌─────────────────────────────────────────┐
                    │         CT Surgery Department           │
                    │                                         │
  Patient ──────► Doctor's Staff                             │
  (speaks)          │  uses handheld device                  │
                    │  guided by AI questions                 │
                    │  speaks patient answers                 │
                    │              ↓                          │
                    │     AI processes each answer            │
                    │     asks follow-up if needed            │
                    │     signals when done                   │
                    │              ↓                          │
                    │     Summary generated in 30s            │
                    │              ↓                          │
  Cardiothoracic Surgeon ◄── reads summary ◄─────────────────┘
  (2-3 min consultation)     asks AI follow-up questions
```

**What changes for Doctor's Staff:** Instead of taking informal notes, they conduct a structured AI-guided conversation. The AI tells them what to ask next based on what the patient just said.

**What changes for Surgeons:** They walk into consultations with a complete, structured patient summary instead of fragmented notes. They can query the AI for specific details in seconds.

---

## 3. Four Solution Pillars

The AI team lead defined four capability areas. Here is how each one is implemented in this system.

---

### Pillar 1 — Chatbot (Adaptive Questioning Engine)

**What it is:**
Claude acts as a clinical intake decision engine. After each patient response, Claude receives the full conversation history and the CT Surgery question protocol, and decides the single most clinically relevant next question to ask. When all required questions are covered, Claude signals that intake is complete.

**What it is not:**
Claude does not speak directly to the patient. It does not diagnose. It does not classify emergencies. It is a question-routing engine — the Doctor's Staff is always the human in the room.

**How it works:**
```
Patient answers question
        ↓
Answer transcribed to English
        ↓
Claude receives:
  - CT Surgery system prompt (dos and don'ts)
  - Department question protocol
  - Full conversation history so far
  - Latest answer
        ↓
Claude returns:
  - Next question   →  Doctor's Staff asks it
  - INTAKE_COMPLETE →  Staff submits, summary generated
```

**Where it lives:** FastAPI (internal Python function) → Claude API (`claude-sonnet-4-6`)

---

### Pillar 2 — RAG (Retrieval-Augmented Generation)

**What it is:**
Every time Claude is called, its context is augmented with retrieved data — the department's clinical protocol and the full session conversation history. This is how the AI "knows" what has already been asked and what still needs to be covered.

**This system uses structured RAG — not vector search.** The data retrieved is structured (question bank from PostgreSQL, conversation history from PostgreSQL) and injected deliberately into Claude's context per call. There is no embedding database.

**Three RAG patterns in use:**

| Pattern | What is retrieved | Where it goes |
|---|---|---|
| Protocol injection | CT Surgery question bank from `protocols` table | Into every Claude intake call |
| History injection | All Q&A so far in the session from `question_responses` | Into every Claude intake call |
| Session injection | Full conversation + summary from completed session | Into Ask More Claude calls |

**Why this matters:**
Without retrieval, Claude has no knowledge of the clinical protocol or what was already asked. RAG is what makes the questioning adaptive and complete — Claude knows both the rules (protocol) and the context (conversation so far).

**Where it lives:** FastAPI fetches protocol + conversation history from PostgreSQL and passes them directly into every Claude call.

---

### Pillar 3 — DevOps + AIOps + Evals

#### DevOps
The system runs as four Docker containers managed by Docker Compose. The same setup runs locally for development, staging for testing, and production for deployment — no environment drift.

```
Docker Compose
  ├── frontend     (React PWA — nginx, public)
  ├── fastapi      (Port 8000, public)
  ├── postgres     (Port 5432, internal only)
  └── redis        (Port 6379, internal only)
```

CI/CD pipeline runs on every push to main — build, lint, test, deploy.

#### AIOps
Every LLM call is instrumented. The following is logged per session:

| Metric | Why it matters |
|---|---|
| Claude latency per call | SLA: ≤2s next question, ≤30s summary |
| Claude token count per session | Cost control — catch runaway prompts |
| Summary generation latency | SLA: ≤30s — critical for surgeon workflow |
| Sessions per day | Usage baseline for capacity planning |

`generation_latency_ms` is stored in `patient_summaries` table. All other metrics are logged to application logs and monitored via Docker log aggregation in M1, with a proper observability stack added in M2.

#### Evals
AI output quality cannot be verified by unit tests alone. The following evaluation framework is defined for M1 validation before go-live:

**Eval 1 — Protocol Coverage**
> Does the AI always ask all required CT Surgery base questions before signalling INTAKE_COMPLETE?

Method: Run 20 simulated intake sessions with scripted patient answers. Verify 100% of required questions appear in `question_responses` before `intakeComplete: true`.

**Eval 2 — Follow-up Relevance**
> Are the follow-up questions clinically relevant to the patient's answers?

Method: A Cardiothoracic Surgeon reviews 10 sample sessions and scores follow-up question relevance on a 1–5 scale. Target: average ≥ 4.

**Eval 3 — Summary Completeness**
> Does the summary contain all significant information captured during intake?

Method: Compare 10 generated summaries against the raw `question_responses` for those sessions. No significant finding should be absent from the summary. Surgeon signs off.

**Eval 4 — No Diagnostic Language**
> Does Claude ever produce diagnostic or emergency classification language?

Method: Automated scan of all Claude outputs (next questions, summaries, query answers) across 50 test sessions for a prohibited word list (diagnose, emergency, critical condition, heart attack, etc.). Zero tolerance.

**Eval 5 — Transcription Accuracy**
> Does Web Speech API achieve ≥ 90% accuracy for CT Surgery medical terminology in English, Hindi, and Telugu?

Method: Have 3 medical staff members speak 20 CT Surgery terms each in all three languages into the intake UI. Compare transcribed output to ground truth. Calculate word error rate per language.

---

### Pillar 4 — UI/UX

**Design principle:** Zero-training interface. Doctor's Staff must be able to pick up the device and conduct an intake session without any onboarding.

**Three distinct interfaces:**

#### Intake Interface (Doctor's Staff)
- Mobile-first, touch-friendly, designed for handheld devices
- One question visible at a time — no scrolling, no clutter
- Large audio record button — single tap to capture answer
- Transcribed text shown for staff to verify before submitting
- Session progress indicator (questions answered / total base questions)
- Intake history panel — shows who else has contributed to this session

#### Summary Interface (Cardiothoracic Surgeon)
- Clean, sectioned summary — readable in 1–2 minutes
- Labelled sections: Chief Complaint, Cardiac Symptoms, Respiratory Symptoms, History, Medications, Lifestyle, Investigations
- "Ask AI" input field below summary for follow-up queries
- Query responses appear inline — no page navigation

#### Account Management (Team Lead)
- Minimal form: create staff account with name, role, department, email, PIN
- Deactivate / reset PIN for existing accounts
- No complex admin UI in M1 — full admin module in M3

---

## 4. System Context

```mermaid
graph TD
    DS["Doctor's Staff\n(handheld device)"]
    CT["Cardiothoracic Surgeon\n(tablet / laptop)"]
    TL["Team Lead\n(any device)"]

    subgraph AI-NIMS System
        UI["React PWA\n(Web Speech API — browser transcription)"]
        BE["FastAPI\n(Auth · Sessions · Business Logic · DB · Claude)"]
    end

    EXT1["Claude API\n(Anthropic)"]
    DB["PostgreSQL"]
    RD["Redis"]

    DS -->|Conducts intake\nSpeaks answers| UI
    CT -->|Reviews summary| UI
    TL -->|Creates staff accounts| UI

    UI --> BE
    BE --> DB
    BE --> RD
    BE --> EXT1
```

**System boundary:** Everything inside AI-NIMS is built and owned by Divami. Claude API is the only external AI dependency. The hospital's network infrastructure is a deployment dependency but not part of the system.

**What is explicitly outside the system:**
- Hospital EMR/EHR systems — no integration
- Senior staff notification — external to the system
- Patient data beyond 48 hours — not stored

---

## 5. Capability Map

| Business Capability | Solution Component | Milestone |
|---|---|---|
| AI-guided CT Surgery intake | Chatbot (Claude adaptive questioning) | M1 |
| Browser transcription | Web Speech API (English, Hindi, Telugu) | M1 |
| Patient case summary | Claude summary generation | M1 |
| Session resilience | Redis locks + PostgreSQL persistence | M1 |
| User management | FastAPI auth + staff accounts | M1 |
| Senior consultation alerts | Claude pattern detection + alert engine | M2 |
| Full role enforcement | FastAPI RBAC middleware | M2 |
| Audit logging | PostgreSQL audit_logs table | M2 |
| Admin management UI | React admin module | M3 |
| Doctor protocol configuration | Protocol management UI + DB | M3 |
| Multi-department onboarding | Department config in DB (schema ready in M1) | M4 |

---

## 6. Multi-Department Extensibility

The system is designed so that adding a new department (e.g., Cardiology, Neurosurgery, Orthopaedics) requires **zero code changes**.

Each department is a row in the `departments` table with its own:
- LLM system prompt (defines the clinical context and dos/don'ts for that specialty)
- LLM summary prompt (defines the summary format for that specialty)
- Question protocol (the base question bank for that specialty)

```
To add Cardiology department:
  1. INSERT INTO departments (name, llm_system_prompt, llm_summary_prompt, llm_query_prompt)
  2. INSERT INTO protocols (department_id, question_bank)
  3. Create Team Lead account for that department
  → System works for Cardiology with no code deployment
```

Staff, patients, sessions, and protocols are all department-scoped. One deployment serves all departments with full data isolation.

---

## 7. Milestone Progression

```
M1 — Core intake loop works
  Chatbot questions + Web Speech API transcription (browser) + Summary generation
  Staff sessions + Patient data lifecycle + Basic auth

      ↓

M2 — Safety layer added
  Senior consultation alerts (Claude pattern detection)
  Full RBAC enforcement
  Audit logging

      ↓

M3 — Self-service configuration
  Admin module (Team Lead onboards staff via UI)
  Doctor training module (Surgeon configures protocols)
  Regional language configuration UI

      ↓

M4 — Scale
  Second department onboarded
  Performance optimization under load
  Expansion framework validated
```

Each milestone builds on the previous — M1 must be stable before M2 adds safety features, and M3 must be complete before departments can self-configure for M4.
