Backend module reference
Everything lives in backend/app/: Python 3.13, FastAPI, run by uvicorn. Run anything outside pytest with PYTHONPATH=backend.
Entry points
| File | Responsibility |
|---|---|
main.py | Creates the FastAPI app and mounts the routers (api.py core: health/config/integrations; api_ops.py live; api_platform.py). The legacy scenario routers (api.py::legacy_router, api_stream.py) and the startup scenario seed are mounted only with VAAZHVU_LEGACY=1 (mount_legacy). On startup, unless VAAZHVU_LIVE=0, it: starts the OpsController and the simulator; warms the voice line in a thread (loads both TTS voices and runs MLX Whisper once); and starts the LLM keep-warm thread, which keeps the TLS connection to the cloud LLM open. It serves the built web UI (frontend/dist), /hospital, /ambulance and /debug/voice, with an SPA fallback. |
api_ops.py | The live API (/api/ops/*, including the Copilot at /copilot); see API reference. Thin: validates input, calls the controller, shapes the responses for each audience. The citizen view (/incidents/{id}/public) carries no clinical internals; the crew view (/units/{id}/assignment) carries telemetry and the caller conversation. |
models.py | Pydantic domain models: GeoPoint, Ambulance (capabilities, agency ems/police/fire, status, base), Hospital (capabilities, readiness, diversions), Incident, TriageAssessment (severity distribution, confidence, explain), PolicyDecision, DispatchDecision, CandidateOption, enums Capability (ALS, BLS, CARDIAC, TRAUMA, OB), UnitStatus, Severity. |
observability/access_log.py | Request access-log middleware (vaazhvu.access logger: method, path, status, ms). |
Live operations: ops/
| File | Responsibility |
|---|---|
ops/controller.py | OpsController, the operational brain (singleton via get_controller()). It owns the incident lifecycle: • ingest creates or threads an incident, with idempotency keys. • _process runs ASR → triage → geocode → policy → dispatch. • _recommend_and_maybe_dispatch commits the decision, or holds it as pending_approval. • approve / override; set_location; resolve_incident / cancel_incident. • append_transcript: continuous re-triage on every caller turn; re-dispatches if still waiting, escalates if moving. • ingest_vitals: NEWS2; deterioration leads to re-optimisation or a backup unit. • Hospital alerts plus FHIR; set_hospital_status (diversions re-evaluate inbound patients). • Coverage checks and redeploy recommendations; traffic disruptions with re-routing; unit failure and failover. • Caller messaging: reply, caller_message, turn_reply, and status announcements on text channels. • run_demo (scripted storylines from config/demo.yaml). |
ops/calltaker.py | The AI call-taker. • situation() turns the incident into what the model reads: status and its meaning, what was last told to the caller, location confidence, triage findings with the caller's quotes, ruled-out concepts, patient details, the responding unit with level, ETA and hospital. • speak() streams the model's reply, splits it into sentences, guards each one (caller's script; no numbers not supplied by the system or the caller), and caps the reply at 2 sentences. If no model is reachable it falls back to the configured offline line. • respond(): the text-channel turn, recorded in the thread. • history_for(): voice and text are separate conversations; each agent sees the other channel's turns as labelled context. • The brief is config/calltaker.yaml. |
ops/conversation.py | Channel helpers: TEXT_CHANNELS (sms, app, sos), announce_statuses(), caller_lang(). |
ops/world.py | World: units, hospitals, incidents, unit tracks (road geometry + timing, position(), remaining_sec(), remaining_route()), unit↔incident map, traffic disruptions, demand per zone (an OSM prior blended with observed incidents). TrafficIncident: a disruption, either a circle (no OSRM) or snapped to its road (node pairs, name, bearing): touches() / passes_closure() test a route against that road only. |
ops/forecast.py | Next-hour call forecast per zone: city rate × hour-of-day multiplier × zone share, the share a Dirichlet update of the OSM prior with recent incidents decayed by age (half-life). Seeds from persisted incidents once. Used by check_coverage / coverage_snapshot (forecast, forecast_top, recommendation reason: "forecast"). Config forecast:. |
ops/fleet.py | Fleet planning: MEXCLP (maximum expected coverage) solved with OR-Tools CP-SAT over emergency-profiled hospitals as candidate bases and OSM localities as demand points, using the OSRM duration matrix. Writes or reads data/fleet_plan.json. Also places police and fire first responders from OSM stations. |
ops/offers.py | Unit acceptance: a committed unit with a crew present is offered the job (held at assigned) until it accepts; decline or timeout releases it and re-dispatches without it; late acceptance switches back only when clearly better. Simulated units accept at once. |
ops/manual.py | Manual dispatch fallback: run card (nearest free units by straight-line distance, nearest EDs) when the engine raises (dispatch_engine degraded) or a supervisor switches manual mode on. |
ops/sim.py | The simulation clock thread. Advances world.sim_time, moves units along their tracks, fires arrivals (on scene, at hospital, back at base), drives the patient monitor, and publishes fleet.positions. |
ops/bus.py | LiveBus: every event gets a global sequence number and an optional idempotency key. It is persisted to SQLite, fanned out to SSE subscribers, and mirrored to NATS. |
ops/persistence.py | The store: the event log, incidents, and the audit trail (who approved or overrode what). VAAZHVU_DB: the compose Postgres, or a SQLite file (default var/vaazhvu.db; tests). Claims the database for the live api. |
ops/db.py | Postgres behind the sqlite3 interface: placeholder and DDL translation, SQLite-like typing, rollback on error, reconnect, and the owner advisory lock. Portable helpers columns(), tables(), json_text(). |
AI access: mcp/, copilot.py
See AI access and the Copilot. No module here decides anything: they read what the engine recorded, or feed labelled simulated inputs through the controller's normal entry points.
| File | Responsibility |
|---|---|
mcp/tools.py | The tool registry: name, schema, permission(s), kind (read / sim). call(name, args, principal) checks permissions, runs the tool, counts vaazhvu_mcp_tool_*, and for sim tools writes an mcp.<tool> audit row and publishes mcp.action. |
mcp/views.py | Read-only projections over the OpsController: incident, timeline (er_handoff.describe), dispatch explanation (from inc.decision: selected, nearest, nearest capable, alternatives with the engine's reasons), hospital explanation (ranked options; one named hospital scored with the engine's fit / admissible), duplicates, units / hospitals near a point, statewide facilities. Leaves out caller identity and transcripts. |
mcp/sim.py | Labelled simulation: a demo call via ingest (waits for the pipeline), deterioration via ingest_vitals with monitor-sim/mcp vitals from config/copilot.yaml (seeds the simulated monitor so later readings agree), the playback clock, storylines. Waits until the incident's event log goes quiet so the result lists what Vaazhvu did. |
mcp/server.py | MCP server (mcp SDK 2.x low-level Server): tools, instructions stating the safety boundary, prompts incident_brief / jury_demo. mount(app) adds stateless Streamable HTTP at /api/mcp. Principal: the HTTP request's (platform/access.resolve), or current_principal in process. |
mcp/gateway.py | Public edge (compose service mcp-gateway, :8790): serves only POST /mcp, requires an API key, forwards no cookies or role headers, and proxies to /api/mcp. A tunnel points here. |
mcp/bridge.py | python -m app.mcp.bridge: stdio MCP server that forwards to /api/mcp (VAAZHVU_MCP_URL, VAAZHVU_API_KEY). |
copilot.py | Dispatcher Copilot: run_turn opens an in-process MCP client session as the dispatcher, loops llm.chat(…, tools) for up to generation.max_steps rounds, and yields tool_call / tool_result / answer events. Without a model it answers from get_incident + explain_dispatch without generation. Brief and settings: config/copilot.yaml; telemetry operation copilot.turn. |
Voice: voice/
| File | Responsibility |
|---|---|
voice/agent.py | Real-time voice line on Pipecat. • The pipeline: WebSocket transport (binary PCM16 16 kHz both ways; JSON control messages) → Silero VAD (0.7 s end-of-turn) → ContextualWhisperMLX → IntakeAgent → transport. • ContextualWhisperMLX is MLX Whisper on the Apple GPU, primed with the agent's last words, with temperature fallback and a script check (garbage-script output becomes an unclear event). • IntakeAgent streams call-taker sentences into macOS say TTS. It merges turns when the caller pauses mid-thought, barges in only on sustained caller speech, re-replies if a transcript is lost, and announces dispatch progress when the line is quiet. It records every turn in the incident thread. • Helpers: synthesize() (cached TTS), warm_tts(), script_ok(), make_stt(). |
voice/intake.py | Legacy Pipecat intake contract (question flow) used by /api/voice/intake-flow. |
Understanding the call: asr/, nlp/, triage/, llm/, geo/
| File | Responsibility |
|---|---|
asr/service.py | Speech-to-text for uploaded audio (/intake/voice). Uses faster-whisper (CTranslate2, CPU int8, model VAAZHVU_WHISPER_MODEL), forced language, and confidence metadata passed into triage. The live voice line uses MLX Whisper instead (see voice/agent.py). Has an IndicConformer adapter (gated weights, not installed). |
nlp/langid.py | Language ID: Tamil script vs Latin, fastText lid.176 for English vs other, and a wordfreq code-mix ratio. If 25% or more of the tokens are not English, the text is treated as Tanglish. |
nlp/transliterate.py | Client for the IndicXlit service (services/xlit). Converts Tanglish to Tamil script. |
nlp/translate.py | IndicTrans2 (dist-200M, on MPS on a macOS host, CPU in Docker). Translates Tamil script to English, giving the LLM and the dispatcher an extra view; it never replaces the caller's words. |
triage/ontology.py | Clinical concept ontology: each concept's severity weight, red-flag status and required capabilities (e.g. not_breathing: critical, red flag, ALS). |
triage/extractor.py | LLM structured extraction with a JSON schema. Runs N samples (VAAZHVU_TRIAGE_SAMPLES, default 5), each returning findings with status (present/absent/uncertain) and an evidence quote. A finding counts only if its quote appears in the caller's words or one of the machine views (transliteration, translation); otherwise it is rejected (hallucination containment). |
triage/pipeline.py | Puts it together. Severity distribution = the smoothed vote over samples. Confidence = vote share × agreement × input quality (ASR confidence, language-pipeline health). Returns a TriageAssessment with an explain block (views, findings, denied, patient age/sex, location text, rejected findings). |
triage/engine.py | triage_text() / triage_audio() entry points, delegating to the pipeline. |
llm/client.py | LLM clients: • OllamaClient (local, schema-enforced JSON). • OpenAICompatClient (DeepSeek or any OpenAI-compatible API: JSON mode with the schema in the prompt; per-mode extra params). • FallbackClient (cloud primary → local fallback). • json(), sample() (parallel self-consistency), stream() (streamed text for the call-taker). • A pooled keep-alive HTTP client and keep_warm(). Provider chosen by get_llm() from the environment. |
geo/gis.py | Loads data/chennai_gis.json: hospitals (merged with hospital_profiles.json), police/fire/ambulance stations, localities, landmarks, zones. Has zone_for(point) and nearest-locality lookups. |
geo/geocode.py | Resolves spoken locations: rapidfuzz n-gram windows over every view of the call, matched against the OSM gazetteer, with a distinctive-token rule (avoids "road" or "nagar" matching anything). A window needs a word that identifies a place: the region's own name (Chennai / சென்னைல / a misheard சின்னைல்), generic street words ("2nd Avenue"), numbers and particles never match alone. Tamil is also compared with sound-alike letters folded, and a short Tamil word may not fuzzy-match a name more than a letter away. Score ≥ 88 means verified; ≥ 80 is plausible; below that is rejected: no point, and the guessed name is not reported as the place. Optional Nominatim fallback. |
Deciding: safety/, dispatch/, routing/, optimizer/, scorer/
| File | Responsibility |
|---|---|
safety/policy.py | Deterministic safety policy, rules R1–R9 (see Safety and dispatch). Output is a PolicyDecision: an effective_assessment (what downstream must use), mandatory capabilities, human_required with reasons, and provisional dispatch. Thresholds are in config/policy.yaml. |
dispatch/risk.py | RiskDispatchEngine: enumerates response bundles and scores J = E[harm] + ρ·Std[harm] + future-coverage cost. Hard constraints apply; the decision records alternatives, the nearest-unit baseline and why it lost. Handles degradation when ALS is unavailable. Cross-checks with the Go scorer /score/risk when VAAZHVU_SCORER_URL is set. Parameters are in config/dispatch.yaml. |
routing/provider.py | OsrmRoutingProvider (route with geometry; table, i.e. the duration matrix) and the HaversineRoutingProvider fallback. default_routing() picks based on VAAZHVU_OSRM_URL. |
routing/traffic.py | Traffic-aware routing per road: snap_disruption snaps a disruption to its road (OSRM nearest + a bearing probe). route() asks OSRM for alternatives with steps and node annotations; a closure blocks only routes that drive through the closed point on that road (detours via points either side if every alternative does; otherwise radius penalty and provider osrm+traffic:no-detour, steps no_detour:<id>); a slowdown adds (factor−1) × the OSRM duration of the route's stretch on that road within radius_m. Without OSRM the old circle model applies. Config traffic:. |
optimizer/vroom_client.py | VROOM VRP adapter (capability-as-skills baseline B2 in the evaluation). |
optimizer/cpsat.py | CP-SAT batch assignment (legacy multi-incident path). All three OR-Tools models: Optimisation (OR-Tools). |
scorer/client.py | HTTP client for the Go dispatch scorer. |
dispatch/engine.py, dispatch/batch.py | Legacy weighted-utility engine and batch assignment (used by the legacy runner and tests). |
Patient and hospital: vitals/, fhir/, cad/
| File | Responsibility |
|---|---|
vitals/physiology.py | PatientMonitor: a latent physiological state per patient, driven by the severity class and time. It synthesises ECG / PPG / respiration with NeuroKit2 and re-measures HR, SpO₂ and RR from those signals, the way a real monitor does. |
vitals/news2.py | NEWS2 (Royal College of Physicians, 2017): component scores, total, risk band, red score, escalate flag. |
vitals/sim.py | Legacy vitals simulator and ECG waveform. |
fhir/resources.py | FHIR R4 Patient, Encounter, vital-signs Observations (LOINC + UCUM) and Conditions, packed as transaction Bundles (incident_bundle) and POSTed to HAPI FHIR (VAAZHVU_FHIR_URL). Each triage finding counted as present becomes a provisional encounter-diagnosis Condition. It always has code.text and the caller's quote as evidence. It gets a SNOMED CT coding only where config/fhir_codes.yaml maps the concept. post_bundle never raises; it returns {posted, status, error} and logs rejections. IDs are sanitised for HAPI. Tested against a live HAPI server when VAAZHVU_FHIR_TEST_URL is set (tests/test_fhir_resources.py). |
fhir/writer.py | Legacy single-Observation writer. |
cad/resgrid_adapter.py | Mirrors every committed dispatch into a Resgrid CAD (POST /api/v4/Calls/SaveCall). Does nothing unless VAAZHVU_RESGRID_URL and _TOKEN are set. |
Events: events/
| File | Responsibility |
|---|---|
events/nats_bus.py | NatsBridge: publishes bus events to NATS JetStream subjects ems.<event_type> (VAAZHVU_NATS_URL). |
events/bus.py | Legacy in-process bus (one per scenario run). |
Legacy scenario path
| File | Responsibility |
|---|---|
sim/runner.py | run_scenario(): the original single-pass pipeline over a scripted scenario (call → triage → policy → dispatch → vitals → escalation → coverage). |
sim/scenarios.py, sim/full_demo.py, sim/agency_units.py, sim/cli.py | Scenario definitions, the full storyline, police/fire units, and the CLI (make demo). |
api.py, api_stream.py, store.py | Legacy /api/* endpoints, SSE and the in-memory STORE. |
operations.py | Fleet strain / coverage overview for /api/operations/overview. |
eval/baselines.py | Legacy B0/B1 baseline comparison on the scenarios. |
Other code
| Path | Responsibility |
|---|---|
services/xlit/server.py | IndicXlit HTTP service (Python 3.10 venv because of fairseq). POST /transliterate, Latin → Tamil script. Port 8095. |
services/dispatch-scorer/ | Go reimplementation of the dispatch objective (main.go legacy weights, risk.go the risk objective) with tests. Used for parity cross-checking. |
backend/app/static/voice_debug.html | The voice debug page. |
scripts/ | See Data and Setup and running: build_chennai_gis.py, profile_hospitals.py, fetch_models.py, eval_dispatch.py, voice_call_sim.py, plus run helpers. |
tests/ | pytest suite. conftest.py turns off external services and injects ScriptedLLM (fixed structured extractions) via set_pipeline. |