Skip to content

Repository files navigation

Hybrid Product Search Agent — Reference Architecture

A production-oriented hybrid product retrieval system inspired by the Amazon ESCI shopping-search task. It combines SPLADE sparse representations with BGE-Large dense embeddings in Qdrant, retrieves both channels concurrently, and applies Reciprocal Rank Fusion (RRF). This repository is an educational/reference implementation; obtain ESCI from its authorized source and comply with its license/terms.

1. Why hybrid retrieval?

Commerce search has two competing requirements. Lexical precision matters for SKUs, model numbers, brands, sizes, compatibility phrases and rare attributes. Semantic retrieval matters for paraphrases, intent, category language and descriptions that do not repeat query tokens. A single representation creates systematic blind spots. Hybrid retrieval makes those failure modes observable and composable.

                         ┌───────────────────────────────┐
Query ─► API/Auth ─► Query Understanding / Policy       │
                         └──────────────┬────────────────┘
                                        │
                         fan-out under one deadline
                         ┌──────────────┴───────────────┐
                         │                              │
                 SPLADE encoder                 BGE-Large encoder
                         │                              │
                 sparse vector                    dense vector
                         │                              │
                 Qdrant sparse                    Qdrant dense
                    search                           search
                         │                              │
                         └──────────────┬───────────────┘
                                        ▼
                             Reciprocal Rank Fusion
                                        │
                           optional cross-encoder/LTR
                                        │
                          filters / policy / diversity
                                        │
                                  Search Results

2. Repository

app/
  main.py       FastAPI serving edge
  encoders.py   SPLADE + BGE adapters
  store.py      named dense/sparse Qdrant vectors
  service.py    parallel retrieval orchestration
  fusion.py     deterministic RRF
scripts/
  ingest_esci.py
  evaluate.py
tests/
docker-compose.yml
.github/workflows/ci.yml

3. Data contract and ESCI ingestion

The serving document should be a canonical product snapshot: stable product id, locale, title, brand, description/bullets and filterable structured attributes. Do not use relevance labels as document text. ESCI query-product labels belong in offline evaluation/training splits. Normalize Unicode and whitespace, retain model-number punctuation when useful, cap pathological fields, and version every transformation.

A real pipeline should be: raw snapshot -> validation -> canonicalization -> enrichment -> embedding jobs -> shadow collection -> evaluation -> alias cutover. Write a manifest containing dataset snapshot, code SHA, dense model/version, sparse model/version, tokenizer hashes, dimensions, locale, schema version and build timestamp. That manifest is the reproducibility boundary.

4. Representation layer

Dense: BGE-Large

The example defaults to BAAI/bge-large-en-v1.5. Dense vectors are normalized before cosine retrieval. Production systems should batch on GPU, use dynamic batching, enforce token limits, and cache repeated query embeddings. Query/document instructions must follow the chosen model's documented convention and be frozen with the index version.

Sparse: SPLADE

SPLADE emits learned term weights in tokenizer vocabulary space. SpladeEncoder applies the standard log(1+ReLU(logits)) transformation, masks padding, and max-pools over sequence positions. Store only non-zero (token_id, weight) pairs. Production ingestion should additionally benchmark pruning thresholds/top-N terms: sparse posting volume can dominate memory.

5. Qdrant schema

One logical product point carries two named representations:

point(product_id)
  vector["dense"]  -> BGE embedding
  vector["sparse"] -> SPLADE SparseVector(indices, values)
  payload           -> title, brand, locale, attributes, visibility...

Payload indexes should be created for high-selectivity filters such as locale, marketplace, availability, tenant/catalog and category. Avoid putting volatile price/inventory semantics into embeddings; retrieve authoritative commerce state from its source or update payloads through a CDC path.

6. Online request path

  1. authenticate/authorize;
  2. normalize query and derive locale/filter constraints;
  3. compute dense and sparse query representations;
  4. dispatch both Qdrant searches concurrently;
  5. independently record latency, candidate count and ranks;
  6. RRF the candidate ids;
  7. optionally rerank the top fused candidates;
  8. enforce policy/availability/diversity;
  9. return products plus trace identifiers.

Use a common end-to-end deadline and smaller child budgets. If one channel times out, serve the healthy channel with a degraded-mode metric rather than exceeding the user deadline.

7. Why RRF instead of adding scores?

