# arjun-57561/ufac architecture

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

- Interactive diagram: https://gitdiagram.com/arjun-57561/ufac
- Repository: https://github.com/arjun-57561/ufac

## Overview

1. **This repo is a two-tier application**: a **Python backend** that performs PM-KISAN eligibility assessment and a **Next.js frontend** that presents the assessment flow, results, and system status. The backend is the source of truth for eligibility logic; the UI is primarily a client for submitting user data and visualizing outputs.

2. **Primary request path** starts at the frontend’s assessment forms/pages, which call the backend’s **`POST /check`** endpoint. The backend returns a structured UFAC assessment containing the answer, confidence, known facts, assumptions, unknowns, risk level, and next steps. The UI also has pages for the overall agent flow, eligibility checking, and backend health/status.

3. **Backend entrypoints are split between API and CLI**. `api/app.py` exposes the FastAPI application, while `main.py` and `core/ufac_engine.py` support direct programmatic/command-line execution of the same assessment engine. This makes the core logic reusable outside the HTTP layer.

4. **The core architecture is a multi-agent orchestration layer** in `core/`. The engine coordinates five specialized agents: **Fact**, **Assumption**, **Unknown**, **Confidence**, and **Decision**. The assessment is intentionally decomposed into these stages so each agent produces a distinct part of the final response rather than one monolithic model call.

5. **Agent execution is optimized and partially parallelized**. The README describes a two-batch execution model: the first batch handles fact/assumption/unknown extraction, and the second batch handles confidence and decision generation. That means the engine is not just routing; it is also coordinating concurrency and merging results into a unified schema.

6. **LLM access is isolated behind utility and resilience layers**. `core/llm_utils.py` centralizes calls to the Groq API, while `core/circuit_breaker.py`, retry logic, and timeout configuration protect the system from upstream failures. This boundary matters: the rest of the app should not depend directly on provider-specific behavior.

7. **Eligibility reasoning combines LLM output with rules and RAG**. The `data/` package contains PM-KISAN rule definitions plus a RAG pipeline backed by `data/chroma_db/` and PDF source documents. If the retrieval pipeline is unavailable, the system degrades to hardcoded rules, so there is a clear fallback path from knowledge retrieval to deterministic policy logic.

8. **Stateful subsystems are separated from request handling**. `core/cache.py` provides in-memory caching with TTLs for assessments, RAG, and LLM calls; `core/database.py` persists assessment history to SQLite/PostgreSQL via async SQLAlchemy; and `core/metrics.py` tracks latency, request counts, and agent performance. These are supporting planes around the main inference path, not part of the core decision logic.

9. **The API layer is also a control and observability surface**. Besides `/check`, it exposes health, RAG status, circuit breaker state, cache stats, metrics, history lookup, and cache/metrics reset endpoints. The presence of these endpoints shows the backend is designed for operational transparency, not just request/response handling.

10. **Security is enforced at the boundary** in the FastAPI app: environment-driven CORS allowlists, rate limiting on assessment requests, input sanitization, and security headers. This means the HTTP layer is responsible for abuse prevention before data reaches the UFAC engine.

11. **The frontend is a fairly rich presentation layer, not a thin form**. Under `UI/app/` and `UI/components/`, it includes the eligibility form, agent flow visualization, result panels, confidence/consensus indicators, backend status indicators, theme controls, and animated UI scaffolding. The hooks suggest a client-side integration model for polling backend status and submitting assessments.

12. **The app uses modern web tooling but remains architecture-light on the client side**. The frontend is built with Next.js 14 App Router, React, TypeScript, and component primitives in `UI/components/ui/`. The important boundary is that the UI depends on backend APIs for assessment logic and system state; it does not embed the PM-KISAN rules itself.

13. **Testing is focused on the backend’s reliability surface**. The `tests/` folder covers API behavior, caching, and error handling, which matches the repo’s emphasis on resilience, fallback behavior, and operational endpoints. This indicates the critical architectural risk is not just correctness of eligibility results, but failure handling under real API/LLM conditions.

14. **There is a separate research/prototyping area** in `research/` with scripts for Groq, Gemini, and Llama API testing. This appears to be exploratory tooling rather than production flow, and it sits outside the main runtime path.

15. **For an architecture diagram, the key data flow is:** user inputs enter the **UI**, go to the **FastAPI `/check` endpoint**, pass through **security/rate limiting/cache**, then into the **UFAC engine**, which consults **LLM/RAG/rules** through resilience wrappers, and finally returns a structured assessment that may also be **persisted to the database** and reflected back in **metrics/history/status endpoints**.

