AI System
AI Orchestration Layer
RAFIQ runs a multi-model AI stack entirely at the edge. MedGemma 4B handles clinical reasoning; Qwen2.5 handles conversation; Whisper and Piper provide the voice interface. All inference is local-first with cloud fallback via OpenAI when models are unavailable.
AI Components
MedGemma 4B
Medical AI · GGUF quantized
Primary inference model trained on medical corpora. Handles vital sign analysis, anomaly detection, clinical reasoning, and emergency classification.
Qwen2.5:3b
Conversational AI · GGUF
Lightweight general-purpose model for reminders, scheduling, and daily conversation. Lower latency makes it ideal for interactive use-cases.
Whisper STT
Speech-to-Text · faster-whisper
OpenAI Whisper Small running on faster-whisper with INT8 quantization. Processes 30s audio chunks at ~320ms on CPU for real-time voice commands.
Piper TTS
Text-to-Speech · ONNX
Piper neural TTS with English and Arabic voice models. Generates natural speech audio in ~80ms via ONNX runtime, streamed directly to audio output.
AI Orchestrator
Routing · Fallback · Context
Central routing engine that selects models based on query type, complexity score, latency budget, and local availability. Implements a cascading fallback chain.
Picovoice / Silero
Wake Word · VAD
Always-on wake word engine ('Hey RAFIQ') powered by Picovoice Porcupine with < 1% CPU. Silero VAD used as fallback for voice activity detection in noisy environments.
Routing Architecture
Emergency Query?
Fall detected / SpO₂ critical / unresponsive
Health / Clinical Query?
vitals, anomaly, symptoms, drug interactions
Conversational Query?
reminders, questions, casual interaction
High Complexity (> 0.75)?
multi-step reasoning, differential diagnosis
Fallback Chain
Runtime Engine
GGUF model format, SIMD-optimized
Quantization
4-bit mixed precision, 35% size reduction
Threading
Auto thread detection, pinned to performance cores
Context Cache
Persistent key-value cache across turns
Memory Layout
Memory-mapped model weights, zero-copy load
API Server
OpenAI-compatible /api/generate endpoint
RAM Footprint
Implementation
# ai/router.py — AI Routing Decision Engine
import asyncio
from enum import Enum
from dataclasses import dataclass
from typing import Optional
class ModelProvider(Enum):
MEDGEMMA = "medgemma:4b" # Primary: health/clinical queries
QWEN = "qwen2.5:3b" # Secondary: general conversation
CLOUD_GPT = "gpt-4o" # Fallback: complex or offline-failed
@dataclass
class RoutingContext:
query_type: str # "health" | "conversation" | "reminder" | "emergency"
complexity: float # 0.0 – 1.0 estimated reasoning depth
is_emergency: bool
local_available: bool
latency_budget_ms: int # caller's max tolerable latency
class AIRouter:
def __init__(self, ollama_client, openai_client):
self.ollama = ollama_client
self.openai = openai_client
self._health_check_interval = 30 # seconds
async def route(self, ctx: RoutingContext) -> ModelProvider:
# Rule 1: Emergencies always go to MedGemma (lowest latency local model)
if ctx.is_emergency:
return ModelProvider.MEDGEMMA
# Rule 2: Health / clinical queries → MedGemma
if ctx.query_type in ("health", "anomaly", "vitals"):
if ctx.local_available:
return ModelProvider.MEDGEMMA
return ModelProvider.CLOUD_GPT # cloud fallback
# Rule 3: Conversation within latency budget → Qwen (faster)
if ctx.query_type == "conversation":
if ctx.local_available and ctx.latency_budget_ms >= 100:
return ModelProvider.QWEN
return ModelProvider.CLOUD_GPT
# Rule 4: High-complexity reasoning → MedGemma or Cloud
if ctx.complexity > 0.75:
return ModelProvider.MEDGEMMA if ctx.local_available else ModelProvider.CLOUD_GPT
# Default: Qwen for speed
return ModelProvider.QWEN if ctx.local_available else ModelProvider.CLOUD_GPT
async def infer(self, prompt: str, ctx: RoutingContext) -> str:
provider = await self.route(ctx)
try:
if provider in (ModelProvider.MEDGEMMA, ModelProvider.QWEN):
response = await self.ollama.generate(
model=provider.value,
prompt=prompt,
options={"temperature": 0.3, "num_ctx": 4096},
)
return response["response"]
else:
# Cloud fallback with retry
return await self._cloud_infer(prompt)
except Exception as exc:
# Fallback chain: try other local model first
return await self._fallback_infer(prompt, failed=provider, error=exc)
async def _fallback_infer(self, prompt, failed, error) -> str:
fallback_order = [
ModelProvider.MEDGEMMA,
ModelProvider.QWEN,
ModelProvider.CLOUD_GPT,
]
for model in fallback_order:
if model == failed:
continue
try:
if model == ModelProvider.CLOUD_GPT:
return await self._cloud_infer(prompt)
resp = await self.ollama.generate(model=model.value, prompt=prompt)
return resp["response"]
except Exception:
continue
return "AI system unavailable. Please check local model status."# voice/pipeline.py — Voice Processing Pipeline
import asyncio
from faster_whisper import WhisperModel
from pvporcupine import Porcupine # Wake word detection
import piper # TTS engine
class VoicePipeline:
def __init__(self, ai_router):
# STT: faster-whisper with INT8 quantization for edge performance
self.stt = WhisperModel("small", device="cpu", compute_type="int8")
# Wake word: "Hey RAFIQ" via Picovoice Porcupine
self.porcupine = Porcupine(
access_key=PICOVOICE_KEY,
keywords=["rafiq"],
sensitivities=[0.6],
)
# TTS: Piper with Arabic/English voice model
self.tts = piper.PiperVoice.load(
model_path="models/en_US-lessac-medium.onnx",
config_path="models/en_US-lessac-medium.onnx.json",
)
self.router = ai_router
self.is_listening = False
async def listen_for_wake_word(self):
"""Continuously monitor audio for wake word activation."""
async for audio_frame in self._mic_stream(frame_length=512):
keyword_index = self.porcupine.process(audio_frame)
if keyword_index >= 0:
await self.on_wake_word_detected()
async def on_wake_word_detected(self):
"""Capture, transcribe, route, and respond to user utterance."""
self.is_listening = True
audio = await self._capture_utterance(timeout_ms=5000)
# STT: transcribe with beam search
segments, _ = self.stt.transcribe(audio, beam_size=5, language="en")
transcript = " ".join(seg.text for seg in segments).strip()
if not transcript:
return
# Route to AI
ctx = RoutingContext(
query_type=classify_query(transcript),
complexity=estimate_complexity(transcript),
is_emergency=False,
local_available=True,
latency_budget_ms=2000,
)
response_text = await self.router.infer(transcript, ctx)
# TTS: synthesize and stream audio output
await self._speak(response_text)
self.is_listening = False
async def _speak(self, text: str):
audio_bytes = self.tts.synthesize(text, streaming=True)
await self._audio_output(audio_bytes)Model Registry
AI Model Comparison
All models registered in RAFIQ runtime
| Model | Provider | Size | Quantization | Latency | Context | Primary Use-Case |
|---|---|---|---|---|---|---|
| MedGemma 4B | Ollama / GGUF | 4B params | Q4_K_M | ~160ms | 8192 tok | Health analysis, clinical reasoning, anomaly detection |
| Qwen2.5:3b | Ollama / GGUF | 3B params | Q4_K_M | ~90ms | 4096 tok | Reminders, conversation, simple queries |
| GPT-4o (cloud) | OpenAI API | Cloud | — | ~1200ms | 128k tok | Fallback when local models unavailable or insufficient |
| Whisper Small | faster-whisper | 244M params | INT8 | ~320ms | 30s audio | Speech-to-text, voice command recognition |
| Piper TTS | piper-tts | ~28MB | ONNX | ~80ms | Streaming | Text-to-speech, RAFIQ voice output |
Health Analysis Pipeline
- Heart Rate (BPM)
- SpO₂ (%)
- Blood Pressure
- Temperature
- Motion / Fall
- Rule-based filters
- Soft alert zone
- Hard alert zone
- Emergency zone
- Trend analysis
- MedGemma analysis
- Context injection
- Patient history
- Differential dx
- Confidence score
- Alert generation
- TTS announcement
- SMS / call family
- Home automation
- Emergency 911
Anomaly Detection & Emergency Classification
RAFIQ uses a two-phase anomaly engine. Phase 1 applies deterministic threshold rules for known vital sign ranges. Phase 2 passes borderline cases to MedGemma with a structured prompt including patient history, recent metrics, and the suspected anomaly for probabilistic reasoning.
Heart Rate
Soft
< 50 or > 110 BPM
Hard
< 40 or > 140 BPM
Emerg
< 30 or > 180 BPM
SpO₂
Soft
< 94%
Hard
< 91%
Emerg
< 88%
Temperature
Soft
> 37.8°C
Hard
> 38.5°C
Emerg
> 40°C or < 35°C
Systolic BP
Soft
> 140 mmHg
Hard
> 160 mmHg
Emerg
> 180 mmHg
Triggers: Fall + unresponsive, SpO₂ < 88%, cardiac rhythm anomaly
Actions: Emergency 911 call, family SMS, all home devices alert, voice emergency mode
Triggers: Hard threshold breach, gas detected, temperature critical
Actions: Family SMS, voice alert, automatic valve close (gas), doctor notification
Triggers: Soft threshold, irregular pattern, medication miss
Actions: Voice reminder, mobile push notification, dashboard alert
Triggers: Trend anomaly, slight deviation, hydration low
Actions: Dashboard log, next-interaction voice mention
Conversational Memory System
Context Window
Short-term memory · 4096 tokens
Active conversation kept in a rolling 4096-token context window. Older turns are summarized and compressed when the window fills, using MedGemma's summarize prompt.
Long-term Memory
SQLite ai_memory table
Compressed summaries, patient preferences, and AI observations stored in the ai_memory SQLite table. Retrieved via FTS5 semantic search on each new conversation.
Patient Profile
Injected context · every turn
Structured patient profile (age, conditions, medications, allergies, preferences) injected into every LLM prompt as a system context block, ensuring personalized health responses.
Emotional AI States
Trigger Condition
All vitals nominal, no active alerts
Voice Style
Soft, measured pace, lower frequency
Avatar Behavior
Gentle idle animation, relaxed expression
Trigger Condition
Minor anomaly detected, threshold soft-breach
Voice Style
Slightly elevated, attentive tone
Avatar Behavior
Eyebrow raise, leaning forward animation
Trigger Condition
Hard threshold breach, critical metric out of range
Voice Style
Urgent, clear pronunciation, fast rate
Avatar Behavior
Alert gesture, direct eye contact animation
Trigger Condition
Fall detected, SpO₂ < 88%, unresponsive user
Voice Style
Maximum clarity, contact instructions only
Avatar Behavior
Red pulse overlay, emergency action prompts
Runtime Status