Skip to content
mentoor

Embeddings beyond search

For engineers

Embeddings for clustering, dedup and classification, with metrics and Postgres storage.

Embeddings turn text into vectors, and the same vectors can find duplicates, group themes and label intents, as long as the threshold is measured, the model is versioned and exact or live data stays out of the index.

The case

Kestrel Support is the help desk of a small invoicing app. Its Postgres database holds 180,000 tickets and grows by about 20,000 a month. Three problems keep coming back. Agents answer the same fault several times because the new ticket is worded differently from an open one. The Monday meeting has no view of what customers wrote about last week. And routing by intent (billing, bug, how-to, cancellation, account, other) is done by hand.

The team does not need a chatbot. It needs one tool, embeddings, used three ways: duplicate flags, theme clusters and an intent classifier. Five skills decide whether this works.

What embeddings are for here (llm-embeddings)

An embedding model maps a text to a list of numbers so that texts about the same thing sit close together. Cosine similarity measures how close. Three uses follow. Dedupe: compare a new ticket to the open ones and flag the near ones. Clustering: group a week of tickets by similarity to find themes. Classification: label a ticket by the labels of its nearest labelled neighbours, or with a small classifier trained on the vectors.

Know the limits. Similarity means "about the same thing", not "means the same". "Refund approved" and "refund declined" score high. Exact codes such as ERR-4021 blur into ERR-4012. Pair embeddings with a keyword or exact match for codes, and keep a human in the loop where an opposite meaning is costly.

Choose and store the model (rag-embeddings)

Do not pick a model from a leaderboard. Label about 40 real pairs of your own tickets, and compare candidates on recall@5. A cheaper, smaller model often wins on your own text. Count storage: 180,000 rows x 1,024 dimensions x 4 bytes is about 740 MB of raw vectors.

Vectors from different models are not comparable, and neither are their score thresholds. Store the model version and a hash of the embedded text with every vector. A migration then becomes a backfill into a versioned index, a retuned threshold and a rollback path.

Keep it in Postgres (dataeng-postgres)

At this size, the pgvector extension keeps vectors next to the tickets. One database means one transaction and real filters.

ALTER TABLE tickets ADD COLUMN embedding vector(1024);
CREATE INDEX tickets_emb_idx ON tickets USING hnsw (embedding vector_cosine_ops);
SELECT id FROM tickets WHERE status = 'open'
ORDER BY embedding <=> $1 LIMIT 5;

Three details cause most bugs. The column dimension must match the model. The index operator class must match the operator in the query. And <=> returns a distance, so similarity 0.92 means a distance of 0.08. With an approximate index, a filter such as status = 'open' runs after the index returns its candidates, so a query can return fewer rows than the limit; the pgvector README describes this and the hnsw.ef_search setting.

Measure before you merge (ml-metrics)

A duplicate flagger is a classifier, so score it. Precision is the share of flags that were right. Recall is the share of real duplicates found. Wrongly merging two tickets loses a customer's request, so Kestrel sets a precision floor of 0.97 for auto-merge and takes the lowest threshold that meets it. Pairs below that go to an agent as suggestions. For intent classification, never judge by accuracy when one class is 3.5% of the data, and split train and test by duplicate group so the nearest neighbour is not a copy of the answer.

Know what to leave out (rag-when)

This design has no RAG pipeline, because nothing writes an answer from retrieved text. It also leaves some questions out of the index. "What is the status of invoice INV-20418?" has an exact key and a live value, so it is a database query or a tool call. Copying invoice status into an index nightly makes a confident, wrong answer. For routing, a classifier on embeddings is the first baseline, and a chat model is the comparison, not the start.

Before and after

Before: the team sets the cut-off at 0.90 because it "looks right", mixes old and new vectors after a model change and reports 97% accuracy from a random split.

After: the cut-off comes from 1,000 labelled pairs and a precision floor, every vector carries its model version, and accuracy is reported per class on a duplicate-safe split.

What still goes wrong

  • A threshold tuned on one model is reused on another.
  • A dimension, operator class or distance-versus-similarity slip makes a query slow or backwards.
  • Clusters are used for routing though they group by topic, not outcome.
  • Live or exact data is copied into the index and goes stale.

The questions that follow ask you to make these calls on real artefacts.

Steps

  1. Decide which jobs embeddings should do

    Skill: llm-embeddings

    Write down each job, the method and its weak spot. Embeddings suit meaning-based jobs: dedupe, themes and intent. Exact codes need a keyword match, and pairs whose meaning flips (approved versus declined) need a human check.

    Jobs and methods
    JobMethodWeak spot
    Duplicate flagCosine similarity to open ticketsOpposite outcomes score high
    Weekly themesClustering on vectorsGroups by topic, not outcome
    Intent labelClassifier on vectorsRare classes hide behind accuracy
    Find ERR-4021Exact or full-text matchVectors blur near codes
  2. Pick the model on your own labelled pairs

    Skill: rag-embeddings

    Label about 40 real ticket pairs and score each candidate on recall@5. Record dimensions, price and latency. Leaderboard rank is a hint, not a result. Tag every stored vector with the model version and a hash of the embedded text.

    Model test on 40 pairs
    ModelRecall@5Dimensions
    Model X0.713072
    Model Y0.841024
    Model Z0.801536
  3. Store vectors next to the tickets

    Skill: dataeng-postgres

    Add a vector column that matches the model's dimension and an HNSW index whose operator class matches the query's operator. Query with the cosine distance operator and remember that the status filter runs after the approximate scan.

    pgvector setup
    ALTER TABLE tickets ADD COLUMN embedding vector(1024);CREATE INDEX tickets_emb_idx ON tickets  USING hnsw (embedding vector_cosine_ops);SELECT id FROM tickets WHERE status = 'open'ORDER BY embedding <=> $1 LIMIT 5;
  4. Set the duplicate threshold from precision and recall

    Skill: ml-metrics

    Score the flagger on labelled pairs at several thresholds. Because a wrong merge loses a request, set a precision floor for auto-merge and take the lowest threshold that meets it. Send lower-scoring pairs to an agent as suggestions.

    Threshold sweep
    ThresholdPrecisionRecall
    0.950.990.41
    0.920.970.58
    0.900.910.70
    0.850.780.86
  5. Leave live and exact questions out of the index

    Skill: rag-when

    Ask of each request: does it need meaning, or an exact key and a current value? Invoice status is a live lookup, so use SQL or a tool call. Use embeddings for similar tickets. Compare a classifier on vectors with a chat model before choosing either for routing.

  6. Plan the next model change before it happens

    Skill: rag-embeddings

    When a better model arrives, backfill a new versioned column or index, retune the threshold on labelled pairs, check recall again and keep the old index for a short rollback window. Never search old vectors with new-model queries.

    Model migration

    Goal: Move to a new embedding model with no bad merges

    1. Add a model_version column and tag existing rows
    2. Backfill new vectors into a separate versioned index
    3. Re-run the labelled pairs and retune the threshold
    4. Switch queries to the new index
    5. Keep the old index for a week, then drop it

Skills this scenario uses

Where to study