# oarisar/maya architecture

> Architecture diagram of the GitHub repository oarisar/maya, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-06-27). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/oarisar/maya
- Repository: https://github.com/oarisar/maya

## Overview

1. **Repository shape**
   - This is a two-tier product: a **React/TypeScript frontend** in `frontend/` and a **FastAPI/Python backend** in `backend/`.
   - The application is a **maternal-health assistant** with a strong safety boundary: emergency detection happens **before** any retrieval or LLM generation.

2. **Frontend as the user interaction layer**
   - The frontend is built with **Vite, TanStack Router, Firebase Auth, and a component-heavy shadcn/ui setup**.
   - Major routes are `login`, `dashboard`, `chat`, `docs`, and `emergency`, which suggests the UI is organized around onboarding, ongoing care, document handling, and emergency escalation.
   - `src/lib/` contains client-side service wrappers for auth, chats, docs, theme, and Firebase, so the browser app is not just presentational; it also owns session state and persistence calls.

3. **Frontend data and state boundaries**
   - `src/contexts/lang-context.tsx` and `src/i18n/translations.ts` indicate the app supports **multilingual UI** at the presentation layer.
   - `frontend/src/data/hospitals.json` and the `EmergencyMap` component show that emergency guidance is partly backed by local structured data, not only backend AI.
   - The UI also includes pregnancy-specific views such as `PregnancyTracker`, `OnboardingFlow`, and `SettingsDialog`, which implies a persistent health profile is central to the UX.

4. **Backend as the orchestration layer**
   - The backend is organized into small responsibility-focused modules: `main.py` for API entrypoints, `auth.py` for identity/authorization, `safety.py` for emergency detection, `rag.py` for retrieval, `llm.py` for generation, and `docs_store.py` for document state/storage concerns.
   - This backend is not a general app server; it is the **decision engine** that checks safety, fetches evidence, builds prompts, and streams answers.

5. **Critical request flow**
   - The main conversational flow is: **frontend sends a query → backend safety check runs → if safe, retrieval runs → prompt is assembled with patient context and evidence → Groq LLM streams the answer back**.
   - The README explicitly says the safety classifier runs **before RAG and before the LLM**, so the architecture has a hard safety gate at the top of the inference path.
   - Responses are streamed, so the backend likely returns **SSE/token deltas** rather than waiting for a full completion.

6. **Safety is a first-class subsystem**
   - `backend/safety.py` implements a deterministic-ish emergency classifier tuned for maternal red flags.
   - If emergency patterns are detected, the system **short-circuits** normal generation and returns a structured emergency response.
   - This is the most important architectural boundary in the repo: it prevents the generative model from being the first responder in a crisis.

7. **Retrieval-Augmented Generation boundary**
   - `backend/rag.py` connects the assistant to a **Pinecone vector index** containing curated medical knowledge.
   - The knowledge base is split into multiple namespaces for source separation, including WHO, ACOG, CDC, NHS, and related maternal-health references.
   - Retrieved chunks carry metadata such as source title, URL, and section context so citations can be surfaced in the UI.

8. **LLM and prompt assembly**
   - `backend/llm.py` is the generation layer, using **Groq-hosted Llama 3.3** according to the README.
   - Prompt construction is trimester-aware and includes chat history plus retrieved evidence; this makes the model context-rich but still constrained by retrieved sources.
   - Citations are returned separately from the answer text, which is a useful architectural split for UI rendering and auditability.

9. **Persistent health and chat data**
   - The app uses **Firebase Authentication** for Google sign-in and **Firebase Realtime Database** for user data persistence.
   - The persisted data appears to include: pregnancy profile, medications, chat history, onboarding answers, reminders, and possibly document-derived health facts.
   - `frontend/src/lib/firebase.ts` and the backend auth module indicate auth is a shared boundary: the frontend handles sign-in, while the backend likely verifies identity or permissions with service credentials.

10. **Medical document upload and extraction path**
    - Upload handling is a distinct subsystem: lab reports and prescriptions are parsed from PDFs, then extracted values are folded into the user’s health profile and medication list.
    - The backend uses `pdfplumber` for PDF extraction, and the README says lab extraction and report summarization run in parallel with `asyncio.gather()`.
    - This means uploads are not treated as just files; they are a data-ingestion path feeding the same longitudinal health model used by chat and tracking views.

