Monitoring
One view of every service, dependency and live metric in the stack.
The live system is not one process. It is Docker containers, the native Ollama app
and a cloud call, and they fail independently. scripts/monitor_stack.py probes all of
them in one pass and prints a dashboard. It is stdlib-only, so it runs anywhere
the stack does.
What is watched
| Probe | Where | Why it matters |
|---|---|---|
api | :8001/api/health | REST + SSE + voice WS + built console |
frontend (vite) | VAAZHVU_FRONTEND_URL | dev console; probed only when that variable is set |
dispatch-scorer | :8081/health | Go expected-harm cross-check |
nats | :8222/varz (VAAZHVU_NATS_MONITOR_URL) | JetStream event mirror |
osrm | :5001/nearest/... | real road routing / ETAs |
vroom | :3000/health | capability VRP baseline |
hapi-fhir | :8090/fhir/metadata | FHIR R4 vitals target |
indicxlit | :8095/ | Tanglish → Tamil (optional) |
ollama | :11434/api/tags | local LLM fallback (optional) |
cloud LLM | TCP api.deepseek.com:443 | primary LLM reachability (optional) |
It reads URLs from .env and the environment, so non-default ports and a
different LLM provider are picked up automatically. "Required" probes fail the
exit code; "optional" ones only show off.
On top of the services it reads live operations from the running app
(/api/ops/state): units by status, active/total incidents, zones, traffic
disruptions, event sequence, sim time, and the SQLite database size.
Use it
make monitor # live, refreshing dashboard (Ctrl-C to stop)
make monitor-json # one snapshot as JSON; exit 1 if a required service is down
make monitor-prometheus # one-shot Prometheus text exposition
The HTTP exporter (/metrics, /healthz, / on :9101) runs as the monitor compose service.
Directly, with more control:
python scripts/monitor_stack.py --once # one table (auto in non-tty)
python scripts/monitor_stack.py --watch 5 # refresh every 5s
python scripts/monitor_stack.py --json | jq . # scripted checks
python scripts/monitor_stack.py --strict # also fail on optional services
python scripts/monitor_stack.py --serve --port 9101
make monitor-json is the CI/cron hook: it exits non-zero the moment a required
service is down, so a supervisor or cron job can alert on it.
History and dashboards (Prometheus + Grafana)
The terminal view is current-state. For history, alerting and graphs, the
monitor exporter (:9101), Prometheus (:9090) and Grafana (:3001, admin / GRAFANA_ADMIN_PASSWORD from .env)
start with the rest of the stack on docker compose up -d.
-
Prometheus (
infra/monitoring/prometheus.yml, 10s interval, 15 days of retention) scrapes two targets:monitor:9101, the exporter. It probes every service by its compose name (and native Ollama viahost.docker.internal) and flattens/api/ops/stateand/api/ops/analytics?window=24hinto gauges. It mounts./scriptsand./varread-only, so script edits apply ondocker compose restart monitor.- the api's own
/metricsathost.docker.internal:8001: HTTP traffic and latency histograms, bus events by type, SSE clients, webhooks, rate limiting, web vitals and every LLM call (LLMOps). The same address reaches the api container and the native api (make voice). - Alert rules from
infra/monitoring/rules/(LLMOps), at :9090/alerts.
-
Grafana auto-provisions the Prometheus datasource, the Vaazhvu · LLMOps dashboard (
vaazhvu-llmops.json, see LLMOps) and the Vaazhvu · Command centre dashboard (infra/monitoring/grafana/dashboards/vaazhvu.json, uidvaazhvu-stack). Its rows:- Command overview: stack health, required services down, active incidents, held for approval, EMS available, 8-min coverage, stress gauge, dispatch mode.
- Response performance (24h): call → dispatch and call → scene p50/p90 against the 480 s target, dispatch decisions, override rate, and the pipeline funnel (call → triage → policy → decision → assigned → hospital alerted → on scene).
- Incidents & triage: active incidents by severity, new calls, severity / channel / language / type mix, and active incidents needing attention.
- Fleet & coverage: EMS by status, utilisation by agency, ALS units ready, live coverage against the MEXCLP plan, coverage and demand per zone, units in motion with ETAs, and stress components.
- API edge: req/s by status class, p50/p95/p99 latency, error ratio, live connections, slowest routes, latency heatmap.
- Live event bus, Services & dependencies (availability timeline, inventory with uptime, probe latency) and Clients & storage (web vitals, client errors, webhooks, SQLite + WAL size).
Use the
routeandservicevariables to filter the panels. Annotations mark when a required service goes down, when dispatch leaves auto mode, and when stress passes 50%.
They stop with the rest of the stack on docker compose down (keeps data);
docker compose down -v also drops the Prometheus and Grafana volumes.
Logs (Loki + Promtail)
Every log line from the stack is searchable in one place. Promtail reads the output of every compose container
(through the Docker socket, labelled with its compose service) and the api's log files in ./var (the native api
under make voice writes var/voice-api.log, labelled service="api-native"), and ships them to Loki
(127.0.0.1:3100, 7 days kept in the loki-data volume). Grafana has Loki as a datasource next to Prometheus, and the command-centre dashboard ends with a Database · Postgres row
(size, owner lock, connections, transactions, rows, cache hits, biggest tables, locks; from postgres-exporter, queries in
infra/monitoring/postgres-exporter.yml) and a Logs · Loki row (error lines per service and a live error stream).
Grafana → Explore → Loki, then for example:
{service="api"} # the api container
{service="api-native"} |= "ERROR" # errors from the native voice api
{service="postgres"} # database log
{service=~"api|api-native"} |= "vaazhvu.llm.trace" # every LLM call's trace line (never a prompt or caller words)
sum by (service) (count_over_time({service=~".+"} |= "error" [5m])) # error rate per service
Config: infra/monitoring/loki.yml, infra/monitoring/promtail.yml. On first start Promtail may log a few
"entry too far behind" errors while it skips log lines older than Loki accepts; that is harmless. The monitor
(make monitor) shows Loki as an optional service.
Metrics exposed
| Metric | Meaning |
|---|---|
vaazhvu_service_up{service,role,required} | 1 if the probe answered |
vaazhvu_service_latency_ms{service} | probe round-trip |
vaazhvu_units{status} | fleet units by lifecycle status |
vaazhvu_incidents_active / _total | active and all incidents |
vaazhvu_zones | modelled response zones |
vaazhvu_traffic_disruptions | live traffic disruptions |
vaazhvu_event_seq | highest persisted event sequence |
vaazhvu_sim_time_seconds | live simulation clock |
vaazhvu_db_bytes{file} | SQLite DB and WAL size |
vaazhvu_incidents{status,severity} | incidents in live state |
vaazhvu_incidents_by_{channel,language,type,zone} | intake channel, caller language, incident type, zone name |
vaazhvu_active_incident_flags{flag} | active incidents that are human_required, escalated, have an unverified location, or are on manual hold |
vaazhvu_triage_confidence_mean | mean triage confidence |
vaazhvu_fleet_units{agency,level,status} | units by agency, ALS/BLS, and status |
vaazhvu_unit_eta_seconds{unit,purpose} | ETA of each moving unit |
vaazhvu_coverage_share, vaazhvu_zone_coverage{zone}, vaazhvu_fleet_plan_demand_covered | live, per-zone and planned coverage |
vaazhvu_stress_score, _level{level}, _component{component}, _detail{key} | system stress |
vaazhvu_degraded_components, vaazhvu_manual_mode, vaazhvu_clock_multiplier, vaazhvu_clock_paused | operating mode |
vaazhvu_response_seconds_24h{phase,stat} | call→dispatch / call→scene p50, p90, mean |
vaazhvu_decisions_24h{kind}, vaazhvu_override_rate_24h | engine recommendations and dispatcher actions |
vaazhvu_web_vital_p75_24h{metric}, vaazhvu_incidents_24h | browser vitals (ms; CLS unitless), call volume |
The api's own /metrics adds vaazhvu_http_requests_total,
vaazhvu_http_request_duration_seconds, vaazhvu_events_published_total{type},
vaazhvu_sse_clients, vaazhvu_webhook_deliveries_total, vaazhvu_client_errors_total,
the LLM series (vaazhvu_llm_*, vaazhvu_calltaker_*, see LLMOps),
vaazhvu_mcp_tool_calls_total{tool,outcome} (outcome ok, denied, refused, bad_arguments, error) and
vaazhvu_mcp_tool_duration_seconds{tool} for the MCP tools (AI access and the Copilot), and the other series in backend/app/observability/metrics.py.
LLMOps
(After 20 minutes of make llm-demo synthetic traffic.)
Every model call in the app is traced and measured: triage extraction (n self-consistency
samples), the AI call-taker's streamed turns, hospital profiling, health probes and
keep-warm pings. Every one of them goes through backend/app/llm/client.py, and the
client reports to backend/app/llm/telemetry.py, so no call is missed and no new
service is involved: the metrics are on the api's existing /metrics, scraped by the
same Prometheus and drawn by the same Grafana.
Nothing the caller said is recorded. Traces, metrics and logs hold no prompts,
transcripts, model output or keys: only sizes (characters), template hashes, error
classes, tokens and timings. A provider's error message is scrubbed of keys and cut short.
VAAZHVU_LLM_LOG_CONTENT=1 lets the call-taker's guard log quote what it dropped (local
debugging only).
Model
- Trace: one logical operation (
json,sampleof n, orstream), whichever provider served it (chatfor the Copilot's tool-calling rounds). It carries the operation (triage.extract,calltaker.reply,hospital.profile,copilot.turn), incident id, request id (X-Request-ID), channel, prompt version (name@version#hash), config version (a hash of every non-secret LLM setting), who served it (primary/fallback/only/none), the fallback reason, samples requested / returned, duration, and the tokens and cost of all its spans. - Span: one HTTP request to one provider: provider (
deepseek,ollama, …), model, role (primary/fallback/only), sample index, status (ok/error/cancelled), error class (timeout,connect,transport,no_credit,auth,rate_limited,http_4xx,http_5xx,bad_json,unavailable), HTTP status, latency, time to first token (streams), finish reason, tokens (prompt, completion, reasoning, cached prompt), cost, Ollama model load time, and whether the reader stopped early. - No retry loop exists in the client: a failed primary request is followed by the
fallback, which is the second span of the same trace. A provider that rejects
stream_optionsgets one repeat without it (also a second span).
Tokens come from the provider (usage for OpenAI-compatible APIs, including DeepSeek's
prompt_cache_hit_tokens; prompt_eval_count / eval_count for Ollama). Streamed
replies ask for usage with stream_options.include_usage (VAAZHVU_LLM_STREAM_USAGE=0
turns it off); a reply the call-taker stops reading early has no usage. Cost uses the
rupee prices in config/llmops.yaml (deepseek-flash: about US$0.60 per 100 M tokens = ₹0.528 per million at ₹88 / US$; local models cost 0; an unpriced model has tokens but no cost).
Where it shows
| Where | What |
|---|---|
Grafana Vaazhvu · LLMOps (/d/vaazhvu-llmops, linked from the Command centre) | Who is serving (cloud or local fallback), operations/min, error and fallback rate, triage p95 against the 15 s deadline, call-taker time to first token, spend and tokens; latency per operation and provider; fallback & provider-health timeline, fallbacks by reason, errors by class, deadline misses, sample yield; tokens and spend per model, prompt-cache share, usage table; call-taker turns (AI vs offline line) and guard drops; prompts and config in use. Filter by operation and model. Annotations mark fallback periods and triage deadline misses. |
Prometheus alerts (infra/monitoring/rules/llmops.yml, :9090/alerts) | LLMLocalFallbackServing (2 min), LLMOperationsFailing (>20% for 5 min), TriageLLMMissingDeadline, TriageLLMSlow (p95 > 10 s), CallTakerOffline (>30% offline line). No Alertmanager: they show in Prometheus and Grafana. |
GET /api/ops/llm (analytics.read) | Provider status, fallback state, prompts, config, per-operation stats and the latest traces with spans; ?incident_id= for one incident's calls, ?operation=. In memory (traces.buffer in config/llmops.yaml). |
| Logs | One line per finished trace on vaazhvu.llm.trace (llm <trace> <operation> <status> served_by=… model=… 1.23s attempts=… samples=5/5 tokens=…/… fallback=…); with VAAZHVU_LOG_FORMAT=json the line carries the whole trace under llm. Each operation's switch to the fallback logs a WARNING, its return an INFO. |
| Live bus + audit | Per operation (triage and the call-taker change over independently: the triage client parks a cloud that timed out for its 120 s health TTL, the call-taker builds a fresh client per turn): llm.fallback once the local model has served that operation fallback.announce_after times in a row (default 2, config/llmops.yaml; a single blip is only counted) for any cause (timeout, 5xx, lost link, no credit) and llm.recovered when the cloud answers it again, with primary, fallback, reason, operation and trace id; also an audit row. The dispatcher terminal shows them as notifications. Informational only: ops.degraded cloud_llm still covers a parked account, and dispatch behaviour does not change. |
| Incident | triage.explain.llm on every triage (trace id, who served it, samples, tokens, cost, prompt/config version, deadline_exceeded), so triage.completed and the incident record say which model produced the reading. |
Metrics (api /metrics)
| Metric | Labels | Meaning |
|---|---|---|
vaazhvu_llm_requests_total | provider, model, operation, kind, role, status | Provider requests (one per sample) |
vaazhvu_llm_request_duration_seconds | provider, model, operation, kind | Request latency histogram |
vaazhvu_llm_time_to_first_token_seconds | provider, model, operation | Streams: first text chunk |
vaazhvu_llm_errors_total | provider, model, operation, error | Failed requests by error class |
vaazhvu_llm_calls_total | operation, kind, served_by, status | Logical operations; fallback rate = served_by="fallback" share |
vaazhvu_llm_call_duration_seconds | operation, kind, served_by | Operation latency, fallback included |
vaazhvu_llm_fallbacks_total | operation, reason | Primary → local handovers |
vaazhvu_llm_fallback_active | operation | 1 while the local fallback serves that operation |
vaazhvu_llm_tokens_total | provider, model, operation, type | prompt, completion, reasoning, cached_prompt |
vaazhvu_llm_cost_inr_total | provider, model, operation | Estimated spend in rupees |
vaazhvu_llm_samples_total | operation, result | Self-consistency samples requested / returned |
vaazhvu_llm_skipped_total | operation, reason | No model answer: deadline, unavailable, disabled |
vaazhvu_llm_inflight_requests | provider | Requests in flight |
vaazhvu_llm_health_checks_total, vaazhvu_llm_provider_up | provider, model | Health probes and keep-warm pings |
vaazhvu_llm_prompt_info, vaazhvu_llm_config_info | prompt, version, hash / provider, model, fallback_model, version | Versions in use (value 1) |
vaazhvu_calltaker_turns_total | channel, source | Call-taker turns: ai, offline, cancelled |
vaazhvu_calltaker_sentences_dropped_total | reason | Guard drops: script, numbers |
Run it
make up # api + Prometheus (:9090) + Grafana (:3001); nothing extra to start
make llm-dashboard # opens Grafana "Vaazhvu · LLMOps"
make llm-status # latest traces + stats; N=20 INCIDENT=INC-... OPERATION=calltaker.reply
make llm-metrics # the raw vaazhvu_llm_* series
After editing config/llmops.yaml (prices) or the alert rules: make build for the api
image (it copies config/), docker compose restart prometheus for the rules. Prompt
versions: bump prompt_version in config/calltaker.yaml or the version in
PROMPT = llm_telemetry.prompt(...) (triage/extractor.py) when a prompt changes on
purpose; the content hash beside it changes on any edit anyway.
A new LLM call site needs nothing more than going through get_llm(); wrap it in
llm_telemetry.scope("<operation>", incident_id=..., prompt=...) so its traces are labelled.
Extending it
Add a probe in build_probes() in scripts/monitor_stack.py: a Probe is an
HTTP or TCP check with a required flag and an optional one-line detail
extractor. It appears in the table, JSON, Prometheus output and exporter
automatically. In-app aggregate health (/api/ops/health) and OpenTelemetry
traces are the natural next steps if per-request latency becomes the question
rather than per-service liveness. LLM calls already have their own traces (see LLMOps
above); their trace and span ids could be exported to an OTLP collector as they are.