The easiest way to build an AI recommendation system is to let the model browse the catalog, reason in a loop, and pick products.
That is also the fastest way to lose control of ranking behavior.
When I built ai-florist, I wanted the opposite property: if a recommendation is wrong, I want to know which layer was wrong. Was intent parsing bad? Did delivery filtering remove too much? Did vector retrieval miss the right candidates? Were the scoring weights off? Did the rationale overstate the fit?
That requirement leads to a very different design from the usual "agent with tools" pattern. The LLM is still there, but it is treated like a narrow component with typed inputs and typed outputs. The engine that decides what to show is deterministic, observable, and debuggable.
This article is the engineering companion to What agentic commerce actually requires in production. That piece makes the architectural argument. This one walks through the implementation.
Start with boundaries, not prompts
The first decision was not prompt design. It was API design.
In the current stack there are two distinct entry points:
POST /api/recommendfor direct recommendation requestsPOST /api/conversation/turnfor the guided conversational flow
That split matters. The direct recommendation path is basically ranking plus presentation. The conversational path is orchestration: routing, guided data collection, delivery checks, recommendation, upsell, and checkout handoff.
The repo reflects that separation:
frontend/contains the Next.js storefront and chat UIbackend/contains the FastAPI APIs, conversation graph, retrieval, ranking, and monitoringcore/contains shared catalog schemas and ORM modelsdata_collection/handles catalog collection, ingestion, and normalizationeval-phoenix/handles offline quality evaluation
That sounds banal, but it avoids one of the most common GenAI architecture mistakes: letting "the chat system" become the whole system.
Where the LLM is allowed to matter
The system does use the model. It just uses it in places where language is the hard part, not correctness.
In practice there are three core LLM touchpoints in the backend:
1. Intent parsing
backend/app/services/intent_parser.py turns user text into a typed ParsedIntent.
The important detail is that this module does not return prose. It returns structure. If the model is available, parse_intent() calls the provider and normalizes the result. If it is unavailable or invalid, the service raises IntentParsingUnavailableError instead of pretending the parse was trustworthy.
That is a very different contract from "send a prompt and trust the answer." The downstream system only reads fields such as budget, occasion, colors, tone tags, or persona choice.
2. Scope classification
backend/app/services/scope_guard.py is a good example of how to use an LLM without letting it become a single point of failure.
The happy path is model-based scope classification. But before that, there are deterministic checks for obvious prompt injection and hard refusals. And if the model is unavailable, the code drops to _deterministic_scope_fallback() rather than blocking the whole conversation.
That design gives you graceful degradation instead of binary uptime.
3. Rationale generation
backend/app/ranking/rationale.py writes the one-line explanation shown on each product card.
This is the one place where free-form generation is actually useful. The ranking has already happened. The product is already selected. The model is not deciding. It is translating deterministic selection into human-readable copy.
Even here, the code has a deterministic backstop: deterministic_rationale(). So if the provider fails, the card still ships with grounded explanation text.
Here is what the output looks like when the pipeline works correctly. A customer asks for roses with no budget limit — the retrieval pipeline filters to rose-based bouquets, scores by semantic fit and price tier, and the LLM writes per-card rationale grounded in the actual product data:
A guided conversation where the customer asks for roses with no budget limit, resulting in three rose-based bouquet recommendations with per-card rationale explaining the selection
Each card includes the rationale text, price, availability, and occasion tags. The selection is deterministic and reproducible — the same intent, constraints, and catalog state will produce the same ranking every time.
The recommendation engine is not the graph
One thing I would emphasize for engineers: the LangGraph orchestrator is not the recommendation engine. It is the conversation coordinator.
The orchestrator lives in backend/app/services/conversation/graph_orchestrator.py. Right now it compiles a LangGraph with roughly two dozen named nodes: router, persona choice, delivery collection, budget collection, recommendation, recovery, upsell, checkout, and a few refusal or fallback paths.
That graph is useful because the conversational flow is stateful and branchy. It keeps the shopping interaction legible.
But the actual recommendation logic is not buried in graph prompts. It is mostly concentrated in a much simpler path:
backend/app/services/recommendation.pybackend/app/retrieval/service.pybackend/app/retrieval/scoring.pybackend/app/ranking/rationale.py
That separation is intentional. I want to be able to improve ranking without editing conversation logic, and improve conversation logic without touching retrieval math.
The retrieval path in code
At a high level, build_recommendations() and recommend_for_context() both funnel into retrieve_candidates().
The retrieval service does four things in order:
- Build query embeddings and pull vector candidates when possible
- Apply deterministic catalog constraints
- Score candidates with multiple explicit signals
- Deduplicate and cap the result set
That ordering is visible in backend/app/retrieval/service.py:
vector_scores = _vector_similarity_scores(request)
filtered_products = _vector_candidate_pool(request, month, vector_scores, catalog_snapshot)
if not filtered_products:
filtered_products = _deterministic_candidate_pool(request, month, catalog_snapshot)
if not filtered_products:
filtered_products = _fallback_product_pool(request, catalog_snapshot)The shape of the logic matters more than the exact code. It says:
- try semantic retrieval first when embeddings are available
- keep deterministic pool building as a first-class path
- keep a broader fallback pool so the system can degrade instead of going empty
That is much safer than putting every failure mode behind one opaque "agent" abstraction.
pgvector is useful, but only after you constrain the search
Vector search is used in _vector_similarity_scores(), backed by pgvector and text-embedding-3-small.
The implementation already bakes in some pragmatic constraints:
- it scopes search to the active merchant provider
- it filters by product availability in SQL
- it applies budget bounds in SQL when those are known
- it caps the vector result window before ranking
That keeps the embedding layer from pretending it knows business truth it does not actually know.
Semantic retrieval is good at "this feels close." It is bad at "this can be delivered tomorrow to this postal code and still respects the user's budget." Those checks live elsewhere, and that is exactly where they belong.
Scoring is explicit, not mystical
After candidate retrieval, backend/app/retrieval/scoring.py converts each candidate into five explicit feature groups:
- semantic score
- occasion match score
- style and tone match score
- price fit score
- business score
The default weights are:
DEFAULT_SCORING_WEIGHTS = ScoringWeights(
semantic_score=0.45,
occasion_match_score=0.25,
style_tone_match_score=0.15,
price_fit_score=0.10,
business_score=0.05,
)That alone already makes the system much easier to reason about than an LLM picking products directly. If a result feels wrong, you can inspect the score components and see whether the issue is semantic over-weighting, weak occasion tagging, poor price fit, or bad business-rule calibration.
The part I particularly like here is that the weights are not frozen forever. get_runtime_scoring_weights() can learn adjusted weights from observed recommendation sessions and positive events, while blending back toward the defaults when there is not enough data.
So the ranking system is neither:
- fully hand-tuned forever
- nor fully surrendered to the model
It is a deterministic scorer with a controlled learning loop.
Business rules live outside prompts
Commerce systems always have operator logic that should not be hidden inside prompt text.
In this repo, delivery feasibility and provider-specific business rules are loaded from config-backed files in backend/app/tools/. backend/app/tools/simulation.py loads provider-specific YAML and exposes checks like:
check_delivery_feasibility()product_is_available_for_context()
That means campaign logic, serviceable zones, blocked dates, and product-level exceptions can be applied as code and config, not as "please remember this" instructions to a model.
This is one of the core differences between a demo and a system. In a demo, prompts are often used as policy storage. In a system, prompts should not be your policy database.
Fallbacks are part of the design, not an embarrassment
Most GenAI systems have fallbacks. Few of them admit it cleanly.
This stack has several, and I think that is healthy:
- deterministic scope fallback when model classification is unavailable
- deterministic rationale generation
- deterministic candidate pool when vector retrieval yields nothing useful
- keyword catalog search as a last resort
The keyword fallback lives in backend/app/tools/catalog.py. It is simple on purpose. It token-matches against searchable catalog text, returns RecommendationCards, and records monitoring events.
That is not glamorous, but it solves a real production problem: users do not care whether your fallback is elegant. They care whether the system remains useful when one layer fails.
Observability is the real differentiator
The most important engineering choice in this repo may actually be backend/app/services/monitoring.py.
The TurnMonitor tracks:
- user message receipt
- LLM call metadata
- intent classification events
- retrieval start and completion
- ranking start and completion
- validation checks
- recommendation generation
- fallbacks and errors
The design detail I like most is that LLM calls are not just logged as strings. They are recorded with fields like:
- operation
- provider
- model
- prompt version
- input hash
- validation status
- retry count
- latency
- fallback usage
That changes debugging from "it felt worse this week" into "the parse_intent path started falling back more often after this change."
For recommendation systems, that is the difference between observability and vibes.
Analytics closes the loop
The analytics layer persists recommendation runs and user events into relational tables. backend/app/services/analytics.py stores:
- the original query
- parsed intent
- ranked result metadata
- final recommendation positions
- downstream positive events
That data is later reused by backend/app/retrieval/scoring.py to learn runtime weights.
I like this pattern because it keeps the feedback loop narrow and inspectable. The system is not retraining a giant model. It is adjusting the balance of explicit ranking signals based on observed outcomes.
In other words: learn at the edge of the deterministic system, not at the center of the trust boundary.
Data quality still dominates architecture quality
Even with good retrieval code, the engine is only as good as the catalog it can reason over.
This repo handles that through a separate catalog data pipeline:
- catalog collection and source ingestion into the database layer
- normalization and canonicalization in
data_collection/ingestion/ - shared schemas in
core/
That matters because retrieval quality is mostly upstream of LLM quality. If the catalog lacks reliable flowers, colors, occasion tags, tone descriptors, or delivery attributes, the ranking layer has nothing solid to score against. At that point the model is forced to improvise, and the whole "deterministic core" story collapses.
Good recommendation systems are not built by adding one clever ranking function at the end. They are built by making the data legible to the ranking function in the first place.
The real takeaway
The phrase "don't trust the LLM" can sound anti-model. That is not the point.
The point is narrower: do not ask the model to own the part of the system you most need to debug.
If the hard problem is language, let the model do language.
If the hard problem is ranking, constraints, delivery feasibility, operator control, and failure analysis, build explicit software for those things.
That is what I was aiming for in ai-florist. Not a system with no LLM, but a system where the LLM is never the only explanation for why something happened.
Solutions
About the author

Cyril Noirot
Lead Data Scientist
Freelance data scientist. I design and ship decision systems — forecasting, pricing, marketing measurement, optimization.
Seen in practice
Anonymized case studies where these ideas were applied to real decision problems.