11. **Offline knowledge ingestion pipeline**
    - The `notebooks/` folder contains scraping and chunking notebooks for web sources and embeddings, which signals that the knowledge base is built **offline**, not dynamically at request time.
    - The vector content is prepared from authoritative sources, chunked by section, embedded with `BAAI/bge-m3`, and then upserted to Pinecone.
    - This separation keeps runtime chat fast and stable while pushing heavy extraction/indexing work into preprocessing jobs.

12. **Deployment and runtime footprint**
    - The backend is Dockerized via `backend/Dockerfile`, while the frontend has deployment config for **Cloudflare Workers / Vercel-style hosting** (`wrangler.jsonc`, `vercel.json`).
    - That suggests a split deployment model: static/frontend delivery at the edge, plus an API backend hosted separately.
    - The runtime dependencies are therefore externalized: Firebase for identity/data, Groq for inference, and Pinecone for retrieval.

13. **What to emphasize in an architecture diagram**
    - Draw three major zones: **client UI**, **Python API/orchestrator**, and **external services**.
    - Inside the backend, show the sequence: **auth/safety → retrieval → prompt/LLM → streamed response**.
    - Show side flows from the frontend to Firebase for persistence, and from offline notebooks/backend utilities to Pinecone for knowledge ingestion.
    - Make the safety gate visually dominant, since it is the defining architectural choice of the system.

