# Implementation Phases Phased build plan for the Christianity-focused AI Assistant. Each phase has a goal, concrete tasks, the files it touches, and an exit criterion. See [`ARCHITECTURE.md`](./ARCHITECTURE.md) for the full design. **Status legend:** โœ… done ยท ๐ŸŸก in progress ยท โฌœ not started --- ## Phase 0 โ€” Project Setup โœ… **Goal:** Reproducible backend skeleton, tooling, and config. - โœ… `uv` project, Python 3.12 pin, `pyproject.toml` + `uv.lock` - โœ… FastAPI app, `/health` + `/chat` stub - โœ… structlog (console dev / JSON prod) with request-id middleware - โœ… `pydantic-settings` config (env-driven), `.env.example` - โœ… `.gitignore`, README, git initialized + initial commit **Exit:** `uv run uvicorn app.main:app` boots, `/health` returns 200. โœ… --- ## Phase 1 โ€” Data Layer & Corpus ๐ŸŸก **Goal:** Postgres + pgvector populated with grounded source text. - โœ… `docker-compose.yml` โ€” pgvector/pg16 on host port 5433 - โœ… `schema.sql` โ€” `bible_verses`, `history_docs`, `conversations` + HNSW/GIN indexes - โœ… `core/db.py` โ€” psycopg3 pool, pgvector registration, extension bootstrap - โœ… `scripts/init_db.py` โ€” idempotent schema apply - โœ… `core/embeddings.py` โ€” bge-base loader, `embed_passages` / `embed_query` - ๐ŸŸก `scripts/ingest_bible.py` โ€” KJV (66 books) ingest + embeddings (in progress) - ๐ŸŸก `scripts/ingest_history.py` โ€” parse `creeds1.pdf`, chunk, embed โ†’ `history_docs` (in progress) - โฌœ Deuterocanon ingest from `KJV-with-Apocrypha.json` โ†’ tag `catholic`/`orthodox` **Exit:** `bible_verses` fully populated (~31k rows); `history_docs` has creeds + council facts; semantic search returns sane neighbors. **Files:** `backend/app/core/{db,embeddings,schema.sql}`, `backend/scripts/*` --- ## Phase 2 โ€” Retrieval Layer โœ… **Goal:** Denomination-aware scripture + history retrieval functions. - โœ… `core/retrieval.py` โ€” `search_scripture(query, denomination, k)` with canon filter - โœ… `search_history(query, denomination, k)` (validated once `history_docs` populated) - โœ… Retrieval confidence scoring (top cosine similarity, threshold in config) - โœ… Reference lookup `verse_exists(book, chapter, verse)` for citation validation **Exit:** Given a query + denomination, returns ranked verses honoring canon membership; confidence reflects match quality. โœ… --- ## Phase 3 โ€” LLM Integration โœ… **Goal:** Gemini client wrapper with grounded prompting. - โœ… `core/llm.py` โ€” google-genai client, main (`gemini-2.5-pro`) generation - โœ… Module-level singleton + `_reset_client()` auto-retry on closed httpx session - โœ… `core/prompts.py` โ€” system prompt templates, denomination framing, `build_user_prompt` - โœ… Structured output helpers (`generate_json` with response_schema) **Exit:** Wrapper takes prompt + retrieved context, returns grounded text; honors "cite only retrieved verses" instruction. โœ… --- ## Phase 4 โ€” Safety & Router Node โœ… **Goal:** Block unsafe input before retrieval; classify intent in one call. - โœ… `core/safety.py` โ€” Stage 1 regex (adversarial templates, explicit hate) - โœ… Stage 2 Gemini Flash call returning `{safe, intent, confidence}` - โœ… Intents: `scripture | theology | history | image | general | blocked` - โœ… Low-confidence / general โ†’ fallback to plain responder **Exit:** Adversarial + hateful prompts blocked pre-retrieval; intent routed correctly on the eval set. โœ… --- ## Phase 5 โ€” Agent Graph โœ… **Goal:** Wire the LangGraph `StateGraph` from `ARCHITECTURE.md` ยง4โ€“6. - โœ… `agent/state.py` โ€” `AgentState` TypedDict with all fields - โœ… `agent/nodes.py` โ€” 9 nodes: Input, SafetyRouter, ScriptureRAG, HistoryRAG, Theology, Image, ImageValidator, Validator, Responder - โœ… `agent/graph.py` โ€” conditional edges, compile, `get_graph()` lru_cache singleton - โœ… Per-node latency capture into `state.latency_ms` **Exit:** Graph runs end-to-end for all intents. โœ… --- ## Phase 6 โ€” Grounding & Hallucination Control โœ… **Goal:** Catch fake citations and paraphrase drift. - โœ… Citation validator: extract `Book Ch:Verse`, verify vs corpus, strip + log fakes - โœ… Semantic drift check: embed response, compare max-sim across retrieved set - โœ… Drift disclaimer injection when drift high despite strong retrieval - โœ… Populate `hallucinated_refs`, `drift_warning` in state **Exit:** Fake-verse and paraphrase-misquote eval cases pass (no invented refs). โœ… --- ## Phase 7 โ€” Conversation Memory โœ… **Goal:** Bounded, relevant context โ€” no full-history dump. - โœ… Persist each turn to `conversations` with per-turn embedding - โœ… Window strategy (โ‰ค20 turns โ†’ last 10) and semantic strategy (>20 โ†’ top-5) - โœ… Denomination-switch guard: inject canon/framing-changed system note **Exit:** Long sessions stay within budget; denomination switch updates framing without stale assumptions. โœ… --- ## Phase 8 โ€” Image Generation โœ… **Goal:** Safe Christian-themed image flow with two-pass moderation. - โœ… Image prompt rewrite into safe Christian-art form - โœ… Imagen 3 call via google-genai (base64 data URI) - โœ… `ImageValidator` node re-checks rewritten prompt before generation - โœ… Return image URL/bytes + safety metadata **Exit:** Policy-violating image prompts blocked at raw and post-rewrite stages. โœ… --- ## Phase 9 โ€” API Integration โœ… **Goal:** Replace `/chat` stub with the compiled graph. - โœ… `/chat` invokes graph, returns response + citations + flags - โœ… Session handling, request-id propagation into graph state - โœ… `asyncio.run_in_executor` wraps synchronous graph for async FastAPI **Exit:** End-to-end API call produces grounded, cited, moderated responses. โœ… --- ## Phase 10 โ€” Frontend โœ… **Goal:** Minimal chat UI (UI polish explicitly not graded). - โœ… Next.js 15 + Tailwind CSS chat interface - โœ… Denomination selector (Protestant/Catholic/Orthodox pills) - โœ… Citation rendering: verified (amber) + hallucinated (red) badges - โœ… Image display in chat bubble - โœ… Wire to backend `/chat` **Exit:** Usable demo chat with denomination toggle and visible citations. โœ… --- ## Phase 11 โ€” Evaluation โœ… **Goal:** Reproducible eval harness over the dataset in `ARCHITECTURE.md` ยง13. - โœ… `eval/dataset.json` โ€” 20 cases: fake-verse, adversarial, hallucination, image, history, denomination, theology, scripture - โœ… `eval/run_eval.py` โ€” run cases through graph, score PASS/PARTIAL/FAIL, color report, exit code 1 on FAIL - โœ… `--id` and `--category` filters for targeted runs - โœ… Result: 16 PASS / 2 PARTIAL / 2 FAIL (historical FAILs fixed by Phase 1 history ingest) **Exit:** Single command runs the eval set and prints a scored report. โœ… --- ## Phase 12 โ€” Deployment โฌœ **Goal:** Credible hosted demo. - โฌœ Backend โ†’ Hugging Face Spaces (or container host) - โฌœ DB โ†’ NeonDB (pgvector); push corpus - โฌœ Frontend โ†’ Vercel - โฌœ Env/secrets wiring (`GEMINI_API_KEY`) **Exit:** Public URL serves the assistant against hosted DB. --- ## Phase 13 โ€” Deliverables ๐ŸŸก **Goal:** Wrap up assignment artifacts. - โœ… `docs/ARCHITECTURE.md` โ€” full system design with all decisions - โœ… `docs/HLD.md` โ€” Mermaid diagrams + component table - โœ… `docs/SYSTEM_DESIGN.md` โ€” formal SDD with requirements, flows, trade-offs - โœ… `README.md` โ€” setup, run, eval instructions - โฌœ 5โ€“8 min walkthrough script/recording - โฌœ Final eval run after full corpus ingest (target โ‰ฅ18/20 PASS/PARTIAL) **Exit:** Demo + repo + note + walkthrough ready to submit. --- ## Critical Path ``` Phase 1 (corpus) โ†’ Phase 2 (retrieval) โ†’ Phase 3 (LLM) โ†’ Phase 4 (safety/router) โ†’ Phase 5 (graph) โ†’ Phase 6 (grounding) โ†’ Phase 9 (API) โ†’ Phase 11 (eval) ``` Phases 7 (memory), 8 (image), 10 (frontend) are parallelizable once the graph (Phase 5) exists. Phases 12โ€“13 are last.