Repos Health Triage
HT Health Triage
Health Triage: a health-guidance mobile app whose backend takes symptoms, voice notes and medical documents, runs an asynchronous AI triage pipeline (speech-to-text, OCR, Gemini), and sells monthly plans and one-time top-ups through Google Play and the App Store.
- Stack
- Python 3.11, FastAPI, gunicorn + uvicorn workers, MongoDB (Motor async + PyMongo sync), Redis (rate limits, OTP, pub/sub, Celery broker), Celery + beat, AWS S3, Google Gemini / Vertex AI, Sarvam STT, Firebase Cloud Messaging, Resend email, Google Play Billing + App Store Server API, Sentry, nginx + certbot, Docker Compose on EC2, GitHub Actions, Flutter / Dart client
- Examples
- 32: 29 solid, 2 naive, 1 missing
- Chapters
- 11 of 34
- Who wrote it
- Backend branch: 12 of 117 commits (a teammate, has 104). Gaurav's backend work by lines added: FRONTEND_API_ANALYSIS.md (456, sole author), app/services/user_export_pdf.py (359 of 893), tests/test_apple_revoke.py (179, sole author), scripts/add_apple_product_ids.py (162) and scripts/check_duplicate_emails.py (68), app/core/apple_revoke.py (158, sole author), app/routes/auth/users.py (~104, export + Apple revocation wiring), app/workers/celery_app.py (~25), plus small edits in app/config.py, app/core/file.py, app/services/subscription_service.py and the *.p8 gitignore rule. No commits in app/routes/assessment, app/workers/tasks.py, billing, webhooks, db or infra files. Frontend branch: 75 of 101 commits (55 of 76 touching frontend/); sole or main author of lib/core/api_client.dart, fcm_service.dart, media_service.dart, feature_flags_service.dart, analysis_screen.dart, assessment_service.dart, auth_service.dart and the frontend CI workflows.
How the AI path is built
The Flutter app calls https://api.../api/v1 through nginx (TLS termination, forwarded headers, a no-buffering location for SSE), which proxies to three gunicorn/uvicorn workers running one FastAPI app. Requests pass RequestId, TrustedHost, CORS and SecurityHeaders middleware, then per-route dependencies (JWT + session lookup, plan entitlements, Redis fixed-window rate limits). Handlers talk to MongoDB directly through module-level Motor collections; billing logic sits in a service module. Slow work (speech-to-text, OCR, Gemini triage and final analysis, vision, push notifications) is enqueued to Celery over Redis and executed by a 16-thread worker using sync PyMongo/Redis clients; progress is written to the assessment document and published on Redis pub/sub, which the API relays to the client as Server-Sent Events with polling as fallback. Files go client to S3 via presigned URLs. Google Play (Pub/Sub push) and Apple (signed JWS) webhooks update subscriptions idempotently, with an hourly reconcile job as backstop. Everything runs as docker compose services (nginx, certbot, api, worker, beat) on a single EC2 host, deployed by a GitHub Actions workflow that builds, pushes and SSHes in; logs go to CloudWatch and errors to Sentry. NOTE: the evidence entries in this file are re-mapped from the backend edition (bfp-annotated) to the AI Engineering chapters; there is no local copy of the repo, so the lines and snippets could not be re-verified locally for this edition.
Every example, by chapter
11Serving, Model Selection and Economics● 1Read with these
HTDependency injection: auth result feeds a per-user limiter●
def per_api_rate_limit(limit: int, window: int = 60):
limiter = RedisRateLimiter(
key_prefix="endpoint",
limit=limit,
window=window
)
async def dependency(
request: Request,
user=Depends(auth_required)
):
identifier = f"{user['_id']}:{request.url.path}"
await limiter.check(identifier)
return dependencyper_api_rate_limit is a factory that returns a dependency; that dependency itself depends on auth_required and keys the limiter by user id + path.
Lesson auth_required is resolved once per request by FastAPI's dependency cache, which is what keeps this cheap.
12Prompting Fundamentals● 1Read with these
HTPrompt-level constraints●
CONSTRAINTS:
- Return ONLY JSON. No markdown, no backticks, no extra text.
- The "is_medical" field is REQUIRED and must be a boolean.
- If is_medical is false, DO NOT include any analysis fields (no observations, no interpretations, no next_steps).
- If is_medical is true, ALL accepted-schema fields are REQUIRED.
- Never "try to be helpful" with non-medical images. Reject them.The prompt fixes the output contract (JSON only, required boolean, no analysis when rejecting).
13Structured Output● 1Read with these
HTValidating model output before trusting it●
try:
result = json.loads(text)
except json.JSONDecodeError:
raise RuntimeError("Invalid JSON from Gemini triage")
if "questions" not in result or not result["questions"]:
raise RuntimeError("Triage response missing questions")
return resultThe triage response must parse as JSON and contain questions, otherwise the task fails and is retried.
Lesson The final analysis is stored unvalidated as rawMarkdown and parsed at read time with a fallback.
14Multimodal and Realtime Voice● 0 ◐ 1Read with these
HTBlocking requests call with only a coarse timeout◐
try:
resp = requests.post(
SARVAM_URL,
headers=headers,
files=files,
data=data,
timeout=120,
)
resp.raise_for_status()The Sarvam speech-to-text call uses requests with a single 120s timeout, after downloading the whole audio file into memory.
Lesson Split connect/read timeouts and stream the upload.
22The Agent Loop and Architectures● 3Read with these
HTTwo-stage LLM workflow with a human answer in between●
try:
triage_result = run_gemini_triage(assessment_id)
questions = triage_result.get("questions", [])
confidence = float(triage_result.get("top_confidence", 0.5))
confidence = max(0.0, min(1.0, confidence))
update_fields = {
"processing.triage": "done",
"processing.triageUpdatedAt": now_utc(),
"status": "awaiting_answers",
"triageResult": {Stage one (triage) produces an internal assessment and 2-3 questions and parks the job in awaiting_answers; the user's answers trigger stage two.
Lesson A fixed sequential workflow, not an agent loop: no tool calling and no model-chosen next step.
HTDocument model: one assessment document holds its pipeline state●
doc = {
"_id": assessment_oid,
"userId": ObjectId(user["_id"]),
"profileId": ObjectId(req.profileId),
"weight": user.get("weight"),
"height": user.get("height"),
"age": user.get("age"),
"gender": user.get("gender"),
"symptoms": req.symptoms,
"bodyPartsAnterior": req.bodyPartsAnterior,
"bodyPartsPosterior": req.bodyPartsPosterior,
"initialVoiceKey": req.initialVoiceKey,
"attachments": req.attachments or [],
"attachmentsText": [An assessment is a single Mongo document with embedded arrays (symptoms, attachmentsText with per-file status) and references (userId, profileId) to other collections.
Lesson Age/weight/height are copied from the user, not the profile the assessment is for.
HTOptional stage failure does not sink the whole job●
except _RateLimitExhausted:
# STT is optional — mark it failed and let the AI proceed with whatever
# text/OCR input exists, matching the ordinary STT failure path below.
assessments.update_one(
{"_id": oid, "processing.stt": {"$in": ["queued", "running"]}},
{"$set": {"processing.stt": "failed", "processing.sttUpdatedAt": now_utc()}},
)
maybe_trigger_ai(assessment_id)
returnIf speech-to-text cannot get a rate-limit slot it is marked failed and the AI step still runs with typed text and OCR.
23Memory● 1Read with these
HTBounded context: rolling summary plus last six messages●
last_msgs = list(
messages.find({"assessmentId": oid})
.sort("createdAt", -1)
.limit(6)
)
payload = build_analysis_prompt(
assessment=assessment,
summary=assessment.get("conversationSummary"),
last_messages=last_msgs,
)
text = _call_gemini(
model=GEMINI_MODEL,
contents=[{"role": "user", "parts": [{"text": payload[:12000]}]}],
config={"response_mime_type": "application/json"},Follow-ups send a maintained bullet summary and only the last six messages, truncated to 12,000 characters, with JSON response mode.
Lesson Truncating the assembled prompt by characters can cut the instructions' tail.
29Guardrails and Safety● 1Read with these
HTGuardrail: the model must classify the image as medical first●
if not isinstance(parsed, dict) or parsed.get("is_medical") is not True:
reason = (
(isinstance(parsed, dict) and parsed.get("rejection_reason"))
or "Only medical images are supported. Please upload a scan, lab report, "
"prescription, or a photo of a physical medical concern."
)
detected = parsed.get("detected_content") if isinstance(parsed, dict) else None
raise NotMedicalImageError(reason, detected)Unless the JSON says is_medical is true the result is discarded and a typed rejection is raised.
30Observability● 3Read with these
HTRequest id accepted, generated and echoed●
incoming = request.headers.get(_HEADER)
rid = incoming if incoming else uuid.uuid4().hex
token = request_id_ctx.set(rid)
with sentry_sdk.configure_scope() as scope:
scope.set_tag("request_id", rid)An incoming X-Request-Id is reused or a UUID generated; it is put in the ContextVar, tagged on the Sentry scope and returned in the response header.
Lesson The incoming header is trusted verbatim (no length/charset check).
HTPropagating the request id across the task queue●
@before_task_publish.connect
def _inject_request_id(headers=None, **kwargs):
"""API side: attach the current request_id to the outgoing task headers."""
rid = request_id_ctx.get()
if rid and headers is not None:
headers["request_id"] = rid
@task_prerun.connect
def _bind_request_id(task_id=None, task=None, **kwargs):
"""Worker side: pull request_id from the task message and set ContextVar."""
rid = None
req = getattr(task, "request", None)
if req is not None:
rid = (getattr(req, "headers", None) or {}).get("request_id")
if not rid:A before_task_publish hook copies the request id into Celery message headers and task_prerun restores it into the ContextVar in the worker, so API and worker logs share one id.
HTScrubbing sensitive keys before events leave the process●
def _scrub(value: Any) -> Any:
if isinstance(value, dict):
return {
k: (_REDACTED if k.lower().replace("-", "").replace("_", "") in _SENSITIVE_KEYS else _scrub(v))
for k, v in value.items()
}
if isinstance(value, list):
return [_scrub(v) for v in value]
return valueA recursive scrubber redacts any dict key in a deny-list (tokens, OTP, phone, purchase tokens) from Sentry payloads.
Lesson Meanwhile auth_required sets the Sentry user email and otp.py logs the recipient address.
31Cost and Latency Engineering● 4Read with these
HTService layer for quota logic●
if limit > 0:
_res = await _charge_plan_counter(user_id, period, metric, limit, now)
if _res:
await _record_charge_source(ref_id, user_id, metric, "plan", now)
return
# Plan quota exhausted (or zero) for this cycle. Draw from the durable top-up
# balance (reserve). Only metrics in _TOPUP_METRICS have balances.
if await _try_consume_topup(user_id, metric):
await _record_charge_source(ref_id, user_id, metric, "topup", now)
return
# No plan quota and no top-up balance → genuinely over limit.
raise HTTPException(403, f"{metric} limit exceeded")check_and_increment_usage owns the business rule 'spend plan quota first, then top-up balance, else 403'; routes just call it.
Lesson The service raises HTTPException, coupling it to the web layer (workers have to catch HTTPException from the limiter for the same reason).
HTDurable ledger separate from the subscription record●
res = await topup_balances.update_one(
{
"userId": user_id,
"metric": metric,
"applied.purchaseToken": {"$ne": purchase_token},
},
{
"$inc": {"remaining": n, "grantedTotal": n},
"$set": {"updatedAt": now},Top-up credits live in their own collection and are applied once per purchase token via a $ne guard.
HTCost and safety controls around the model●
gemini_limit = RedisRateLimiterSync(
key_prefix="gemini",
limit=GEMINI_RATE_LIMIT_PER_MIN,
window=60
)A global per-minute limiter, per-plan quotas, kill switches and a queue-depth gate sit in front of every model call.
Lesson No evals or recorded prompts to detect quality regressions.
HTCompensation: refund the credit when the job fails for good●
def _refund_assessment_credit(oid: ObjectId, assessment_id: str) -> None:
"""Refund one assessments_per_month credit. Call only after all retries are exhausted."""
doc = assessments.find_one({"_id": oid}, {"userId": 1})
if not doc:
return
try:
# ref_id is the assessment id — routes the refund to the exact bucket
# (plan counter vs top-up balance) the credit was charged from.
refund_usage_sync(doc["userId"], "assessments_per_month", ref_id=assessment_id)
except Exception:
logger.exception("Failed to refund assessment credit for %s", assessment_id)When retries are exhausted the worker refunds the usage credit, routed by the assessment id to the bucket it was charged from.
32Deployment and LLMOps● 12 ◐ 1 ○ 1Read with these
HTFeature flags and kill switches stored in the database●
stt_enabled: bool = True
vision_enabled: bool = True
ai_enabled: bool = True
symptom_check_enabled: bool = True
nearby_places_enabled: bool = True
download_enabled: bool = True
# Kill switches (emergency hard-stop)
stt_kill: bool = False
vision_kill: bool = False
ai_kill: bool = False
nearby_places_kill: bool = FalseEach capability has an enabled flag and a separate kill flag, editable at runtime through PATCH /config and checked before enqueuing work.
HTChained stages: ingest fans in to triage●
# Trigger triage (which later leads to user Q&A then final AI)
res = assessments.update_one(
{"_id": oid, "processing.triage": {"$nin": ["queued", "running", "done"]}},
{"$set": {"processing.triage": "queued", "processing.triageUpdatedAt": now_utc()}},
)
if res.modified_count:
fresh = _fetch_for_progress(oid) or assessment
step_map, total = _compute_pipeline_steps(fresh)
publish_event(build_event(
assessment_id=assessment_id,
type_=SSEEventType.TRIAGE_QUEUED,
step=step_map["triage"],
total_steps=total,
assessment=fresh,After every STT/OCR completion maybe_trigger_ai checks whether all inputs are terminal and, using a conditional update as the latch, enqueues triage exactly once.
HTConsumer with automatic retry and backoff●
@celery_app.task(bind=True, autoretry_for=(Exception,), retry_backoff=10, retry_kwargs={"max_retries": 3})
def triage_task(self, assessment_id: str):
"""First AI call: internal assessment + generate MCQ follow-up questions."""
oid = ObjectId(assessment_id)
try:
_await_rate_limit(self, gemini_limit)
except _RateLimitExhausted:
_fail_assessment_ai(oid, assessment_id, SSEEventType.TRIAGE_FAILED, "triage")
returntriage_task is a bound Celery task that retries any exception up to 3 times with exponential backoff starting at 10s.
Lesson autoretry_for=(Exception,) also retries permanent errors such as invalid JSON from the model.
HTProducer: mark queued atomically, then enqueue●
res = await assessments.update_one(
{"_id": ObjectId(assessment_id), "processing.stt": {"$nin": ["queued", "running"]}},
{"$set": {"processing.stt": "queued", "processing.sttUpdatedAt": now_utc()}},
)
if res.modified_count:
stt_task.delay(assessment_id)
tasks_triggered.append("stt")
stt_queued = TrueThe handler flips processing.stt to queued only if not already queued/running and enqueues the Celery task only when that update matched.
HTSSE client written by hand●
final client = http.Client();
try {
final request = http.Request('GET', uri);
request.headers['Accept'] = 'text/event-stream';
if (token != null && token.isNotEmpty) {
request.headers['Authorization'] = 'Bearer $token';
}
final response = await client.send(request);
if (response.statusCode < 200 || response.statusCode >= 300) {
throw ApiException('SSE connect failed', response.statusCode);
}The Flutter client opens a streamed GET with Accept: text/event-stream and a Bearer header, then parses lines into events itself.
HTServer-Sent Events endpoint●
async def gen():
pubsub = r.pubsub(ignore_subscribe_messages=True)
await pubsub.subscribe(channel)
start = asyncio.get_event_loop().time()
try:
yield {
"event": "update",
"data": SSEEvent(
v=1,
type="OPEN",
assessmentId=assessment_id,
payload=None,
ts=now_utc(),
).model_dump_json()An async generator subscribes to the Redis channel and yields an OPEN event, wrapped by EventSourceResponse.
HTClient disconnect cancels the stream and cleans up●
except asyncio.CancelledError:
pass
finally:
await pubsub.unsubscribe(channel)
await pubsub.close()When the client goes away the SSE generator is cancelled; the finally block unsubscribes and closes the Redis pub/sub connection.
HTRedis as the backplane between workers and API processes●
fresh = _fetch_for_progress(oid)
publish_event(build_event(
assessment_id=assessment_id,
type_=SSEEventType.STT_RUNNING,
assessment=fresh,
))The worker that does the job is a different process from the one holding the HTTP stream, so events travel through Redis.
HTStream lifecycle: forward, detect terminal event, close◐
msg = await pubsub.get_message(ignore_subscribe_messages=True, timeout=5.0)
if msg and msg.get("type") == "message":
raw = msg["data"]
SSEEvent.model_validate_json(raw)
yield {"event": "update", "data": raw}
# Auto-close on terminal events
evt = SSEEvent.model_validate_json(raw)
if evt.type in (
SSEEventType.AI_DONE, SSEEventType.AI_FAILED,
SSEEventType.FOLLOWUP_DONE, SSEEventType.FOLLOWUP_FAILED,
):
break
await asyncio.sleep(0.5)Each message is validated and forwarded; the loop ends on a terminal event or after 5 minutes.
Lesson Each event is parsed twice, there is an extra 0.5s sleep per iteration, and each client holds its own Redis connection.
HTGlobal rate limit inside workers with spaced retries●
try:
limiter.check(identifier)
except HTTPException:
try:
raise task.retry(countdown=_RATE_LIMIT_RETRY_COUNTDOWN)
except MaxRetriesExceededError as exc:
logger.error(
"%s: gave up waiting on '%s' rate limiter after %s retries",
task.name, limiter.key_prefix, task.request.retries,
)
raise _RateLimitExhausted(
f"{limiter.key_prefix} rate limit saturated"
) from excBefore calling Gemini the task reserves a slot on a shared Redis limiter; if saturated it retries after 30s and, once retries run out, raises a typed error so the caller can mark the job failed.
HTBack-pressure: reject new work when queues are deep●
ingest_depth = await r.llen(f"{Q}ingest")
ai_depth = await r.llen(f"{Q}ai")
if max(ingest_depth, ai_depth) > features.max_queue_depth:
raise HTTPException(429, "System is busy. Try again later.")Before enqueuing, the API reads the Redis list length of both queues and returns 429 if it exceeds an admin-configurable max_queue_depth.
HTOne quick retry with jitter for transient model errors●
except RETRYABLE_EXCEPTIONS as e:
last_exc = e
if attempt < MAX_GEMINI_RETRIES:
wait = 1 + random.uniform(0, 1)
logger.warning(
"Gemini call attempt %d failed (%s), retrying in %.1fs",
attempt + 1, type(e).__name__, wait,
)
time.sleep(wait)
else:
raiseOnly 503/429/connection errors are retried, once, after 1-2s of jittered sleep; longer backoff is left to Celery's task-level retry.
HTGraceful degradation switches●
if not stt_queued and not ocr_queued:
if features.ai_enabled and not features.ai_kill:
res = await assessments.update_one(
{"_id": ObjectId(assessment_id), "processing.triage": {"$nin": ["queued", "running", "done"]}},
{"$set": {"processing.triage": "queued", "processing.triageUpdatedAt": now_utc()}},
)
if res.modified_count:
triage_task.delay(assessment_id)
tasks_triggered.append("triage")With the AI flag off or kill switch on, assessments are still accepted and ingested; only the AI stage is skipped.
HTCircuit breaker written but never used○
def is_open(self) -> bool:
open_until = r.get(self._open_until_key())
if not open_until:
return False
return time.time() < float(open_until)
def record_success(self):
r.delete(self._fail_key())
r.delete(self._open_until_key())
def record_failure(self):
fails = r.incr(self._fail_key())
if fails >= self.fail_threshold:
r.set(self._open_until_key(), time.time() + self.reset_timeout)A Redis-backed CircuitBreaker class exists (failure counter, open-until timestamp) but nothing imports it, so a provider outage is absorbed only by retries and rate limits.
Lesson Wrap _call_gemini and the Sarvam call with it, or delete it.
34Product UX for AI and the Feedback Loop● 2Read with these
HTVersioned event schema for the SSE stream●
class SSEEvent(BaseModel):
v: Literal[1] = 1
type: SSEEventType
assessmentId: str
payload: Optional[Dict[str, Any]] = None
step: Optional[int] = None
totalSteps: Optional[int] = None
percent: Optional[int] = Field(default=None, ge=0, le=100)
ts: datetimeEvery server-sent event is an SSEEvent with a version field, an enum type, optional step/percent and a timestamp; workers serialize it with .json() and the API re-validates it before forwarding.
HTFallback to polling when the stream fails●
onError: (_) {
_startPollingFallback();
},
onDone: () {
if ((_status?.isTerminal ?? false) == false &&
!_isAssessmentFailed) {
_startPollingFallback();
}
},
cancelOnError: false,
);
if (!mounted) return;
setState(() {});
}SSE is primary; on error or early close the screen starts a 3-second polling timer against /status.
Lesson No Last-Event-ID resume; the fallback re-fetches full status instead.