All articles

Retail AI9 min readBy Petrică RădanReference guide

Architecting a Zero-Hallucination AI Shopping Assistant

Stop retail assistants from inventing prices and stock by confining models to SKU selection while synced caches and streaming interfaces supply live ERP data

  • AI Shopping Assistant
  • Change Data Capture
  • Redis
  • Server-Sent Events
  • Structured Tool Calling
  • Vercel AI SDK
  • Vector Search

At 9:02 a.m. during a Friday flash sale, a shopper asks your bot for waterproof trail shoes in size 42 under €120, and it promises three pairs at €95. Ten seconds later, checkout throws a 409 conflict because the last pair sold at 8:45 and the discount ended Tuesday. Your support team gets an angry screenshot of a binding quote your model invented out of yesterday's HTML.

Building a zero-hallucination AI shopping assistant has very little to do with prompt engineering or picking a lower temperature. You get factual accuracy by forbidding the language model from ever generating prices, variants, or stock counts. Instead, the model resolves shopper intent into deterministic SKU identifiers while real-time ERP inventory sync and a streaming UI supply every number on the screen.

Why scraped-HTML RAG fails in retail

Most broken retail bots share the same origin story. A team scrapes its own storefront, chunks product pages into 500-token passages, embeds them in a vector database, and feeds the top five matches into a system prompt.

Chunking a product page severs the relational link between a parent item, its size variants, its regional pricing, and its warehouse availability. As the engineering team behind Sanity's Agent Context points out, the failure isn't the model, it's the text-chunk data layer. Scrape-and-embed pipelines inevitably mix up variants, invent stock, and quote stale prices.

Even if your embeddings are fresh at midnight, retail state decays in seconds. Xorosoft puts the division of labor plainly: the ERP holds the facts, while the AI helps people understand those facts faster. When you ask a probabilistic token predictor to act as a database read replica, you get noise dressed up as customer service.

NVIDIA takes the right structural stance in its retail shopping blueprint by pulling generative models out of the retrieval and arithmetic paths altogether. In its reference architecture, LangGraph and Nemotron models handle conversation, while a deterministic catalog service runs structured filters and typed code tools execute every cart change and total calculation.

The model emits a SKU, never a price

The single architectural rule I would enforce from day one is simple: the LLM may emit a SKU identifier, never a price or an inventory count. If a model cannot write a currency figure into a rendered component, it cannot hallucinate a discount.

I used the same pattern in a dashboard-generator prototype I tested against an energy-market dataset. Rather than letting Gemini write raw queries against arbitrary BigQuery columns, I forced it to plan strictly against a fixed semantic model backed by a deterministic validator and allowlist, so it could not invent a field name. In e-commerce, your SKU catalog and live read cache play that exact gatekeeper role.

Structured tool calling makes that boundary enforceable. LangChain found in its 2026 agent survey that agents wired with structured tool calling hit 41% higher task completion rates on multi-step workflows than prompt-only setups. Systems like Sanity's Agent Context and DezemberHub, a DACH-region retail ERP for shoe, fashion, and sports stores, expose typed product fields like sku, price, variants, and inventory.quantity over the Model Context Protocol (MCP). DezemberHub also enforces user-level permissions and human approval gates before any write action.

There is a catch with MCP and large tool surfaces that vendor demos gloss over. In an arXiv study testing ten hosted models across two invocation surfaces, researchers recorded 322 genuine tool hallucinations. Fabricated tool calls clustered heavily on unconstrained raw-JSON surfaces (34 versus 3 on constrained interfaces), and 154 hallucinations happened on merged MCP namespaces. QBCS shipped an internal retail ERP assistant covering nearly 200 merchandising operations across purchasing, pricing, and finance. That breadth makes sense for trained staff, but dumping dozens of overlapping ERP tools into a public shopping session asks for namespace collisions.

Keep the customer-facing agent down to four or five strict, Zod-validated tools: search catalog, recommend by SKU, inspect variant fit, and stage cart item. In the server-side tool contract below, the model passes only SKU strings and short reasoning, while the execute function pulls the authoritative numbers straight from Redis.