Cosine similarity and SPLADE retrieval scores do not share a calibrated numeric scale. Raw weighted addition therefore couples ranking quality to score distributions, model upgrades and query types. RRF uses ranks: RRF(d) = Σ_c 1/(K + rank_c(d)). The implementation defaults to K=60. Treat K, candidate depths and any channel weights as versioned ranking configuration and tune offline before an experiment.

RRF is intentionally simple. At larger scale, compare it with calibrated score fusion and learned-to-rank features: dense/sparse scores, ranks, query features, category/brand matches, popularity and freshness. Never silently turn business objectives into relevance labels—measure relevance and business constraints separately.

8. Optional reranking

Fusion optimizes candidate recall, not final precision. A cross-encoder can rerank top 20–100 candidates using query plus concise product text. Bound its latency with batch inference and a timeout. On timeout, return RRF order. Keep reranker model/version in the response trace and evaluation manifest.

9. Evaluation architecture

Two layers are required.

Candidate/retrieval evaluation: Recall@K, MRR, nDCG@K, coverage and per-channel overlap. Report dense-only, sparse-only and hybrid side-by-side. Segment by locale, head/tail frequency, query length, brand/model-number queries, category and ESCI relevance class.

Online evaluation: controlled experiments measuring reformulation, zero-result rate, click/add-to-cart/purchase metrics and latency. Those signals are biased by position, UI and inventory; they are not interchangeable with editorial relevance judgments.

Promotion gate example:

build candidate index
 -> replay frozen benchmark
 -> compare against production baseline
 -> inspect slices/regressions
 -> load test
 -> shadow traffic
 -> canary
 -> experiment
 -> promote / rollback

10. Principal+ control plane vs data plane

The data plane serves embeddings, retrieval, fusion and reranking. It should have no authority to change model/index configuration. The control plane owns model registry, ranking configs, index manifests, evaluation artifacts, experiment assignment, rollout state and collection aliases. Changes are signed/audited and promoted through gates. This separation prevents an experimental notebook or compromised serving process from mutating production ranking globally.

11. Zero-downtime index/model migration

Never overwrite an incompatible vector representation in place.

products_v41 (active alias)
        │
 build products_v42 with new model/schema
        ▼
offline validation -> shadow -> canary
        ▼
atomically move read alias to v42
        ▼
retain v41 for rollback window

Dual-write only when justified; immutable rebuilds are easier to reason about. A request trace must say which collection/model/ranker versions served it.

12. Reliability

Suggested SLOs are illustrative, not universal: 99.9% successful search availability and a product-specific p95 latency budget. Track separate p50/p95/p99 for query encoding, sparse search, dense search, fusion and reranking. Define error-budget policy before launch.

Failure matrix:

Failure Behavior
dense encoder unavailable sparse-only degraded search
SPLADE unavailable dense-only degraded search
one Qdrant channel timeout fuse/return healthy channel
reranker timeout return RRF ranking
Qdrant unavailable fail fast or bounded stale cache
index build failure active alias unchanged
bad candidate release alias rollback

Retries belong only on transient/idempotent operations, with jitter and strict deadline awareness. Use circuit breakers to prevent encoder/Qdrant cascades.

13. Capacity and cost model

Measure, do not guess: QPS × candidates/channel × payload bytes for network pressure; N_products × dense_dimension × bytes/value × replication/ANN overhead for dense storage; and empirical non-zero SPLADE terms/product for sparse storage. GPU encoder capacity is governed by tokens/sec and batching rather than raw request count. Load-test realistic query-length and filter distributions.

Cost levers: offline batch embedding, quantization after relevance validation, sparse pruning, right-sized candidate depths, rerank only top-N, cache hot query embeddings/results, payload projection, and tiered replicas.

14. Partitioning and multi-region

Partition first by hard isolation boundaries (tenant/marketplace/locale) only when operationally justified; excessive collections create control-plane overhead. For very large catalogs, shard by stable hash while preserving filter behavior. Replicate serving close to users when latency warrants it. Keep index builds deterministic so another region can reconstruct from source snapshots plus manifests. Define RPO/RTO for source metadata, index manifests and ranking configs; vector indexes are usually rebuildable artifacts, not the sole system of record.

15. Security and abuse

Authenticate callers, authorize catalog/tenant scope, validate payload filters server-side, cap query length and candidate depth, rate-limit abusive clients, and never trust client-provided Qdrant filters directly. Encrypt traffic and storage, rotate credentials, isolate build workers from serving credentials, scan dependencies/images, redact sensitive query logs, and define retention. Product text is untrusted content if later passed to an LLM; retrieval does not make instructions inside a product description trustworthy.

