# devfullcycle/mba-ia-cache architecture

> Architecture diagram of the GitHub repository devfullcycle/mba-ia-cache, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-07-10). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/devfullcycle/mba-ia-cache
- Repository: https://github.com/devfullcycle/mba-ia-cache

## Overview

1. **Purpose and runtime shape**
   - This repository is a small FastAPI service for support-ticket analysis with an AI-backed response flow.
   - The core architectural idea is a two-level cache: an in-memory exact cache first, then a semantic cache in Postgres/pgvector, and only then an LLM call.

2. **Primary request path**
   - The main flow is centered on `POST /tickets/analyze`.
   - Requests arrive at the FastAPI app in `main.py`, are normalized and fingerprinted, and then checked against caches in order:
     1) exact in-memory hit,
     2) semantic similarity hit in pgvector,
     3) AI model call,
     4) write-through into the semantic cache only when the model was used.

3. **Exact cache boundary**
   - The exact cache is memory-resident and keyed by a fingerprint built from the current prompt/rules/model capability context.
   - This is a fast local optimization and is not persisted across restarts.
   - A hit here bypasses both the vector search and the model.

4. **Semantic cache boundary**
   - Semantic reuse is persisted in Postgres with `pgvector`.
   - The service stores both the input embedding and the AI response payload, then later compares new inputs using vector distance.
   - A threshold controls whether the best match is accepted as reusable; if it is below the threshold, the system falls through to the AI model.

5. **AI/model integration**
   - `config.py` is responsible for environment/config loading and for constructing LangChain model/embedding factories.
   - The repository depends on an external model provider, with `OPENAI_API_KEY` called out in the README.
   - The model is only invoked on semantic misses, which reduces latency and cost.

6. **Database subsystem**
   - `db.py` owns the persistence layer: connection setup, enabling the `vector` extension, creating the cache table, and creating the fingerprint index.
   - Postgres is the durable store for semantic cache items and any lookup metadata needed by search/evaluation.
   - The table includes an `embedding VECTOR(1536)` column, so embedding dimensionality is part of the storage contract.

7. **API surface beyond ticket analysis**
   - `GET /db/status` is a health/diagnostic endpoint for verifying database connectivity, pgvector availability, and table presence.
   - `POST /semantic-cache/items` inserts a semantic-cache item directly.
   - `POST /semantic-cache/search` performs similarity search over saved embeddings.
   - `POST /semantic-cache/evaluate` applies a threshold decision to the best candidate without calling the model.

8. **Data flow through search/evaluation**
   - For search and evaluation, the service normalizes input, generates an embedding, and compares it to stored vectors using pgvector distance (`<=>`).
   - Search returns candidates with distance and derived similarity, while evaluation picks the top match and decides accepted/rejected.
   - These endpoints are read-oriented helpers around the same persistence and embedding pipeline used by `/tickets/analyze`.

9. **Cache write policy**
   - The semantic cache is written only on the AI path, not on exact hits or semantic hits.
   - The response metadata includes whether a semantic cache write was attempted, saved, or failed, which makes the cache behavior observable.
   - This means the cache grows from genuinely model-generated answers, not from reused answers.

10. **Configuration and operational boundaries**
   - Environment configuration comes from `.env` / `.env.example`.
   - The stack runs locally with `docker-compose.yml` for Postgres + pgvector and `python main.py` for the API.
   - Startup behavior includes DB initialization, so the service expects the database to be available and will fail loudly if it is not.

11. **Code organization**
   - `main.py` is the orchestration layer: routes, request handling, cache decision logic, and response shaping.
   - `db.py` is the persistence/infrastructure layer.
   - `models.py` contains Pydantic request/response schemas.
   - `log_helpers.py` provides structured/block-style logging for the main flows.

12. **Diagram-friendly mental model**
   - Think of the repo as three boundaries: an HTTP API layer, a caching/decision layer, and a persistence/model layer.
   - The key dependency direction is: FastAPI routes → cache decision logic → embeddings/model factories + Postgres/pgvector.
   - External dependencies are the database and the LLM provider; everything else is internal orchestration around those two services.

