Rafael Andrade
  • PT
  • EN (current language)
All projects

Full stack application · Recommender system

Cheiro Agradável

A perfume recommendation engine driven by data and vector similarity, where the LLM only writes the explanation.

  • NestJS, Prisma and PostgreSQL with pgvector
  • Hybrid ranking with 7 configurable criteria
  • Unit, integration and component tests
Type
Personal project
Period
Dec 2026
Stack
NestJS, Prisma, PostgreSQL, pgvector
Cheiro Agradável sign-in screen (in Portuguese): the headline “From what you already wear to your next bottle, for each occasion”, an illustration of perfume test strips fanned out and the login form.
Sign-in screen, with the catalog size in the footer: 1,479 perfumes, 420 notes and 160 houses. Captured with the project running locally through Docker Compose. The interface is in Portuguese.

Architecture overview

  1. 01Input

    • Mode 1 · favorites — Input

      1 to 3 perfumes; vector = centroid of the stored embeddings

    • Mode 2 · preferences — Input

      families, notes and styles become an embedded document

  2. 02Retrieval

    • Vector search — Data

      pgvector, cosine, HNSW index · up to 200

    • Structural search — Data

      SQL over shared notes and families · up to 80

  3. 03Ranking

    • Weighted scorers — Deterministic code

      vector, notes, family, character, occasion, intensity, affinity

    • Penalties — Deterministic code

      rejected notes, unsuitable occasion, similarity to disliked perfumes

      fewer than 3 above 0.55 → reports there aren’t enough results

  4. 04Diversity

    • MMR — Deterministic code

      max. 2 per brand and 1 flanker per line

  5. 05Explanation

    • LLM via OpenRouter — Language model

      strict JSON Schema, model chain with fallback

    • Reconciliation — Deterministic code

      accepts only candidate ids and notes the perfume actually has

      failure or timeout → deterministic template

  6. 06Output

    • Result + history — Output

      stores the ranking, classifier and model versions

  • Input and output
  • Deterministic code
  • Language model
  • Data
How one recommendation flows. The LLM only steps in after the ranking has already chosen the perfumes.

01Context and problem

Perfume recommendations usually depend on a salesperson’s opinion or on generic lists. A chatbot could handle the conversation, but it might make up perfumes, notes and claims that nobody can verify.

The challenge was to recommend from real catalog data — scent notes, families, concentration — and still explain why in Portuguese, without the explanation contradicting the data.

02Goal

Build a recommendation engine where every decision is traceable: each recommended perfume comes from the database, each criterion has an explicit weight, and the LLM only drafts the explanation, under validation.

Ship it as a complete application — accounts, profile, favorites, history, feedback and refinements — with a reproducible Docker setup for development, testing and production.

03How it works

  1. 1.

    Scent profile

    In favorites mode, the search vector is the centroid of the stored embeddings of the chosen perfumes, with no external call. In preferences mode, families, notes, styles and intensity become a document in the same format as the perfumes, embedded with the same model.

  2. 2.

    Hybrid retrieval

    Two searches run in parallel: cosine similarity in pgvector and an SQL query that scores shared notes and families. Their union forms the candidate set.

  3. 3.

    Occasion of use

    The dataset has no occasion data. A deterministic classifier computes, for each perfume, a 0-to-1 score across 9 occasions from real data — character, family, seasons, time of day, concentration and estimated intensity — and stores the factors behind each score.

  4. 4.

    Ranking

    Each criterion is a class with a weight defined in ranking.config.ts. The final score is the weighted average of the applicable criteria minus the penalties. With fewer than three perfumes above 0.55, the response says there aren’t enough results instead of padding the list.

  5. 5.

    Diversification

    Maximal Marginal Relevance picks the result set by balancing relevance against redundancy, with at most two perfumes per brand and one flanker per line.

  6. 6.

    Explanation

    The LLM receives the already-chosen candidates and returns JSON in a strict schema, validated with Zod. Reconciliation discards ids that aren’t candidates and notes the perfume doesn’t have. If the model chain fails or the deadline runs out, the explanation comes from a deterministic template.

  7. 7.

    Feedback and refinement

    “Liked it” pulls the next searches toward that perfume, “didn’t like it” excludes it and penalizes similar ones, and refinements such as “fresher” or “more intense” produce a new recommendation linked to the original one.

System screens

“New recommendation” form with Libre (Yves Saint Laurent) and Sauvage Elixir (Dior) already picked and a search for “Bleu” listing perfumes with each one’s brand and olfactory family.
Mode 1: the person picks up to three perfumes they already wear. The search queries the catalog and shows each result’s olfactory family.
“What I like” mode in the dark theme, with three olfactory families and the Woody and Spicy styles selected.
Mode 2, in the dark theme: favorite families, styles and notes become a document that is turned into an embedding.
Home screen on a phone with the two ways to ask for a recommendation.
The same interface on a 390 px screen.