Main entry points: [`core/ufac_engine.py`](https://github.com/arjun-57561/ufac/blob/main/core/ufac_engine.py) (UFAC engine), [`api/app.py`](https://github.com/arjun-57561/ufac/blob/main/api/app.py) (API app), [`core/llm_utils.py`](https://github.com/arjun-57561/ufac/blob/main/core/llm_utils.py) (LLM utils), [`data/rag_pipeline.py`](https://github.com/arjun-57561/ufac/blob/main/data/rag_pipeline.py) (RAG pipeline)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_frontend["Frontend"]
  node_ui_app["UI app<br/>Next.js routes"]
  node_ui_components["UI components<br/>React components"]
  node_ui_hooks["UI hooks<br/>Client hooks"]
end

subgraph group_backend["Backend"]
  node_api_app["API app<br/>FastAPI entrypoint<br/>[app.py]"]
  node_ufac_engine["UFAC engine<br/>Orchestrator<br/>[ufac_engine.py]"]
  node_fact_agent["Fact agent<br/>Extraction agent<br/>[fact_agent.py]"]
  node_assumption_agent["Assumption agent<br/>Reasoning agent"]
  node_unknown_agent["Unknown agent<br/>Gap analysis<br/>[unknown_agent.py]"]
  node_confidence_agent["Confidence agent<br/>Scoring agent"]
  node_decision_agent["Decision agent<br/>[decision_agent.py]"]
  node_llm_utils["LLM utils<br/>Groq adapter<br/>[llm_utils.py]"]
  node_resilience_layer["Resilience<br/>Retry/circuit breaker<br/>[circuit_breaker.py]"]
  node_schema["Schema<br/>UFAC contract<br/>[schema.py]"]
end

subgraph group_knowledge["Knowledge"]
  node_pm_rules["PM-KISAN rules<br/>Deterministic policy<br/>[pm_kisan_rules.py]"]
  node_rag_pipeline["RAG pipeline<br/>Retrieval pipeline<br/>[rag_pipeline.py]"]
  node_chroma_store[("Chroma store<br/>Vector store")]
  node_guidelines_docs["Guidelines docs<br/>Source PDFs"]
end

subgraph group_support["Support"]
  node_cache["Cache<br/>[cache.py]"]
  node_database[("Database<br/>Assessment store<br/>[database.py]")]
  node_metrics(("Metrics<br/>Observability<br/>[metrics.py]"))
  node_tests_api["API tests<br/>Backend tests<br/>[test_api.py]"]
  node_research_tools["Research tools<br/>Experiment scripts"]
end

node_ui_app -->|"submit /check"| node_api_app
node_ui_components -->|"render pages"| node_ui_app
node_ui_hooks -->|"poll/call"| node_api_app
node_api_app -->|"read/write"| node_cache
node_api_app -->|"protect calls"| node_resilience_layer
node_api_app -->|"invoke engine"| node_ufac_engine
node_ufac_engine -->|"batch 1"| node_fact_agent
node_ufac_engine -->|"batch 1"| node_assumption_agent
node_ufac_engine -->|"batch 1"| node_unknown_agent
node_ufac_engine -->|"batch 2"| node_confidence_agent
node_ufac_engine -->|"batch 2"| node_decision_agent
node_fact_agent -->|"LLM call"| node_llm_utils
node_assumption_agent -->|"LLM call"| node_llm_utils
node_unknown_agent -->|"LLM call"| node_llm_utils
node_confidence_agent -->|"LLM call"| node_llm_utils
node_decision_agent -->|"LLM call"| node_llm_utils
node_llm_utils -->|"wrap provider"| node_resilience_layer
node_ufac_engine -->|"assemble"| node_schema
node_api_app -->|"serialize"| node_schema
node_ufac_engine -->|"retrieve context"| node_rag_pipeline
node_rag_pipeline -->|"query index"| node_chroma_store
node_rag_pipeline -->|"built from"| node_guidelines_docs
node_ufac_engine -->|"fallback rules"| node_pm_rules
node_api_app -->|"persist history"| node_database
node_api_app -->|"observe"| node_metrics
node_api_app -.->|"validated by"| node_tests_api
node_research_tools -.->|"prototype"| node_llm_utils

click node_ui_app "https://github.com/arjun-57561/ufac/tree/main/UI/app"
click node_ui_components "https://github.com/arjun-57561/ufac/tree/main/UI/components"
click node_ui_hooks "https://github.com/arjun-57561/ufac/tree/main/UI/hooks"
click node_api_app "https://github.com/arjun-57561/ufac/blob/main/api/app.py"
click node_ufac_engine "https://github.com/arjun-57561/ufac/blob/main/core/ufac_engine.py"
click node_fact_agent "https://github.com/arjun-57561/ufac/blob/main/core/fact_agent.py"
click node_assumption_agent "https://github.com/arjun-57561/ufac/blob/main/core/assumption_agent.py"
click node_unknown_agent "https://github.com/arjun-57561/ufac/blob/main/core/unknown_agent.py"
click node_confidence_agent "https://github.com/arjun-57561/ufac/blob/main/core/confidence_agent.py"
click node_decision_agent "https://github.com/arjun-57561/ufac/blob/main/core/decision_agent.py"
click node_llm_utils "https://github.com/arjun-57561/ufac/blob/main/core/llm_utils.py"
click node_resilience_layer "https://github.com/arjun-57561/ufac/blob/main/core/circuit_breaker.py"
click node_cache "https://github.com/arjun-57561/ufac/blob/main/core/cache.py"
click node_database "https://github.com/arjun-57561/ufac/blob/main/core/database.py"
click node_metrics "https://github.com/arjun-57561/ufac/blob/main/core/metrics.py"
click node_schema "https://github.com/arjun-57561/ufac/blob/main/core/schema.py"
click node_pm_rules "https://github.com/arjun-57561/ufac/blob/main/data/pm_kisan_rules.py"
click node_rag_pipeline "https://github.com/arjun-57561/ufac/blob/main/data/rag_pipeline.py"
click node_chroma_store "https://github.com/arjun-57561/ufac/tree/main/data/chroma_db"
click node_guidelines_docs "https://github.com/arjun-57561/ufac/tree/main/data"
click node_tests_api "https://github.com/arjun-57561/ufac/blob/main/tests/test_api.py"
click node_research_tools "https://github.com/arjun-57561/ufac/tree/main/research"

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_ui_app,node_ui_components,node_ui_hooks toneBlue
class node_api_app,node_ufac_engine,node_fact_agent,node_assumption_agent,node_unknown_agent,node_confidence_agent,node_decision_agent,node_llm_utils,node_resilience_layer,node_schema toneAmber
class node_pm_rules,node_rag_pipeline,node_chroma_store,node_guidelines_docs toneMint
class node_cache,node_database,node_metrics,node_tests_api,node_research_tools toneRose
```

## Components

### Frontend

Next.js presentation layer for assessment, flow visualization, and status views.

- [UI app](https://github.com/arjun-57561/ufac/tree/main/UI/app): Next.js routes · App Router pages for home, eligibility, check, flow, agent flow, and about. · `UI/app`
- [UI components](https://github.com/arjun-57561/ufac/tree/main/UI/components): React components · Reusable form, results, visualization, status, and layout components. · `UI/components`
- [UI hooks](https://github.com/arjun-57561/ufac/tree/main/UI/hooks): Client hooks · Browser-side hooks for backend status, counts, and assessment submission. · `UI/hooks`

### Backend

FastAPI API and reusable UFAC engine that perform eligibility assessment.

- [API app](https://github.com/arjun-57561/ufac/blob/main/api/app.py): FastAPI entrypoint · HTTP surface exposing /check plus health, status, metrics, cache, and history endpoints. · `api/app.py`
- [UFAC engine](https://github.com/arjun-57561/ufac/blob/main/core/ufac_engine.py): Orchestrator · Coordinates the multi-agent assessment pipeline and assembles the final UFAC response. · `core/ufac_engine.py`
- [Fact agent](https://github.com/arjun-57561/ufac/blob/main/core/fact_agent.py): Extraction agent · Derives known facts from the submitted assessment data. · `core/fact_agent.py`
- [Assumption agent](https://github.com/arjun-57561/ufac/blob/main/core/assumption_agent.py): Reasoning agent · Produces assumptions needed to complete the assessment. · `core/assumption_agent.py`
- [Unknown agent](https://github.com/arjun-57561/ufac/blob/main/core/unknown_agent.py): Gap analysis · Identifies missing information and unresolved unknowns. · `core/unknown_agent.py`
- [Confidence agent](https://github.com/arjun-57561/ufac/blob/main/core/confidence_agent.py): Scoring agent · Estimates confidence and uncertainty for the assessment result. · `core/confidence_agent.py`
- [Decision agent](https://github.com/arjun-57561/ufac/blob/main/core/decision_agent.py): Decision agent · Determines the final eligibility answer and next steps. · `core/decision_agent.py`
- [LLM utils](https://github.com/arjun-57561/ufac/blob/main/core/llm_utils.py): Groq adapter · Centralized provider access for LLM calls and prompt execution. · `core/llm_utils.py`
- [Resilience](https://github.com/arjun-57561/ufac/blob/main/core/circuit_breaker.py): Retry/circuit breaker · Protects LLM and external calls with retries, timeouts, and circuit breaking. · `core/circuit_breaker.py`
- [Schema](https://github.com/arjun-57561/ufac/blob/main/core/schema.py): UFAC contract · Structured response model for answer, confidence, facts, assumptions, unknowns, risk, and next steps. · `core/schema.py`

### Knowledge

Rules, retrieved documents, and persisted RAG store used by the backend.

- [PM-KISAN rules](https://github.com/arjun-57561/ufac/blob/main/data/pm_kisan_rules.py): Deterministic policy · Hardcoded eligibility rules used when retrieval is unavailable or as policy grounding. · `data/pm_kisan_rules.py`
- [RAG pipeline](https://github.com/arjun-57561/ufac/blob/main/data/rag_pipeline.py): Retrieval pipeline · Retrieves guideline context from embedded PM-KISAN documents. · `data/rag_pipeline.py`
- [Chroma store](https://github.com/arjun-57561/ufac/tree/main/data/chroma_db): Vector store · Persistent embedded document index backing retrieval. · `data/chroma_db`
- [Guidelines docs](https://github.com/arjun-57561/ufac/tree/main/data): Source PDFs · Operational and scheme guideline documents used to build retrieval context. · `data`

### Support

State, observability, tests, and exploratory tooling around the main runtime.

- [Cache](https://github.com/arjun-57561/ufac/blob/main/core/cache.py): TTL cache · In-memory caching for assessments, RAG results, and LLM responses. · `core/cache.py`
- [Database](https://github.com/arjun-57561/ufac/blob/main/core/database.py): Assessment store · Persists assessment history through async SQLAlchemy to SQLite/PostgreSQL. · `core/database.py`
- [Metrics](https://github.com/arjun-57561/ufac/blob/main/core/metrics.py): Observability · Tracks request counts, latency, and agent performance. · `core/metrics.py`
- [API tests](https://github.com/arjun-57561/ufac/blob/main/tests/test_api.py): Backend tests · Coverage for API behavior, caching, and error handling. · `tests/test_api.py`
- [Research tools](https://github.com/arjun-57561/ufac/tree/main/research): Experiment scripts · Ad hoc Groq, Gemini, and Llama API experiments outside the production path. · `research`

## Connections

- UI app → API app: submit /check · Frontend submits assessment data and reads backend state.
- UI components → UI app: render pages · Shared components power the assessment and status views.
- UI hooks → API app: poll/call · Client hooks fetch backend status and assessment results.
- API app → Cache: read/write · API consults cache for repeated assessments and status data.
- API app → Resilience: protect calls · HTTP requests are guarded by throttling and failure controls.
- API app → UFAC engine: invoke engine · The /check endpoint delegates assessment to the core engine.
- UFAC engine → Fact agent: batch 1 · First execution batch extracts known facts.
- UFAC engine → Assumption agent: batch 1 · First execution batch derives assumptions.
- UFAC engine → Unknown agent: batch 1 · First execution batch identifies unknowns.
- UFAC engine → Confidence agent: batch 2 · Second batch computes confidence after extraction.
- UFAC engine → Decision agent: batch 2 · Second batch determines final eligibility outcome.
- Fact agent → LLM utils: LLM call · Agent uses centralized model access.
- Assumption agent → LLM utils: LLM call · Agent uses centralized model access.
- Unknown agent → LLM utils: LLM call · Agent uses centralized model access.
- Confidence agent → LLM utils: LLM call · Agent uses centralized model access.
- Decision agent → LLM utils: LLM call · Agent uses centralized model access.
- LLM utils → Resilience: wrap provider · Provider calls pass through retry and circuit-breaking controls.
- UFAC engine → Schema: assemble · Engine merges agent outputs into the structured UFAC contract.
- API app → Schema: serialize · API returns the unified assessment schema to clients.
- UFAC engine → RAG pipeline: retrieve context · Engine can pull scheme context for grounding and fallback.
- RAG pipeline → Chroma store: query index · Retrieval reads the persistent vector store.
- RAG pipeline → Guidelines docs: built from · The vector store is derived from scheme guideline PDFs.
- UFAC engine → PM-KISAN rules: fallback rules · Deterministic rules are used when retrieval is unavailable.
- API app → Database: persist history · Assessment results and lookup history are stored.
- API app → Metrics: observe · Operational endpoints expose request and latency metrics.
- API app → API tests: validated by · Backend behavior is exercised by automated tests.
- Research tools → LLM utils: prototype · Experimental scripts exercise provider integrations.
