# dk-krishna2001/trisoul-ai architecture

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

- Interactive diagram: https://gitdiagram.com/dk-krishna2001/trisoul-ai
- Repository: https://github.com/dk-krishna2001/trisoul-ai

## Overview

1. **What this repo is**
Trisoul AI is an academic mental-health support prototype with a clear split between a browser client and a Python API. The backend is the system of record for conversation state, mood tracking, retrieval, and agent orchestration; the frontend is mostly presentation, chat interaction, and dashboard rendering.

2. **Frontend boundary**
The `frontend/` app is a static browser UI built from `index.html`, `script.js`, `auth.js`, and `style.css`. It handles user sign-in, chat input/output, session navigation, and mood/summary displays. It also has a benchmark-login path that uses a shared password instead of normal user auth.

3. **Backend API boundary**
`backend/main.py` is the orchestration layer exposed through FastAPI. It serves the live chat endpoints, user/session read endpoints, benchmark endpoints, and the transcription path mentioned in the README. This layer is stateless in memory and relies on external stores for session history and mood analytics.

4. **Agent workflow core**
`backend/ai_agent.py` contains the main LangGraph `StateGraph`-based conversational workflow. The key architectural choice is a parallel reasoning path: a clinical branch and a sentiment branch run concurrently, then feed a synthesis step. That synthesis output is passed through a response guard/rewrite layer before being returned.

5. **Routing and safety behavior**
The first agent step is a router that decides whether a message is ordinary therapy support, an emergency-like message, or a therapist-location request. Emergency and location requests bypass the normal therapy synthesis path and are handled by dedicated flows. This makes safety and “find a therapist” behavior separate from the reflective chat pipeline.

6. **Streaming response path**
The `/ask` path is designed for streamed delivery rather than a single final response. The backend saves the user message, performs intent routing, then streams token chunks from the synthesis stage back to the browser while the response is still being generated. This is the main latency/UX optimization in the system.

7. **Persistence layer**
`backend/firebase_db.py` is the persistence boundary for chat sessions, messages, and mood data. The README indicates Firebase/Firestore is used for user-scoped storage, with separate session histories per user and read endpoints for sessions, messages, and mood trends. The architecture treats this as durable application state outside the API process.

8. **Memory and personalization**
`backend/memory.py` provides semantic retrieval from ChromaDB, used to pull relevant past context into the agent prompt. That sits alongside session history: session data preserves the conversation record, while memory retrieval supplies longer-range personalization across sessions. This is what lets replies reference prior themes without loading the entire history every time.

9. **Tools and external integrations**
`backend/tools.py` is the integration layer for non-LLM actions such as emergency workflows, therapist-location lookup, and other helper tools referenced in the README. The system depends on external services where needed: Firebase for auth/storage, Groq/OpenAI for model calls, Google Maps for clinic search, and Twilio for emergency-related tooling.

10. **Benchmarking and evaluation**
The repo includes explicit academic evaluation support: `/testbench/ask`, `/testbench/login`, and `/testbench/therapist/chats` for benchmark users and therapist-style exports. `backend/run_trisoul_evaluation.py` and related scripts automate live evaluation against a running API and write results to ignored output files. This makes evaluation a first-class subsystem, not an afterthought.

11. **Configuration and deployment**
`backend/config.py`, `.env.example`, and the Firebase credential file define runtime configuration and secrets boundaries. In production, the README says Nginx serves the static frontend and reverse-proxies API traffic to the FastAPI backend, while systemd keeps the backend process alive and Let’s Encrypt provides TLS. So deployment is a classic static-web-plus-API topology, not a single monolith.

12. **How the main data flows connect**
A typical user message flows from browser UI to FastAPI, then into storage, retrieval, routing, parallel agent analysis, synthesis, and response streaming back to the browser. The final AI message is persisted to Firebase, and mood/session data can then be read back for analytics views. Benchmark flows follow the same backend patterns but use isolated benchmark identities and export endpoints.