ts
1import { streamText, tool } from 'ai';
2import { z } from 'zod';
3
4export async function POST(req: Request) {
5  const { messages } = await req.json();
6
7  const result = streamText({
8    model: geminiFlashModel,
9    system: 'Assist the shopper. Never state prices or stock counts in text; call showProductCards so the UI renders live data.',
10    messages,
11    tools: {
12      showProductCards: tool({
13        description: 'Render live product cards for candidate SKUs.',
14        parameters: z.object({
15          skuIds: z.array(z.string()).min(1).max(6),
16          matchReason: z.string(),
17        }),
18        execute: async ({ skuIds, matchReason }) => {
19          const liveRecords = await redisInventoryCache.mget(skuIds);
20          return liveRecords
21            .filter((item) => item !== null && item.availableQty > 0)
22            .map((item) => ({
23              sku: item.sku,
24              name: item.name,
25              exactPriceCents: item.priceCents,
26              currency: item.currency,
27              availableQty: item.availableQty,
28              matchReason,
29            }));
30        },
31      }),
32    },
33  });
34
35  return result.toUIMessageStreamResponse();
36}

Pair that system prompt instruction with the filter inside the tool execution. Even if vector search surfaces a shoe that sold out four seconds ago, the Redis check strips it before the client ever mounts a card.

Syncing ERP inventory without melting the database

Pointing those tool calls straight at a legacy ERP database will bring an operations engineer to your desk within an hour. Agentic loops multiply read traffic far beyond normal human browsing.

In a data-question agent benchmark published by Redis, GPT-5.2 needed an average of 6.1 iterations and 7.3 tool calls per user request, climbing to 17.6 tool calls on the hardest queries. A traditional retail ERP tuned for store replenishment and accounting batches will buckle if a thousand concurrent shoppers each trigger seven sequential inventory lookups. Redis notes that a 20-node AWS cluster handled over 100 million operations per second at sub-millisecond latency in its own testing. That is a vendor benchmark on a hefty cluster, of course, yet it shows why an in-memory read projection has to shield your system of record.

How you feed that read cache determines your oversell risk. Many teams start with cron jobs polling ERP REST endpoints every fifteen minutes, realize they are burning API quotas on unchanged rows, and then wrestle with migrating to events. OrderPilots puts typical batch polling lag at 5 to 60 minutes, while Exsited cites 5 to 15 minutes for tighter schedules. Moving to webhooks and queues cuts API consumption by 90% to 95% in Exsited's numbers because 100% of calls carry actual changes, bringing latency down to 200 to 800 milliseconds, or 1 to 5 seconds in OrderPilots' typical range.

Sync ArchitectureEnd-to-End LatencyERP Load ProfileOversell Exposure
Scheduled Batch Polling5 to 60 minutesHigh wasted read volume polling unchanged SKUsWide; high risk of 409 checkout failures during promos
Application Webhooks and Queues200 ms to 5 seconds90% to 95% lower API volume; every call carries a changeBounded under 5 seconds
Log-Based CDC and Kafka OutboxUnder 25 msNear-zero query load; reads committed transaction logsMinimal; limited to active checkout race window

If your ERP runs on a relational database you control, log-based Change Data Capture (CDC) via Debezium or Redis Data Integration can read committed changes straight from the Write-Ahead Log (WAL). Another clean route is a transactional outbox feeding Apache Kafka, which Codiest reports can hit sub-25ms propagation with at-least-once delivery. Either way, you capture committed inserts and updates without firing expensive SELECT queries at legacy tables.

Where I part ways with some current vendor pitches is on what you do with that CDC stream next. Oracle's OCI GoldenGate 23ai replicates store inventory transactions into an Autonomous AI Lakehouse and converts relational rows into vector embeddings on the fly for real-time RAG. That sounds slick until you calculate the cost and index churn of re-embedding a product record every time someone in Munich buys a pair of socks.

Don't put volatile numbers in a vector index. Keep vector embeddings strictly for slow-moving semantic attributes like material, silhouette, terrain, and weather rating, then join candidate SKU IDs at query time against your CDC-fed Redis hash for price and stock. AdaptNXT reports 99.8% inventory sync accuracy and sub-200ms vector retrieval by pairing event queues and Redis with a vector store. AdaptNXT also claims a 35% lift in average order value, though every commerce vendor brags about big conversion jumps. Dismiss the marketing number, and the dual-store pattern underneath is still rock solid.

Streaming UI after Vercel walked back Server Components

Resolving clean SKU data in a few milliseconds doesn't help much if the shopper stares at a blank chat for four seconds waiting on a complete JSON payload. Streaming generative UI fixes that wait, though plenty of engineering tutorials from a year ago will lead you straight into a ditch.

The Vercel AI SDK dominates this layer of the stack. Weekly npm downloads for the v6 package reached roughly 12 million, and Vercel's AI SDK 7 release added durable WorkflowAgent primitives, tool approvals, and expanded telemetry. Early adopters flocked to @ai-sdk/rsc and its streamUI helper, which ran tools inside Next.js Server Actions and streamed pre-rendered React Server Components down the wire.

If you are architecting a new storefront now, stay away from streamUI. Vercel's own documentation explicitly warns teams off it:

AI SDK RSC currently faces significant limitations that make it unsuitable for stable production use... Due to these limitations, AI SDK RSC is marked as experimental, and we do not recommend using it for stable production environments.

Those limitations aren't theoretical edge cases. Server Actions cannot cleanly abort an active stream when an impatient shopper types a follow-up filter. Components remount and visibly flicker when .done() fires on streamable UI nodes, deep Suspense boundaries can crash the tree, and createStreamableUI suffers from quadratic data-transfer overhead as the stream grows.

The production replacement in AI SDK UI flips rendering back to the client while keeping data resolution on the server. Your backend streams a standard Server-Sent Events (SSE) message stream with the x-vercel-ai-ui-message-stream: v1 header, and useChat on the frontend parses message.parts in real time. Text tokens stream straight into chat bubbles, while tool outputs arrive as typed tool-showProductCards parts carrying the Redis-verified JSON payload, mounting standard client-side React cards with zero remount flicker.

If I were wiring this for a high-traffic catalog, I would add one extra safeguard on the client card itself. Pass the cache timestamp alongside exactPriceCents in the tool result. When a shopper leaves a chat tab open for twenty minutes before scrolling back up, the React component can silently ping a lightweight edge read endpoint on focus so stale cards gray out gracefully.

Surviving the twelve-second race to checkout

Even sub-25ms CDC sync and typed tool streams leave one nasty failure mode open: the human pause between seeing "1 pair left" in a streamed card and clicking "Add to Cart" twelve seconds later. During a drop or seasonal promo, fifty shoppers can stare at that exact same Redis-verified product card at once.

In an airport-transfer booking platform I built for a UK client, my Gemini agentic loop coordinated 11 tools across fare math, flight tracking, Stripe, and scheduling. I prevented double-bookings there by wrapping the availability check and the insert inside a PostgreSQL advisory lock. That works cleanly when a booking executes in milliseconds at confirmation time, whereas you obviously cannot hold a database lock across an open SSE chat stream while a shopper debates between blue and black.

High-concurrency retail assistants split conversation from commitment. SAP CX models this in its Joule shopping assistant by handling search intent and promotional personalization in discovery agents, then handing off to a separate purchasing agent once transaction rules kick in. On the wire, discovery reads hit your Redis replica, while cart mutations and purchases route through transactional commerce endpoints like /ucp/cart and /ucp/checkout that perform atomic stock decrements or short-TTL inventory holds.

Latency in multi-turn loops is the other operational tax you have to budget for. Suppose a shopper asks for waterproof trail shoes in 42, matching rain pants under €80, and their loyalty tier discount. Sequential tool loops will stack model round-trips until the stream feels sluggish. Where tools don't depend on one another's outputs, force parallel tool execution in a single step, and keep cart math in deterministic backend code rather than letting the agent burn two extra turns checking its own addition.

Before writing a line of Kafka or Next.js code, decide whether your assistant is a salesperson or a cashier. A salesperson can run on eventual consistency with a two-second CDC lag as long as the cart endpoint catches stockouts cleanly. An autonomous cashier that executes conditional purchases on a user's behalf needs pessimistic reservations, idempotency keys, and human approval gates. Building the first while pretending you have the second is how engineering teams end up explaining hallucinated orders to finance.

Frequently asked questions

Why do scraped-HTML RAG pipelines hallucinate in e-commerce?

Chunking scraped product pages into text passages severs the relational links between parent items, size variants, regional pricing, and warehouse availability. Because retail inventory and pricing decay in seconds, static embeddings quickly go stale and cause models to invent discounts or stock counts.

How do you stop an AI shopping assistant from inventing prices or stock counts?

Forbid the language model from generating prices or stock numbers in text and constrain it to emitting SKU identifiers through strict, Zod-validated tool schemas. The server-side tool execution layer then pulls authoritative prices and quantities from an in-memory cache like Redis before rendering product cards.

What is the best way to sync ERP inventory for an AI assistant?

Avoid polling legacy ERP endpoints or re-embedding volatile stock numbers into a vector index. Instead, stream committed inventory changes via log-based Change Data Capture or application webhooks into a Redis read cache, keeping vector embeddings strictly for slow-moving attributes like material and terrain.

Why use Server-Sent Events instead of React Server Components for streaming AI UI?

Vercel marks its RSC-based streamUI helper as experimental and unsuitable for production because of component remount flicker, quadratic data overhead, and broken stream abort handling. Streaming typed tool payloads over Server-Sent Events to client-side React components via useChat and message.parts avoids remount flicker and lets stale cards revalidate on focus.

Sources

Book a discovery call

30 minutesGoogle MeetFree