16. Observability

Emit one trace spanning: HTTP -> dense_encode || sparse_encode -> dense_search || sparse_search -> RRF -> rerank. Metrics include request QPS/error/latency, channel latency/timeouts, embedding cache hit rate, candidate counts, overlap/Jaccard, RRF contribution, zero-result rate, Qdrant saturation, GPU utilization, sparse nnz distributions and model/index versions. Structured logs use query hashes or privacy-reviewed text—not unrestricted raw user queries.

17. Relevance debugging

For every result retain an explain record (internal/debug-only):

{"product_id":"p123","dense_rank":4,"sparse_rank":1,
 "rrf_score":0.0320,"collection":"products_v42",
 "dense_model":"bge-...","sparse_model":"splade-..."}

This turns “search feels worse” into a diagnosable regression. Sample traces can feed a relevance-review UI.

18. Freshness architecture

Embedding rebuild cadence and transactional catalog freshness are different problems. Stream price, inventory, suppression and eligibility changes through CDC/eventing into authoritative filters/payloads. Re-embed only when semantic fields change. At result assembly, optionally revalidate highly volatile fields. Never show stale availability merely because a vector point exists.

19. Query understanding

A mature system can add spell correction, locale/language detection, unit normalization, category/attribute extraction and explicit filters. Run transformations under a versioned policy and preserve the original query. Do not let an unconstrained LLM rewrite erase model numbers or brands; route rewrites as additional retrieval hypotheses and evaluate them.

20. Testing strategy

Unit: RRF math, normalization, schemas, deterministic ranking. Contract: encoder dimensions, Qdrant named-vector schema, payload filters. Integration: ephemeral Qdrant + small fixtures. Golden relevance: frozen ESCI-derived benchmark. Property tests: RRF monotonicity and duplicate handling. Load/soak: tail latency, Qdrant saturation, encoder batching. Chaos: kill one retrieval channel and verify graceful degradation.

21. Local run

cp .env.example .env
docker compose up -d qdrant
python -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
python scripts/ingest_esci.py /path/to/authorized/esci_products.csv --limit 10000
uvicorn app.main:app --reload
curl -X POST localhost:8000/v1/search -H 'content-type: application/json' \
  -d '{"query":"waterproof trail running shoes","limit":10}'

Model downloads are large; use GPU-backed batch jobs for realistic ingestion.

22. API

POST /v1/search

{"query":"usb c charger 65w laptop","limit":10}

Each hit exposes fused score and dense/sparse ranks for demonstration. A public production API would normally hide ranking internals and expose them only through privileged debugging.

23. Evolution roadmap

Stage 1: BGE + SPLADE + Qdrant + RRF.
Stage 2: metadata filters, caches, observability, golden relevance suite.
Stage 3: cross-encoder reranking, shadow/canary index releases.
Stage 4: query understanding, multilingual models, learned fusion/LTR.
Stage 5: personalized ranking with privacy boundaries and explicit experimentation.
Stage 6: LLM shopping agent uses search strictly as a retrieval capability; transactional price/cart/order systems remain authoritative tools.

24. Principal-level trade-offs to discuss

  • Why hybrid retrieval instead of choosing BM25/SPLADE or dense alone?
  • Why rank fusion before score calibration?
  • What does a model upgrade mean for index compatibility?
  • How do you preserve availability when one encoder fails?
  • How do you prove hybrid improved tail queries rather than only aggregate nDCG?
  • When does a cross-encoder justify its latency/cost?
  • How do catalog freshness and embedding freshness differ?
  • How do you roll back an index globally without rebuilding?
  • What is the system of record: Qdrant or the commerce catalog?
  • Which ranking signals are relevance, which are policy, and which are business objectives?

The strongest architecture answer treats search as a continuously evaluated distributed system—not as “generate embeddings and call a vector database.”

Amazon / AWS engineering — repository-specific visual gallery

Amazon ESCI-style product relevance and retrieval. Reuse SPLADE, BGE-Large, Qdrant, concurrent retrieval and RRF; Amazon catalog access is separate from licensed ESCI.

These are independent adaptation designs, not claims of internal Amazon architecture, live account access, deployment or measured outcomes. Verify service region, IAM, permissions, licensing and interface compatibility before implementation.

01. Dual retrieval and rank fusion