Main entry points: [`main.py`](https://github.com/devfullcycle/mba-ia-cache/blob/main/main.py) (main.py), [`db.py`](https://github.com/devfullcycle/mba-ia-cache/blob/main/db.py) (db.py), [`config.py`](https://github.com/devfullcycle/mba-ia-cache/blob/main/config.py) (config.py), [`models.py`](https://github.com/devfullcycle/mba-ia-cache/blob/main/models.py) (models.py)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_api["HTTP API"]
  node_main["main.py<br/>FastAPI app<br/>[main.py]"]
  node_ticket_analyze["Analyze ticket<br/>POST /tickets/analyze<br/>[main.py]"]
  node_db_status["DB status<br/>GET /db/status<br/>[main.py]"]
  node_semantic_items["Cache items<br/>POST /semantic-cache/items<br/>[main.py]"]
  node_semantic_search["Cache search<br/>POST /semantic-cache/search<br/>[main.py]"]
  node_semantic_eval["Cache eval<br/>POST /semantic-cache/evaluate<br/>[main.py]"]
end

subgraph group_decision["Cache & Decision"]
  node_normalize["Normalize<br/>input prep<br/>[main.py]"]
  node_fingerprint["Fingerprint<br/>exact key<br/>[main.py]"]
  node_exact_cache[("Exact cache<br/>memory cache<br/>[main.py]")]
  node_semantic_flow{{"Semantic flow<br/>vector reuse<br/>[main.py]"}}
  node_response_shape["Response shape<br/>result metadata<br/>[main.py]"]
end

subgraph group_infra["Persistence & Model"]
  node_config["config.py<br/>settings & factories<br/>[config.py]"]
  node_db[("db.py<br/>Postgres setup<br/>[db.py]")]
  node_semantic_store[("Semantic store<br/>Postgres table<br/>[db.py]")]
  node_pgvector(("pgvector<br/>vector search<br/>[db.py]"))
  node_model_provider(("LLM provider<br/>external model"))
  node_schemas["models.py<br/>Pydantic schemas<br/>[models.py]"]
  node_logging["log_helpers.py<br/>structured logging<br/>[log_helpers.py]"]
end

node_main -->|"exposes"| node_ticket_analyze
node_main -->|"exposes"| node_db_status
node_main -->|"exposes"| node_semantic_items
node_main -->|"exposes"| node_semantic_search
node_main -->|"exposes"| node_semantic_eval
node_ticket_analyze -->|"prepares"| node_normalize
node_normalize -->|"feeds"| node_fingerprint
node_fingerprint -->|"checks"| node_exact_cache
node_exact_cache -->|"hit returns"| node_response_shape
node_fingerprint -->|"miss routes"| node_semantic_flow
node_semantic_flow -->|"uses"| node_config
node_config -->|"constructs"| node_model_provider
node_semantic_flow -->|"queries"| node_db
node_db -->|"manages"| node_semantic_store
node_semantic_store -->|"uses"| node_pgvector
node_semantic_flow -->|"misses call"| node_model_provider
node_model_provider -->|"produces"| node_response_shape
node_semantic_flow -->|"hit returns"| node_response_shape
node_response_shape -->|"write-through"| node_semantic_store
node_ticket_analyze -->|"logs"| node_logging
node_db_status -->|"probes"| node_db
node_semantic_items -->|"inserts"| node_db
node_semantic_search -->|"embeds"| node_config
node_semantic_search -->|"searches"| node_db
node_semantic_eval -->|"embeds"| node_config
node_semantic_eval -->|"evaluates"| node_db
node_main -->|"validates"| node_schemas

click node_main "https://github.com/devfullcycle/mba-ia-cache/blob/main/main.py"
click node_ticket_analyze "https://github.com/devfullcycle/mba-ia-cache/blob/main/main.py"
click node_db_status "https://github.com/devfullcycle/mba-ia-cache/blob/main/main.py"
click node_semantic_items "https://github.com/devfullcycle/mba-ia-cache/blob/main/main.py"
click node_semantic_search "https://github.com/devfullcycle/mba-ia-cache/blob/main/main.py"
click node_semantic_eval "https://github.com/devfullcycle/mba-ia-cache/blob/main/main.py"
click node_normalize "https://github.com/devfullcycle/mba-ia-cache/blob/main/main.py"
click node_fingerprint "https://github.com/devfullcycle/mba-ia-cache/blob/main/main.py"
click node_exact_cache "https://github.com/devfullcycle/mba-ia-cache/blob/main/main.py"
click node_semantic_flow "https://github.com/devfullcycle/mba-ia-cache/blob/main/main.py"
click node_response_shape "https://github.com/devfullcycle/mba-ia-cache/blob/main/main.py"
click node_config "https://github.com/devfullcycle/mba-ia-cache/blob/main/config.py"
click node_db "https://github.com/devfullcycle/mba-ia-cache/blob/main/db.py"
click node_semantic_store "https://github.com/devfullcycle/mba-ia-cache/blob/main/db.py"
click node_pgvector "https://github.com/devfullcycle/mba-ia-cache/blob/main/db.py"
click node_schemas "https://github.com/devfullcycle/mba-ia-cache/blob/main/models.py"
click node_logging "https://github.com/devfullcycle/mba-ia-cache/blob/main/log_helpers.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_main,node_ticket_analyze,node_db_status,node_semantic_items,node_semantic_search,node_semantic_eval toneBlue
class node_normalize,node_fingerprint,node_exact_cache,node_semantic_flow,node_response_shape toneAmber
class node_config,node_db,node_semantic_store,node_pgvector,node_model_provider,node_schemas,node_logging toneMint
```

## Components

### HTTP API

FastAPI entrypoints and request/response handling

- [main.py](https://github.com/devfullcycle/mba-ia-cache/blob/main/main.py): FastAPI app · Route orchestration, cache flow, and startup init · `main.py`
- [Analyze ticket](https://github.com/devfullcycle/mba-ia-cache/blob/main/main.py): POST /tickets/analyze · Primary request path for support-ticket analysis · `main.py`
- [DB status](https://github.com/devfullcycle/mba-ia-cache/blob/main/main.py): GET /db/status · Connectivity and pgvector/table diagnostics · `main.py`
- [Cache items](https://github.com/devfullcycle/mba-ia-cache/blob/main/main.py): POST /semantic-cache/items · Direct semantic-cache insert endpoint · `main.py`
- [Cache search](https://github.com/devfullcycle/mba-ia-cache/blob/main/main.py): POST /semantic-cache/search · Similarity search over stored embeddings · `main.py`
- [Cache eval](https://github.com/devfullcycle/mba-ia-cache/blob/main/main.py): POST /semantic-cache/evaluate · Threshold decision on best semantic match · `main.py`

### Cache & Decision

Normalization, fingerprinting, cache routing, and response shaping

- [Normalize](https://github.com/devfullcycle/mba-ia-cache/blob/main/main.py): input prep · Clean and standardize request text and context · `main.py`
- [Fingerprint](https://github.com/devfullcycle/mba-ia-cache/blob/main/main.py): exact key · Build exact-cache key from prompt and model context · `main.py`
- [Exact cache](https://github.com/devfullcycle/mba-ia-cache/blob/main/main.py): memory cache · In-memory exact-match cache for fast reuse · `main.py`
- [Semantic flow](https://github.com/devfullcycle/mba-ia-cache/blob/main/main.py): vector reuse · Route through embedding search and threshold evaluation · `main.py`
- [Response shape](https://github.com/devfullcycle/mba-ia-cache/blob/main/main.py): result metadata · Formats analysis output and cache outcome metadata · `main.py`

### Persistence & Model

Database, pgvector, embeddings, and model factories

- [config.py](https://github.com/devfullcycle/mba-ia-cache/blob/main/config.py): settings & factories · Loads env config and constructs model/embedding factories · `config.py`
- [db.py](https://github.com/devfullcycle/mba-ia-cache/blob/main/db.py): Postgres setup · Connection setup, vector extension, schema, and indexes · `db.py`
- [Semantic store](https://github.com/devfullcycle/mba-ia-cache/blob/main/db.py): Postgres table · Durable cache table with VECTOR(1536) embeddings · `db.py`
- [pgvector](https://github.com/devfullcycle/mba-ia-cache/blob/main/db.py): vector search · Similarity distance and vector operations in Postgres · `db.py`
- **LLM provider**: external model · External AI provider used on semantic misses
- [models.py](https://github.com/devfullcycle/mba-ia-cache/blob/main/models.py): Pydantic schemas · Request and response contracts · `models.py`
- [log_helpers.py](https://github.com/devfullcycle/mba-ia-cache/blob/main/log_helpers.py): structured logging · Block-style logging for main request flows · `log_helpers.py`

## Connections

- main.py → Analyze ticket: exposes · Registers the primary analysis endpoint
- main.py → DB status: exposes · Registers diagnostics endpoint
- main.py → Cache items: exposes · Registers direct cache insert endpoint
- main.py → Cache search: exposes · Registers semantic search endpoint
- main.py → Cache eval: exposes · Registers semantic evaluation endpoint
- Analyze ticket → Normalize: prepares · Normalizes incoming ticket content and context
- Normalize → Fingerprint: feeds · Produces the exact-match cache key
- Fingerprint → Exact cache: checks · Looks up in-memory exact cache first
- Exact cache → Response shape: hit returns · Bypasses vector search and model on a hit
- Fingerprint → Semantic flow: miss routes · Falls through to semantic reuse when exact hit misses
- Semantic flow → config.py: uses · Needs embedding/model factories and settings
- config.py → LLM provider: constructs · Builds the model and embedding clients
- Semantic flow → db.py: queries · Searches persisted semantic cache in Postgres
- db.py → Semantic store: manages · Creates and owns cache table and indexes
- Semantic store → pgvector: uses · Stores embeddings and performs distance search
- Semantic flow → LLM provider: misses call · Invokes model only when semantic match is rejected
- LLM provider → Response shape: produces · Generates analysis response payload
- Semantic flow → Response shape: hit returns · Returns reused semantic response when accepted
- Response shape → Semantic store: write-through · Persists only model-generated answers to semantic cache
- Analyze ticket → log_helpers.py: logs · Structured logging around request lifecycle
- DB status → db.py: probes · Checks connectivity, extension, and table presence
- Cache items → db.py: inserts · Directly writes semantic-cache items
- Cache search → config.py: embeds · Normalizes and embeds search input
- Cache search → db.py: searches · Runs vector similarity queries
- Cache eval → config.py: embeds · Normalizes and embeds evaluation input
- Cache eval → db.py: evaluates · Finds top candidate and applies threshold
- main.py → models.py: validates · Uses request/response schemas