04Technical architecture

NestJS backend and React frontend in the same repository, orchestrated by Docker Compose with development (hot reload), production and test configurations.

  • NestJS backend

    Modules by domain: auth, users, catalog, catalog-import, features, embeddings, recommendation, explanation and feedback. Environment variables validated with Zod at startup, structured logs with pino and Swagger documentation.

  • PostgreSQL + pgvector

    Catalog, users, history and vectors in the same database. A vector(1024) column with an HNSW index created in SQL in the migration — Prisma can’t express that index type — and pg_trgm for text search.

  • Bootstrap service

    Runs once per startup, guarded by an advisory lock: applies migrations, imports the catalog idempotently (by content hash), computes the derived features and generates only the pending embeddings.

  • React frontend

    React 19, Vite, Tailwind and TanStack Query. Screens for sign-in, dashboard, recommendation, results, history and profile, with an accessible autocomplete.

  • Production

    Compiled images running as an unprivileged user, nginx serving the frontend and proxying /api on the same origin, database and API on internal networks. Deploy and backup scripts for a VPS with Caddy.

05Technologies

Backend
NestJS 12 · Prisma 7 · Zod · pino · Swagger · argon2
Data
PostgreSQL 18 · pgvector (HNSW) · pg_trgm
AI
OpenRouter (embeddings and chat) · LangSmith (optional)
Frontend
React 19 · Vite · Tailwind CSS 4 · TanStack Query
Infra and tests
Docker Compose · nginx · Caddy · Jest · Vitest · Testing Library

06Engineering decisions

  • The LLM doesn’t pick perfumes

    The ranking is deterministic and auditable; the model only drafts the explanation for candidates that were already chosen. That removes the worst failure — recommending something that doesn’t exist — and makes it possible to switch models without changing the result.

  • Negation becomes a penalty, not text

    Embeddings represent sentences like “I don’t like vanilla” poorly. Instead of embedding the rejection, the system applies it as an explicit penalty, larger when the note sits in the heart or base of the pyramid.

  • Profile and catalog in the same vector space

    The document built from the preferences follows the perfume template and uses the same model. Each vector stores the model, dimension, template version and text hash: switching models reindexes everything, and search only uses vectors from the active model.

  • Weights in versioned configuration

    Weights, penalties and diversity limits live in a configuration file validated with Zod. The ranking, occasion classifier and embedding model versions are recorded with every recommendation, which makes it possible to compare results across versions.

  • Secure sessions without unnecessary complexity

    A short-lived access token and a refresh token in an httpOnly cookie with rotation; reusing a revoked refresh token revokes all of the user’s sessions. Passwords use argon2, and login checks a dummy hash when the email doesn’t exist, so response time doesn’t reveal which accounts exist.

07Technical challenges

  • Quotas and instability of free models

    Free OpenRouter models have a daily limit and can be taken offline — one of them was during development. The answer was a model chain with fallback, a cooldown for models that return 429, a total deadline for the explanation and a cache for query embeddings.

  • Occasion with no source data

    The dataset has no occasion of use, yet occasion weighs 0.25 in the ranking — the highest weight in preferences mode. It took a heuristic classifier that derives the score from real data and stores the factors, so the decision stays explainable and tunable.

  • Results that were too similar

    High similarity tends to return several flankers of the same perfume. MMR diversification and the per-brand and per-line limits fix that without giving up relevance.

  • Repeatable bootstrap

    The first startup has to migrate the database, import 1,479 perfumes, compute features and index embeddings. The bootstrap service does that idempotently and under a lock, without running in parallel or reprocessing what is already up to date.

08What was implemented

  • Sign-up, login, session renewal and logout
  • Profile with preferences, avoided notes and favorites
  • Recommendations from favorites or preferences, across 9 occasions of use
  • Hybrid ranking, penalties and MMR diversification
  • LLM explanation with validation and template fallback
  • Feedback (liked, disliked, already know it) and refinements
  • Recommendation history
  • Idempotent import of the Scento catalog (1,479 perfumes, CC BY 4.0)
  • Unit tests, integration tests with a test database and simulated AI, and frontend component tests
  • Development and production Compose files, deploy and backup scripts

09Possible next steps

Future improvements — not implemented yet

  • Move rate limiting to Redis if the API ever runs with several replicas (it is in memory today, a documented decision).
  • Add price, image and longevity once there is a properly licensed data source — new criteria go in as new scorer classes.
  • Publish a demo instance.

10Code and demo