Hybrid_Product_Search_Agent: Dual retrieval and rank fusion

Concept and step-by-step workflow: Retrieve sparse and dense candidates concurrently; wait for both or explicitly degrade, fuse rank positions, deduplicate by product identity.

Diagram reading guide: Shopping query → SPLADE sparse retrieval → BGE dense retrieval → RRF merge → Ranked products. Arrows show the conceptual processing order; parallel branches, alternative paths and checks follow the workflow explanation.

How to adapt the current repository: Reuse Qdrant sparse/dense indices and current RRF; compare OpenSearch hybrid alternative behind retrieval interface without changing baseline.

Expected outputs, failure handling and validation: Test SKU exact-match and paraphrase; report missing branch and recall changes.

02. ESCI relevance evaluation

Hybrid_Product_Search_Agent: ESCI relevance evaluation

Concept and step-by-step workflow: Keep exact/substitute/complement/irrelevant distinct, partition dataset without leakage and evaluate ranked results with declared gains and metrics.

Diagram reading guide: Licensed ESCI records → Exact and substitute labels → Complement and irrelevant labels → Rank metrics → Model comparison. Arrows show the conceptual processing order; parallel branches, alternative paths and checks follow the workflow explanation.

How to adapt the current repository: Use existing ESCI reference architecture; add reproducible dataset manifest, nDCG/recall metrics and evaluation of lexical versus dense channels.

Expected outputs, failure handling and validation: No invented Amazon search benchmark; dataset/license and label mapping validated.

03. ASIN and variant mapping

Hybrid_Product_Search_Agent: ASIN and variant mapping

Concept and step-by-step workflow: Map permitted catalog metadata to canonical product/variant and marketplace, preserve source revision and normalize attributes before indexing.

Diagram reading guide: Authorized catalog item → ASIN and marketplace → Retailer SKU mapping → Variant evidence → Search index. Arrows show the conceptual processing order; parallel branches, alternative paths and checks follow the workflow explanation.

How to adapt the current repository: Add approved SP-API Catalog Items read adapter for eligible selling partners, separate from ESCI fixtures and authoritative store stock.

Expected outputs, failure handling and validation: Reject ambiguous variants and wrong marketplace; no private Amazon ranking or all-catalog access.

04. Compatibility-aware ranking

Hybrid_Product_Search_Agent: Compatibility-aware ranking

Concept and step-by-step workflow: Check exact technical attributes after retrieval; explicit evidence determines compatibility rather than semantic score.

Diagram reading guide: Candidate product → Exact model and ports → Verified compatibility facts → Filter and rerank → Grounded shortlist. Arrows show the conceptual processing order; parallel branches, alternative paths and checks follow the workflow explanation.

How to adapt the current repository: Extend current product retrieval with typed compatibility relation projection, optionally Neptune for graph traversal and Qdrant for candidates.

Expected outputs, failure handling and validation: Unknown fit remains unknown; test near-identical models and incompatible accessories.

05. Index revision and rollback

Hybrid_Product_Search_Agent: Index revision and rollback

Concept and step-by-step workflow: Stage both representations with same source IDs and embedding versions, verify counts and retrieval fixtures before atomic switch.

Diagram reading guide: Catalog snapshot → Build sparse index → Build dense index → Validate parity → Promote paired revision. Arrows show the conceptual processing order; parallel branches, alternative paths and checks follow the workflow explanation.

How to adapt the current repository: Reuse existing Qdrant collection handling; implement staged alias/version promotion and optional AWS-hosted search backend only after parity tests.

Expected outputs, failure handling and validation: Partial build never replaces healthy revision; test embedding version drift.

06. Commerce search latency and relevance

Hybrid_Product_Search_Agent: Commerce search latency and relevance

Concept and step-by-step workflow: Measure each retrieval path and end-to-end wall time, compare lexical-only/dense-only/hybrid on identical permitted corpus.

Diagram reading guide: Golden queries → Recall by label → Fusion and rerank checks → Latency budget → Release decision. Arrows show the conceptual processing order; parallel branches, alternative paths and checks follow the workflow explanation.

How to adapt the current repository: Add CloudWatch/OpenTelemetry metrics to existing search evaluator; separate operational measurements from relevance scores.

Expected outputs, failure handling and validation: No claim of Amazon internal search algorithm or measured performance until benchmark run.

References: Bedrock AgentCore · Nova Act · Selling Partner API.