Delivered remotely for a business based in Sydney, Australia. Names withheld by agreement.
Project Overview
Standard storefront search bars force customers to translate real-world problems into rigid taxonomy filters. A shopper looking for a quiet espresso setup under a fixed counter height, or compatible roof-rack bars for a specific vehicle year, often bounces between specification PDFs and dozens of filtered tabs before giving up. Generic chat widgets bolted onto retail sites rarely help either, frequently hallucinating features or recommending out-of-stock SKUs.
Designed for a multi-category retail group in Sydney, we built a conversational AI shopping assistant using Python, Next.js, and LLM APIs. Rather than wrapping a static FAQ bot over a storefront, the platform combines multi-turn constraint extraction with deterministic catalog queries, live warehouse stock verification, and interactive UI components streamed directly into the shopping journey.
Guided Discovery Bottlenecks
Conventional e-commerce search and first-generation retail chatbots break down across four critical user-experience boundaries:
- Vocabulary mismatch: Shoppers describe outcomes and constraints in plain language while product catalogs store fragmented technical codes and inconsistent vendor attributes.
- Unconstrained LLM hallucinations: Unbounded text models confidently invent bundle compatibility, promotional coupons, or shipping cutoffs that contradict live ERP state.
- Static prose walls: Plain-text chat bubbles force users to manually search for each mentioned product instead of comparing specs and adding variants inline.
- Runaway inference cost and latency: Sending full catalogs in context or routing simple size queries through heavyweight reasoning models degrades page responsiveness and inflates API spend.
Architectural Strategy
We enforced a strict boundary between probabilistic language orchestration and deterministic commerce state. LLM APIs act solely as structured intent parsers, clarifying-question planners, and concise explanation generators operating over typed Python function-calling schemas.
Every factual claim—price, AU stock availability by postcode, technical dimensions, and cross-product compatibility—originates from PostgreSQL and pgvector via FastAPI tools. Instead of asking the model to copy prices into Markdown prose, FastAPI emits structured UI component events alongside streamed text so Next.js renders authoritative product cards, side-by-side comparison matrices, and single-click cart actions hydrated directly from backend records.
Core Capabilities
- Multi-Turn Constraint Refinement: Extracts hard requirements (budget, dimensions, compatibility, delivery window) alongside soft preferences, asking targeted clarifying questions only when search results remain ambiguous.
- Hybrid Semantic & Attribute Retrieval: Combines
pgvectorembeddings with exact PostgreSQL SQL predicates so semantic intent never overrides hard constraints like size or stock status. - Deterministic Bundle & Compatibility Checks: Validates accessory pairings (cables, mounts, consumables) against curated product relationship graphs before recommending add-ons.
- Interactive Rich Commerce Cards: Streams live comparison tables, variant selectors, and one-click cart additions inside the Next.js drawer without breaking page navigation.
- Live Inventory & Click-and-Collect Awareness: Checks Redis-cached warehouse and store stock snapshots per Australian postcode before surfacing fulfillment options.
- Automated Evaluation Harness: Runs golden multi-turn test suites against every prompt or model update to verify tool-selection accuracy and constraint adherence.
Technical Architecture
User messages enter a Next.js App Router edge-friendly chat interface and stream to a Python FastAPI orchestrator over Server-Sent Events. FastAPI hydrates conversation state from Redis, executes structured LLM API tool calls, runs hybrid PostgreSQL/pgvector queries plus deterministic merchandising filters, and streams interleaved text tokens and typed JSON card payloads back to the browser.
Flow: Next.js Chat & Cart UI → FastAPI Streaming Orchestrator → LLM API Tool-Calling Loop → Deterministic Python Merchandising Guards → PostgreSQL & pgvector Hybrid Catalog + Redis Session State → Typed Product Card & Cart Stream
Keeping pgvector inside the primary PostgreSQL catalog database eliminates stale external vector indexes: the moment a merchandising script updates a stock flag or discontinues a variant, hybrid retrieval respects that change in the same transaction.
Technology Stack
| Category | Technology detail |
|---|---|
| Storefront & Chat UI | Next.js App Router and TypeScript streaming rich product cards, comparison tables, and cart controls |
| Orchestration Service | Python FastAPI handling multi-turn conversation state, tool execution, and Server-Sent Events |
| Reasoning & Tool Calls | LLM APIs configured with strict JSON tool schemas for constraint extraction and guided follow-ups |
| Catalog & Cart State | PostgreSQL managing product specifications, compatibility rules, pricing tiers, and session history |
| Semantic Retrieval | pgvector indexing product descriptions, buying guides, and use-case embeddings alongside SQL filters |
| Session & Cache Layer | Redis storing ephemeral conversation context, live inventory TTL caches, and per-session rate limits |
| Merchandising Rules | Deterministic Python ranking guards enforcing margin floors, stock thresholds, and bundle compatibility |
| Telemetry & Evals | Structured prompt-trace logging and regression evaluation suites verifying tool-call accuracy |
Engineering Trade-offs & Solutions
| Engineering Challenge | Solution & Trade-off |
|---|---|
| Large reasoning models introduce multi-second pauses on simple follow-up queries | Implemented a two-tier model router in Python that dispatches straightforward filter tweaks to low-latency models while reserving larger models for multi-constraint bundle synthesis. |
| Allowing LLMs to write raw prices in text risks subtle formatting or currency errors | Stripped pricing authority from model prose by passing opaque SKU references through typed tool responses that Next.js renders directly from PostgreSQL records. |
| Pure semantic vector search ignores strict numeric bounds like maximum wattage or price | Executed filtered hybrid queries combining pgvector cosine distance with indexed PostgreSQL relational predicates inside single SQL statements, trading slight index tuning complexity for exact constraint enforcement. |
| Re-embedding full product catalogs on frequent price or stock changes wastes compute | Embedded only stable product attributes and usage guides in pgvector while reading volatile stock counts and promotional prices purely from relational columns and Redis caches. |
Grounding, Guardrails & Privacy
A customer-facing LLM endpoint exposed to open web traffic requires defense in depth against prompt injection, price manipulation, and PII leakage. Tool schemas strictly limit execution to read-only catalog search, compatibility verification, and scoped cart-line additions—no tool can modify pricing, apply arbitrary coupon codes, or query another shopper's order history.
Session transcripts stored for quality diagnostics strip email addresses, street numbers, and payment tokens prior to logging. Before launching prompt revisions or model upgrades, CI pipelines execute curated adversarial scenarios checking for competitor steering, fabricated warranty terms, and out-of-budget recommendations.
Streaming Responsiveness & Token Economics
Shoppers abandon conversational UIs that stall behind spinners. FastAPI begins streaming initial acknowledgement and tool-progress indicators immediately, while parallel async tasks pre-warm stock checks for top candidate SKUs. Conversation history compresses older turns into compact structured constraint objects rather than replaying verbose raw HTML or full product JSON specs on every turn.
Redis caches identical normalized intent queries and buying-guide lookups across sessions for short windows, trimming upstream LLM API token consumption during peak weekend retail campaigns without serving stale stock statuses.
Operational Outcomes
Integrating deterministic catalog validation with guided conversational orchestration reshaped how shoppers navigate complex product assortments:
- Confident complex-purchase guidance: Shoppers translate real-world use cases into verified, compatible product shortlists without deciphering opaque spec sheets manually.
- Zero inventory hallucinations: Decoupling LLM reasoning from authoritative PostgreSQL stock and pricing state prevents assistants from pitching unavailable items or imaginary discounts.
- Seamless path from discovery to cart: Streamed Next.js product cards and variant pickers turn answers directly into actionable cart updates inside the same browsing session.
- Predictable merchandising control: Product teams tune compatibility graphs, stock floors, and promotion rules in SQL without retraining or fine-tuning underlying language models.