🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Generative AI Recommendation Systems in Practice

đŸŸĸ Free Lesson

Recommendation Systems with Generative AI

A recommender is a funnel that trades precision for coverage at every stage — and LLMs change which stage is expensive.

Personalization

Prerequisites

  • !Collaborative filtering and matrix factorization ideas
  • !Dot-product retrieval and approximate nearest neighbors
  • !Train-serving skew and feature stores

What You'll Learn

  • 1Split a recommender into candidate generation, ranking and re-ranking with a recall target per stage
  • 2Explain why two-tower models replaced item-item similarity at scale
  • 3Use an LLM where it adds value instead of where it adds latency
  • 4Read offline metrics without confusing them for business outcomes

A recommender is a funnel before it is a model

Start from the numbers. A catalog with ten million items and a user who will look at six results means the system must reduce ten million options to a handful while spending a few hundred milliseconds. No single model does that honestly. Production systems therefore cascade: a cheap stage retrieves a few thousand plausible items, a heavier stage scores them, and a final stage reshapes the list for diversity, freshness and business rules.

Each stage has its own job and its own acceptable failure. Candidate generation optimizes recall — the right item must survive — because a perfect ranker cannot resurface an item it never received. Ranking optimizes precision on what survived. Re-ranking optimizes satisfaction, which is deliberately not the same as predicted click probability: showing five near-identical videos technically maximizes an engagement model's score while producing a worse session.

The funnel framing also dictates where compute goes. Millions of items justify a model that runs only on a pre-filtered subset, which is why the ranking model can afford features the retrieval stage cannot. When teams report that a fancy model "did not help", the first question is whether it was wired into the stage where its strengths matter.

Candidate generation at catalog scale

The historical approaches still appear in production. Collaborative filtering reads interaction patterns — users who bought this also bought that — and works beautifully until sparsity or novelty breaks it. Content-based matching uses item attributes and survives sparsity but cannot discover taste beyond what the metadata encodes.

The workhorse today is the two-tower model: one neural network embeds the user, another embeds each item, and the dot product of the two vectors is the score. Because items can be embedded offline and stored in an approximate nearest neighbor index, serving a request is a single user forward pass followed by a fast index lookup, regardless of catalog size.

python
import torch
import torch.nn as nn

class TwoTowerRecommender(nn.Module):
    """User and item towers producing a shared embedding space."""

    def __init__(self, n_users, n_items, embed_dim=128, hidden=(512, 256)):
        super().__init__()
        self.user_emb = nn.Embedding(n_users, embed_dim)
        self.item_emb = nn.Embedding(n_items, embed_dim)

        def tower():
            layers, d = [], embed_dim * 2
            for h in hidden:
                layers += [nn.Linear(d, h), nn.ReLU(), nn.Dropout(0.2)]
                d = h
            layers.append(nn.Linear(d, embed_dim))
            return nn.Sequential(*layers)

        self.user_tower = tower()
        self.item_tower = tower()

    def forward(self, users, items, labels=None):
        u = torch.cat([self.user_emb(users), users.float().unsqueeze(1)], dim=1)
        i = torch.cat([self.item_emb(items), items.float().unsqueeze(1)], dim=1)
        u_vec = nn.functional.normalize(self.user_tower(u), dim=-1)
        i_vec = nn.functional.normalize(self.item_tower(i), dim=-1)
        logits = (u_vec * i_vec).sum(dim=-1)
        if labels is None:
            return logits
        return nn.functional.binary_cross_entropy_with_logits(logits, labels.float())

Train it with in-batch negatives: every item a different user in the same batch interacted with serves as a negative for everyone else. It is a cheap approximation of the true negative distribution, and it works because most items any given user did not choose are genuinely irrelevant to them.

Ranking with context, not just identity

Once a few thousand candidates survive, the ranker can afford to look at everything: session history, item freshness, cross-feature interactions, predicted dwell time and popularity priors. Gradient-boosted trees still win many of these battles because the features are heterogeneous and missing values are common, though deep ranking models with explicit feature crosses have closed the gap.

The subtle part is training data. Everything the ranker learns comes from logs produced by the previous policy, so positions the old system never showed are missing from the data entirely. Position bias correction — either including position as a feature and discarding it at serving time, or inverse-propensity weighting the loss — is not optional if you want predictions that reflect relevance rather than presentation.

python
import lightgbm as lgb

FEATURES = [
    "user_item_dot", "item_age_hours", "user_hist_item_sim",
    "session_click_count", "item_popularity_7d", "price_percentile",
    "device_type", "hour_of_day", "position_in_candidate_list",
]

def train_ranker(train_rows, valid_rows):
    ds_train = lgb.Dataset(train_rows[FEATURES], label=train_rows["clicked"])
    ds_valid = lgb.Dataset(valid_rows[FEATURES], label=valid_rows["clicked"], reference=ds_train)
    return lgb.train(
        {
            "objective": "lambdarank",
            "metric": "ndcg",
            "ndcg_eval_at": [5, 10],
            "learning_rate": 0.05,
            "num_leaves": 63,
            "min_data_in_leaf": 200,
        },
        ds_train,
        num_boost_round=400,
        valid_sets=[ds_valid],
        callbacks=[lgb.early_stopping(50)],
    )

