AI Online
Local AI Layerv2.1
Avg Latency160ms
Models Active2
Context Window4096 tok

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.

Size
4B params
Quant
Q4_K_M
Latency
~160ms
GGUFllama.cppMedicalOllama

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.

Size
3B params
Quant
Q4_K_M
Latency
~90ms
GGUFQwenFastOllama

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.

Model
small
Quant
INT8
RTF
< 0.3x
WhisperSTTINT8CPU

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.

Engine
ONNX
Latency
~80ms
Model Size
~28MB
PiperTTSONNXStreaming

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.

Fallback Levels
3
Routing Rules
8
Providers
3
RouterFallbackasyncio

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.

CPU Usage
< 1%
Latency
< 20ms
False Positive
< 0.1/hr
PorcupineVADSileroEdge

Routing Architecture

Model Routing Decision Treerule-based cascade
1

Emergency Query?

Fall detected / SpO₂ critical / unresponsive

→ MedGemma 4B (always)
2

Health / Clinical Query?

vitals, anomaly, symptoms, drug interactions

Local available → MedGemma 4B
Local down → GPT-4o (cloud)
3

Conversational Query?

reminders, questions, casual interaction

Latency OK → Qwen2.5:3b (faster)
Latency budget strict → Qwen or Cloud
4

High Complexity (> 0.75)?

multi-step reasoning, differential diagnosis

Local → MedGemma 4B
No local → GPT-4o

Fallback Chain

MedGemmaQwenGPT-4oStatic Response
Ollama Runtime Architecturellama.cpp inference engine

Runtime Engine

GGUF model format, SIMD-optimized

llama.cpp (C++)

Quantization

4-bit mixed precision, 35% size reduction

Q4_K_M

Threading

Auto thread detection, pinned to performance cores

OpenMP

Context Cache

Persistent key-value cache across turns

KV Cache

Memory Layout

Memory-mapped model weights, zero-copy load

mmap()

API Server

OpenAI-compatible /api/generate endpoint

Ollama REST

RAM Footprint

MedGemma 4B Q4_K_M~2.8 GB
Qwen2.5:3b Q4_K_M~1.9 GB
Whisper Small INT8~280 MB

Implementation

ai/router.py
python
# 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
python
# 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

ModelProviderSizeQuantizationLatencyContextPrimary Use-Case
MedGemma 4BOllama / GGUF4B paramsQ4_K_M~160ms8192 tokHealth analysis, clinical reasoning, anomaly detection
Qwen2.5:3bOllama / GGUF3B paramsQ4_K_M~90ms4096 tokReminders, conversation, simple queries
GPT-4o (cloud)OpenAI APICloud—~1200ms128k tokFallback when local models unavailable or insufficient
Whisper Smallfaster-whisper244M paramsINT8~320ms30s audioSpeech-to-text, voice command recognition
Piper TTSpiper-tts~28MBONNX~80msStreamingText-to-speech, RAFIQ voice output

Health Analysis Pipeline

Vital Signs → LLM → Decision → Actionend-to-end processing chain
Step 01 · Sensor Input
  • Heart Rate (BPM)
  • SpO₂ (%)
  • Blood Pressure
  • Temperature
  • Motion / Fall
Step 02 · Threshold Check
  • Rule-based filters
  • Soft alert zone
  • Hard alert zone
  • Emergency zone
  • Trend analysis
Step 03 · LLM Reasoning
  • MedGemma analysis
  • Context injection
  • Patient history
  • Differential dx
  • Confidence score
Step 04 · Decision + Action
  • Alert generation
  • TTS announcement
  • SMS / call family
  • Home automation
  • Emergency 911

Anomaly Detection & Emergency Classification

Anomaly Detection Logicthreshold rules + LLM reasoning

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

Emergency Classificationseverity levels & escalation
SEV-1 · Critical
SLA: < 5s

Triggers: Fall + unresponsive, SpO₂ < 88%, cardiac rhythm anomaly

Actions: Emergency 911 call, family SMS, all home devices alert, voice emergency mode

SEV-2 · Urgent
SLA: < 15s

Triggers: Hard threshold breach, gas detected, temperature critical

Actions: Family SMS, voice alert, automatic valve close (gas), doctor notification

SEV-3 · Warning
SLA: < 60s

Triggers: Soft threshold, irregular pattern, medication miss

Actions: Voice reminder, mobile push notification, dashboard alert

SEV-4 · Informational
SLA: async

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.

Window Size
4096 tok
Summary Model
MedGemma
Compression
~80%
KV CacheRolling WindowCompression

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.

Storage
SQLite FTS5
Retrieval
keyword match
Max Entries
10,000
FTS5SQLiteLong-term

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.

Profile Format
JSON→Prompt
Token Cost
~120 tok
Updated
Real-time
ProfileSystem PromptPersonalized

Emotional AI States

RAFIQ Emotional State Machine4 operational modes
calm

Trigger Condition

All vitals nominal, no active alerts

Voice Style

Soft, measured pace, lower frequency

Avatar Behavior

Gentle idle animation, relaxed expression

concerned

Trigger Condition

Minor anomaly detected, threshold soft-breach

Voice Style

Slightly elevated, attentive tone

Avatar Behavior

Eyebrow raise, leaning forward animation

alert

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

emergency

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

Ollama Service Endpointslocalhost inference server
POST/api/generate~160ms
POST/api/chat~160ms
POST/api/embeddings~40ms
GET/api/tags< 5ms
GET/api/ps< 5ms
POST/api/pullasync