Main entry points: [`backend/main.py`](https://github.com/dk-krishna2001/trisoul-ai/blob/main/backend/main.py) (API Server), [`backend/ai_agent.py`](https://github.com/dk-krishna2001/trisoul-ai/blob/main/backend/ai_agent.py) (Agent Graph), [`frontend/script.js`](https://github.com/dk-krishna2001/trisoul-ai/blob/main/frontend/script.js) (Client Logic), [`backend/tools.py`](https://github.com/dk-krishna2001/trisoul-ai/blob/main/backend/tools.py) (Tools)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_frontend["Frontend"]
  node_frontend_ui["Browser UI<br/>static client<br/>[index.html]"]
  node_frontend_chat["Client Logic<br/>js app<br/>[script.js]"]
  node_frontend_auth["Auth Flow<br/>js auth<br/>[auth.js]"]
end

subgraph group_backend["Backend"]
  node_api_main["API Server<br/>fastapi<br/>[main.py]"]
  node_agent_graph["Agent Graph<br/>langgraph workflow<br/>[ai_agent.py]"]
  node_persistence[("Firebase Store<br/>firestore layer<br/>[firebase_db.py]")]
  node_memory_store[("Memory Retrieval<br/>chromadb memory<br/>[memory.py]")]
  node_toolbox["Tools<br/>[tools.py]"]
  node_config["Config<br/>[config.py]"]
  node_evaluation["Evaluation<br/>benchmarking"]
end

subgraph group_external["External"]
  node_firebase[("Firebase<br/>external storage/auth")]
  node_model_api(("LLM API<br/>external ai model"))
  node_maps(("Maps API<br/>external lookup"))
  node_twilio(("Twilio<br/>external messaging"))
  node_deployment["Nginx/systemd<br/>deployment runtime"]
end

node_frontend_ui -->|"loads"| node_frontend_chat
node_frontend_chat -->|"auth"| node_frontend_auth
node_frontend_chat -->|"api calls"| node_api_main
node_frontend_auth -->|"login"| node_api_main
node_api_main -->|"store/read"| node_persistence
node_api_main -->|"dispatch"| node_agent_graph
node_agent_graph -->|"retrieve"| node_memory_store
node_agent_graph -->|"tool use"| node_toolbox
node_agent_graph -->|"generate"| node_model_api
node_toolbox -->|"lookup"| node_maps
node_toolbox -->|"alert"| node_twilio
node_persistence -->|"backed by"| node_firebase
node_memory_store -->|"separate state"| node_firebase
node_api_main -->|"benchmark"| node_evaluation
node_config -->|"configures"| node_api_main
node_deployment -->|"serves"| node_frontend_ui
node_deployment -->|"proxies"| node_api_main

click node_frontend_ui "https://github.com/dk-krishna2001/trisoul-ai/blob/main/frontend/index.html"
click node_frontend_chat "https://github.com/dk-krishna2001/trisoul-ai/blob/main/frontend/script.js"
click node_frontend_auth "https://github.com/dk-krishna2001/trisoul-ai/blob/main/frontend/auth.js"
click node_api_main "https://github.com/dk-krishna2001/trisoul-ai/blob/main/backend/main.py"
click node_agent_graph "https://github.com/dk-krishna2001/trisoul-ai/blob/main/backend/ai_agent.py"
click node_persistence "https://github.com/dk-krishna2001/trisoul-ai/blob/main/backend/firebase_db.py"
click node_memory_store "https://github.com/dk-krishna2001/trisoul-ai/blob/main/backend/memory.py"
click node_toolbox "https://github.com/dk-krishna2001/trisoul-ai/blob/main/backend/tools.py"
click node_config "https://github.com/dk-krishna2001/trisoul-ai/blob/main/backend/config.py"
click node_evaluation "https://github.com/dk-krishna2001/trisoul-ai/blob/main/backend/run_trisoul_evaluation.py"

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_ui,node_frontend_chat,node_frontend_auth toneBlue
class node_api_main,node_agent_graph,node_persistence,node_memory_store,node_toolbox,node_config,node_evaluation toneAmber
class node_firebase,node_model_api,node_maps,node_twilio,node_deployment toneMint
```

## Components

### Frontend

Static browser UI for chat, auth, and dashboard views.

- [Browser UI](https://github.com/dk-krishna2001/trisoul-ai/blob/main/frontend/index.html): static client · HTML/CSS shell that renders the user-facing app. · `frontend/index.html`
- [Client Logic](https://github.com/dk-krishna2001/trisoul-ai/blob/main/frontend/script.js): js app · Handles chat interactions, session navigation, and dashboard updates. · `frontend/script.js`
- [Auth Flow](https://github.com/dk-krishna2001/trisoul-ai/blob/main/frontend/auth.js): js auth · Manages sign-in and benchmark-login behavior. · `frontend/auth.js`

### Backend

FastAPI API, agent orchestration, storage, retrieval, and evaluation.

- [API Server](https://github.com/dk-krishna2001/trisoul-ai/blob/main/backend/main.py): fastapi · HTTP boundary for chat, reads, transcription, and benchmark endpoints. · `backend/main.py`
- [Agent Graph](https://github.com/dk-krishna2001/trisoul-ai/blob/main/backend/ai_agent.py): langgraph workflow · Parallel clinical/sentiment reasoning, synthesis, and safety rewriting. · `backend/ai_agent.py`
- [Firebase Store](https://github.com/dk-krishna2001/trisoul-ai/blob/main/backend/firebase_db.py): firestore layer · Durable sessions, messages, user state, and mood data. · `backend/firebase_db.py`
- [Memory Retrieval](https://github.com/dk-krishna2001/trisoul-ai/blob/main/backend/memory.py): chromadb memory · Semantic retrieval of prior context across sessions. · `backend/memory.py`
- [Tools](https://github.com/dk-krishna2001/trisoul-ai/blob/main/backend/tools.py): integration tools · Emergency, therapist lookup, and other non-LLM actions. · `backend/tools.py`
- [Config](https://github.com/dk-krishna2001/trisoul-ai/blob/main/backend/config.py): runtime config · Environment, secrets, and deployment settings boundary. · `backend/config.py`
- [Evaluation](https://github.com/dk-krishna2001/trisoul-ai/blob/main/backend/run_trisoul_evaluation.py): benchmarking · Live evaluation scripts and benchmark result capture. · `backend/run_trisoul_evaluation.py`

### External

Third-party services and deployment/runtime boundaries.

- **Firebase**: external storage/auth · Auth and user-scoped application storage.
- **LLM API**: external ai model · Hosted model provider used for generation and reasoning.
- **Maps API**: external lookup · Therapist and clinic search integration.
- **Twilio**: external messaging · Emergency-related communication integration.
- **Nginx/systemd**: deployment runtime · Static frontend hosting, reverse proxying, and process supervision.

## Connections

- Browser UI → Client Logic: loads · The HTML shell boots the client-side app.
- Client Logic → Auth Flow: auth · Client logic coordinates login and benchmark login.
- Client Logic → API Server: api calls · Browser requests chat, read, and benchmark endpoints.
- Auth Flow → API Server: login · Authentication flow exchanges credentials with the backend.
- API Server → Firebase Store: store/read · API persists messages and reads session and mood data.
- API Server → Agent Graph: dispatch · Chat requests enter the conversational workflow.
- Agent Graph → Memory Retrieval: retrieve · Workflow pulls relevant prior context into the prompt.
- Agent Graph → Tools: tool use · Workflow can branch to emergency and location tools.
- Agent Graph → LLM API: generate · Parallel reasoning and synthesis depend on hosted model calls.
- Tools → Maps API: lookup · Therapist-location requests use mapping/search services.
- Tools → Twilio: alert · Emergency tooling can trigger outbound communication.
- Firebase Store → Firebase: backed by · Durable state lives in Firebase/Firestore.
- Memory Retrieval → Firebase: separate state · Longer-range memory complements stored conversation history.
- API Server → Evaluation: benchmark · API exposes benchmark-oriented routes and exports.
- Config → API Server: configures · Runtime settings shape the API process.
- Nginx/systemd → Browser UI: serves · Production deployment serves the static browser app.
- Nginx/systemd → API Server: proxies · Reverse proxy forwards API traffic to FastAPI.