Evaluate with ranking metrics — normalized discounted cumulative gain at ten, mean reciprocal rank — rather than accuracy, because ordering the top results correctly is the only thing the user sees.

Where generative models genuinely help

An LLM is a poor replacement for a ranker that must score ten thousand items in ten milliseconds, and teams that try to make it one usually regret the latency bill. The leverage is elsewhere: generative models excel at understanding text, filling gaps and producing artifacts the structured pipeline cannot.

Four uses have proven practical. Generative rewrites turn terse item metadata into rich descriptions that improve both embedding quality and user comprehension. Query rewriting converts a vague search phrase into a structured intent the retriever can act on. Conversational recommendation lets a user refine by describing taste in plain language instead of filtering on facets. And explanation generation produces the "because you watched" copy that measurably improves click-through when it is grounded in real signals rather than invented.

python
from openai import OpenAI

client = OpenAI()

def rewrite_query(raw_query, session_context):
    """Turn a vague request into retrieval-ready constraints."""
    response = client.chat.completions.create(
        model="gpt-4o-mini",
        temperature=0,
        messages=[
            {
                "role": "system",
                "content": "Convert the user request into JSON with keys "
                           "intent, must_have, avoid, budget, style.",
            },
            {
                "role": "user",
                "content": f"Context: {session_context}\nRequest: {raw_query}",
            },
        ],
        response_format={"type": "json_object"},
    )
    return response.json.loads(response.choices[0].message.content)

def explain_ranking(user_history, chosen_item):
    response = client.chat.completions.create(
        model="gpt-4o-mini",
        temperature=0.4,
        max_tokens=60,
        messages=[
            {
                "role": "system",
                "content": "Explain the recommendation in one sentence, "
                           "grounded only in the provided history. Never invent facts.",
            },
            {"role": "user", "content": f"History: {user_history}\nItem: {chosen_item}"},
        ],
    )
    return response.choices[0].message.content.strip()

Both calls must stay off the critical path where possible — precompute rewrites, cache explanations, and let a failure fall back to the structured pipeline rather than blocking the response.

Cold start, freshness and feedback loops

New users and new items are the standing failure mode. With no interactions, collaborative signal is empty, so systems fall back to content features, popularity priors and explicit onboarding questions. New items are worse: nothing recommends an item nobody has clicked, so it never accrues the signal that would make it recommendable. Deliberate exploration — reserving a slice of inventory for items with insufficient exposure — is the standard fix, and it doubles as your measurement of the problem.

python
def score_with_exploration(base_scores, item_stats, epsilon=0.05, min_exposures=200):
    """Epsilon-greedy boost for items starved of exposure."""
    boosted = []
    for score, stats in zip(base_scores, item_stats):
        if stats["impressions"] < min_exposures:
            boosted.append(score + epsilon)
        else:
            boosted.append(score)
    return boosted

Feedback loops deserve equal suspicion. Recommending only what a model already predicts will be clicked narrows the catalog the user ever sees, which narrows the training data, which narrows the model. Measurement holds it off: track catalog coverage, how much of the item inventory receives impressions at all, and the entropy of the recommendation distribution alongside click-through rate.

Offline numbers versus online reality

Offline metrics are necessary and insufficient. They let you reject bad candidates cheaply, but they inherit the logging policy that produced them and cannot measure effects on retention, session depth or satisfaction that only appear over weeks.

MetricWhat it capturesWhat it misses
NDCG at 10Ordering quality of the shown listItems never retrieved
Recall at 100Whether the answer survived to the rankerWhether users liked it
Catalog coverageBreadth of inventory receiving trafficQuality of those impressions
Online A/B click-throughReal user response under real policyLong-term saturation effects
Online A/B session depthSustained engagementNovelty effects in short tests

Run offline evaluation as a gate on every candidate model, then let a controlled online experiment decide promotion. Guard the experiment against novelty effects by running it long enough for initial curiosity to decay, and watch for regressions in segments — a model that lifts the average while hurting the smallest cohort is not an improvement you can keep.

💡Retrieval recall is the ceiling

If the right item never reaches the top thousand candidates, no amount of ranker sophistication recovers it. Measure stage-level recall before blaming the model that saw the candidates.

Common Mistakes

Calling an LLM for every item score in the ranking stage

Fix: Use the LLM for understanding and generation at the edges; keep per-item scoring on models built for millions of calls.

Training a ranker on logs without correcting position bias

Fix: Include position as a training-only feature or apply inverse-propensity weighting so scores reflect relevance.

Optimizing click-through rate alone

Fix: Track coverage, session depth and long-horizon retention together — clicks alone reward shallow, repetitive lists.

Best Practices

  • Design the funnel first and set an explicit recall target for candidate generation
  • Train two-tower retrieval with in-batch negatives and normalize embeddings before indexing
  • Correct position bias before trusting any logged-label ranking model
  • Keep generative calls off the critical path with caching and structured fallbacks
  • Reserve exploration inventory so new items can accumulate signal

Key Takeaways

  • Recommendations are a funnel: recall in candidate generation, precision in ranking, satisfaction in re-ranking
  • Two-tower models make serving a catalog-scale lookup rather than a full scan
  • Logged training data reflects the old policy, so position bias must be corrected explicitly
  • Generative models earn their place in rewriting, explanation and conversational refinement
  • Offline metrics gate candidates; only online experiments promote them
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Generative AI Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement