How devfullcycle/mba-ia-cache works
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 main.py · db.py db.py · config.py config.py · models.py models.py
Components 18
HTTP API
FastAPI entrypoints and request/response handling
- main.py · Route orchestration, cache flow, and startup init
main.py - Analyze ticket · Primary request path for support-ticket analysis
main.py - DB status · Connectivity and pgvector/table diagnostics
main.py - Cache items · Direct semantic-cache insert endpoint
main.py - Cache search · Similarity search over stored embeddings
main.py - Cache eval · Threshold decision on best semantic match
main.py
Cache & Decision
Normalization, fingerprinting, cache routing, and response shaping
- Normalize · Clean and standardize request text and context
main.py - Fingerprint · Build exact-cache key from prompt and model context
main.py - Exact cache · In-memory exact-match cache for fast reuse
main.py - Semantic flow · Route through embedding search and threshold evaluation
main.py - Response shape · Formats analysis output and cache outcome metadata
main.py
Persistence & Model
Database, pgvector, embeddings, and model factories
- config.py · Loads env config and constructs model/embedding factories
config.py - db.py · Connection setup, vector extension, schema, and indexes
db.py - Semantic store · Durable cache table with VECTOR(1536) embeddings
db.py - pgvector · Similarity distance and vector operations in Postgres
db.py - LLM provider · External AI provider used on semantic misses
- models.py · Request and response contracts
models.py - log_helpers.py · Block-style logging for main request flows
log_helpers.py
Connections 27
- 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