Main entry points: [`frontend/src`](https://github.com/oarisar/maya/tree/main/frontend/src) (Frontend), [`backend/main.py`](https://github.com/oarisar/maya/blob/main/backend/main.py) (API Server), [`backend/llm.py`](https://github.com/oarisar/maya/blob/main/backend/llm.py) (LLM Stream), [`frontend/src/routes/chat.tsx`](https://github.com/oarisar/maya/blob/main/frontend/src/routes/chat.tsx) (Chat)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_client["Client UI"]
  node_frontend_app["Frontend<br/>React/Vite app"]
  node_login_route["Login<br/>route<br/>[login.tsx]"]
  node_dashboard_route["Dashboard<br/>route<br/>[dashboard.tsx]"]
  node_chat_route["Chat<br/>route<br/>[chat.tsx]"]
  node_docs_route["Docs<br/>route<br/>[docs.tsx]"]
  node_emergency_route["Emergency<br/>route<br/>[emergency.tsx]"]
  node_ui_components["UI Kit<br/>shadcn/ui components"]
  node_health_widgets["Health Widgets<br/>pregnancy UI"]
  node_client_libs["Client Services<br/>frontend services"]
  node_lang_state(("Language State<br/>i18n/contexts<br/>[lang-context.tsx]"))
end

subgraph group_api["Python API"]
  node_api_main["API Server<br/>FastAPI entrypoint<br/>[main.py]"]
  node_auth_mod["Auth<br/>identity boundary<br/>[auth.py]"]
  node_safety_mod{{"Safety Gate<br/>emergency classifier<br/>[safety.py]"}}
  node_rag_mod[("Retrieval<br/>Pinecone RAG<br/>[rag.py]")]
  node_llm_mod(("LLM Stream<br/>Groq generation<br/>[llm.py]"))
  node_docs_store_mod["Docs Store<br/>document state<br/>[docs_store.py]"]
end

subgraph group_external["External Services"]
  node_firebase[("Firebase<br/>auth + realtime db")]
  node_pinecone[("Pinecone<br/>vector index")]
  node_groq(("Groq LLM<br/>hosted model"))
end

subgraph group_offline["Offline Ingestion"]
  node_notebooks["Notebooks<br/>offline ingestion"]
end

node_frontend_app -->|"route"| node_login_route
node_frontend_app -->|"route"| node_dashboard_route
node_frontend_app -->|"route"| node_chat_route
node_frontend_app -->|"route"| node_docs_route
node_frontend_app -->|"route"| node_emergency_route
node_frontend_app -->|"renders"| node_ui_components
node_frontend_app -->|"renders"| node_health_widgets
node_frontend_app -->|"uses"| node_client_libs
node_frontend_app -->|"localizes"| node_lang_state
node_client_libs -->|"syncs"| node_firebase
node_docs_route -->|"updates"| node_docs_store_mod
node_chat_route -->|"chat api"| node_api_main
node_api_main -->|"checks"| node_auth_mod
node_api_main -->|"first"| node_safety_mod
node_safety_mod -.->|"short-circuit"| node_llm_mod
node_api_main -->|"retrieves"| node_rag_mod
node_rag_mod -->|"queries"| node_pinecone
node_api_main -->|"generates"| node_llm_mod
node_llm_mod -->|"calls"| node_groq
node_docs_store_mod -->|"persists"| node_firebase
node_notebooks -->|"builds"| node_pinecone
node_frontend_app -->|"auth/data"| node_firebase

click node_frontend_app "https://github.com/oarisar/maya/tree/main/frontend/src"
click node_login_route "https://github.com/oarisar/maya/blob/main/frontend/src/routes/login.tsx"
click node_dashboard_route "https://github.com/oarisar/maya/blob/main/frontend/src/routes/dashboard.tsx"
click node_chat_route "https://github.com/oarisar/maya/blob/main/frontend/src/routes/chat.tsx"
click node_docs_route "https://github.com/oarisar/maya/blob/main/frontend/src/routes/docs.tsx"
click node_emergency_route "https://github.com/oarisar/maya/blob/main/frontend/src/routes/emergency.tsx"
click node_ui_components "https://github.com/oarisar/maya/tree/main/frontend/src/components/ui"
click node_health_widgets "https://github.com/oarisar/maya/tree/main/frontend/src/components"
click node_client_libs "https://github.com/oarisar/maya/tree/main/frontend/src/lib"
click node_lang_state "https://github.com/oarisar/maya/blob/main/frontend/src/contexts/lang-context.tsx"
click node_api_main "https://github.com/oarisar/maya/blob/main/backend/main.py"
click node_auth_mod "https://github.com/oarisar/maya/blob/main/backend/auth.py"
click node_safety_mod "https://github.com/oarisar/maya/blob/main/backend/safety.py"
click node_rag_mod "https://github.com/oarisar/maya/blob/main/backend/rag.py"
click node_llm_mod "https://github.com/oarisar/maya/blob/main/backend/llm.py"
click node_docs_store_mod "https://github.com/oarisar/maya/blob/main/backend/docs_store.py"
click node_notebooks "https://github.com/oarisar/maya/tree/main/notebooks"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_frontend_app,node_login_route,node_dashboard_route,node_chat_route,node_docs_route,node_emergency_route,node_ui_components,node_health_widgets,node_client_libs,node_lang_state toneBlue
class node_api_main,node_auth_mod,node_safety_mod,node_rag_mod,node_llm_mod,node_docs_store_mod toneAmber
class node_firebase,node_pinecone,node_groq toneMint
class node_notebooks toneRose
```

## Components

### Client UI

React/TypeScript app for onboarding, chat, tracking, and emergency guidance.

- [Frontend](https://github.com/oarisar/maya/tree/main/frontend/src): React/Vite app · Browser app with routed maternal-health workflows and local UI state. · `frontend/src`
- [Login](https://github.com/oarisar/maya/blob/main/frontend/src/routes/login.tsx): route · Authentication entry and onboarding to the app. · `frontend/src/routes/login.tsx`
- [Dashboard](https://github.com/oarisar/maya/blob/main/frontend/src/routes/dashboard.tsx): route · Main health overview and pregnancy status surface. · `frontend/src/routes/dashboard.tsx`
- [Chat](https://github.com/oarisar/maya/blob/main/frontend/src/routes/chat.tsx): route · Conversational assistant interface for maternal-health support. · `frontend/src/routes/chat.tsx`
- [Docs](https://github.com/oarisar/maya/blob/main/frontend/src/routes/docs.tsx): route · Document upload and record review workspace. · `frontend/src/routes/docs.tsx`
- [Emergency](https://github.com/oarisar/maya/blob/main/frontend/src/routes/emergency.tsx): route · Emergency guidance and escalation screen. · `frontend/src/routes/emergency.tsx`
- [UI Kit](https://github.com/oarisar/maya/tree/main/frontend/src/components/ui): shadcn/ui components · Reusable presentation components used across the app. · `frontend/src/components/ui`
- [Health Widgets](https://github.com/oarisar/maya/tree/main/frontend/src/components): pregnancy UI · Pregnancy tracker, onboarding flow, settings, and emergency map. · `frontend/src/components`
- [Client Services](https://github.com/oarisar/maya/tree/main/frontend/src/lib): frontend services · Browser wrappers for auth, chats, docs, theme, and Firebase. · `frontend/src/lib`
- [Language State](https://github.com/oarisar/maya/blob/main/frontend/src/contexts/lang-context.tsx): i18n/contexts · Multilingual UI context and translations. · `frontend/src/contexts/lang-context.tsx`

### Python API

FastAPI backend that gates safety, retrieval, and generation.

- [API Server](https://github.com/oarisar/maya/blob/main/backend/main.py): FastAPI entrypoint · Backend entrypoint wiring auth, safety, RAG, and response streaming. · `backend/main.py`
- [Auth](https://github.com/oarisar/maya/blob/main/backend/auth.py): identity boundary · Backend-side identity and authorization handling. · `backend/auth.py`
- [Safety Gate](https://github.com/oarisar/maya/blob/main/backend/safety.py): emergency classifier · Deterministic maternal-red-flag detection that short-circuits unsafe requests. · `backend/safety.py`
- [Retrieval](https://github.com/oarisar/maya/blob/main/backend/rag.py): Pinecone RAG · Fetches curated medical evidence from indexed namespaces. · `backend/rag.py`
- [LLM Stream](https://github.com/oarisar/maya/blob/main/backend/llm.py): Groq generation · Builds prompt context and streams answer tokens. · `backend/llm.py`
- [Docs Store](https://github.com/oarisar/maya/blob/main/backend/docs_store.py): document state · Document-derived health facts and persistence helpers. · `backend/docs_store.py`

### External Services

Hosted identity, persistence, vector search, and LLM services.

- **Firebase**: auth + realtime db · User identity and persistent app data storage.
- **Pinecone**: vector index · Curated maternal-health knowledge namespaces and metadata.
- **Groq LLM**: hosted model · Hosted Llama 3.3 inference used for response generation.

### Offline Ingestion

Preprocessing notebooks that build the knowledge base.

- [Notebooks](https://github.com/oarisar/maya/tree/main/notebooks): offline ingestion · Web scraping, chunking, and embedding preparation jobs. · `notebooks`

## Connections

- Frontend → Login: route · Initial onboarding and sign-in entry.
- Frontend → Dashboard: route · Main health overview navigation.
- Frontend → Chat: route · Conversation workspace.
- Frontend → Docs: route · Document management workspace.
- Frontend → Emergency: route · Emergency guidance path.
- Frontend → UI Kit: renders · Shared UI primitives.
- Frontend → Health Widgets: renders · Pregnancy-specific experience surfaces.
- Frontend → Client Services: uses · Client-side auth, chat, docs, theme, and Firebase wrappers.
- Frontend → Language State: localizes · Language context and translation state.
- Client Services → Firebase: syncs · Authentication and persistent user data.
- Docs → Docs Store: updates · Document upload and extracted health facts.
- Chat → API Server: chat api · Sends user questions to the backend orchestrator.
- API Server → Auth: checks · Identity and permission boundary.
- API Server → Safety Gate: first · Emergency detection runs before retrieval and generation.
- Safety Gate → LLM Stream: short-circuit · Unsafe cases bypass normal generation and return emergency guidance.
- API Server → Retrieval: retrieves · Evidence lookup for safe requests.
- Retrieval → Pinecone: queries · Vector search over curated maternal-health sources.
- API Server → LLM Stream: generates · Prompt assembly and streamed response path.
- LLM Stream → Groq LLM: calls · Hosted Llama 3.3 inference.
- Docs Store → Firebase: persists · Longitudinal user records and extracted document state.
- Notebooks → Pinecone: builds · Offline scraping, chunking, embedding, and upsert pipeline.
- Frontend → Firebase: auth/data · Sign-in and user-state synchronization.
