All articles

Retail AI9 min readBy Petrică RădanReference guide

Architecting a Generative UI Shopping Assistant on Cloud Run

Production shopping assistants need typed JSON streams, strict widget catalogs, and stateless persistence rather than experimental server-rendered components

  • Generative UI
  • Next.js
  • Gemini
  • Cloud Run
  • Vercel AI SDK
  • E-Commerce
  • Function Calling

Picture a shopper typing "waterproof trail shoes under $120, size 43" into an AI chat box, only to watch the cursor spit out four paragraphs of bulleted markdown links. Nobody clicks four markdown links on a phone screen while standing on the metro. When people ask a store for shoes, they want to swipe a product carousel, tap a size pill, and hit buy without leaving the thread.

Wiring Next.js, Gemini, and Google Cloud Run into a generative UI assistant fixes that UX failure by turning model tool calls straight into interactive React components. Getting it right in production means ignoring the tutorials that push experimental React Server Component streams. Instead, you pair deterministic Gemini function calling with typed Server-Sent Events on a stateless container platform.

The stakes are commercial, not aesthetic. One published developer case study reported that swapping plain-text chat for inline generative UI components cut user drop-off from 60% to 12% on the exact same model, prompt, and backend. That is a single self-reported case rather than an industry-wide survey, yet anyone who has watched shoppers abandon a wall of chatbot prose will recognize the dynamic at once.

Skip experimental RSC streaming and send typed tool parts

Search for generative UI in Next.js right now and most code samples will tell you to import streamUI or createStreamableUI from @ai-sdk/rsc. Don't put that in a production storefront.

In AI SDK RSC, a Next.js Server Action invokes Gemini, executes a tool block on the server, and streams rendered React Server Components down the wire to the browser. You open the stream with a loading spinner, mutate it via .update() as your catalog query resolves, and close it with .done(). React nodes in UI State cannot be serialized and sent back to Gemini on the next turn. To work around that, you wrap your tree in a createAI provider that splits visual UI State (via useUIState) from a parallel JSON proxy called AI State (via useAIState).

It looks clever in a five-minute demo, and it falls apart under real shopping traffic. Vercel's own documentation marks AI SDK RSC as experimental and recommends AI SDK UI for production deployments. Vercel cites three concrete engineering defects: Next.js Server Actions cannot abort an active stream, components flicker and remount when .done() fires, and createStreamableUI suffers from quadratic data transfer overhead as the payload grows.

Imagine a shopper filtering a 20-item shoe grid, changing their mind mid-stream, and typing "actually, make them black." Because you cannot abort the previous Server Action stream, your container keeps burning tokens and mutating dead UI while the user stares at a remount flicker.

Vercel AI SDK 7.0, which shipped in June 2026 and requires Node.js 22+, moves component assembly back to the client through AI SDK UI. Vercel's own numbers put the SDK at 48.7 million weekly downloads, and this client-assembled stream architecture is the production path. On the server, an API route calls streamText with the @ai-sdk/google provider and pipes the output through toUIMessageStreamResponse(). That sends Server-Sent Events carrying the x-vercel-ai-ui-message-stream: v1 header. On the client, the useChat hook catches typed tool outputs as they arrive and maps them onto standard React components.

typescript
1// app/api/chat/route.ts (Node.js 22+ on Cloud Run)
2import { streamText, tool, isStepCount } from 'ai';
3import { google } from '@ai-sdk/google';
4import { z } from 'zod';
5
6export async function POST(req: Request) {
7  const { messages } = await req.json();
8
9  const result = streamText({
10    model: google('gemini-2.5-flash'),
11    messages,
12    stopWhen: isStepCount(5),
13    tools: {
14      searchCatalog: tool({
15        description: 'Search footwear catalog by category and max price',
16        parameters: z.object({
17          query: z.string(),
18          maxPrice: z.number().optional(),
19        }),
20        execute: async ({ query, maxPrice }) => {
21          const items = await queryProductVectorIndex(query, maxPrice);
22          return { view: 'carousel', items };
23        },
24      }),
25    },
26  });
27
28  return result.toUIMessageStreamResponse();
29}

Your client component stays clean. While a searchCatalog tool call is running, useChat exposes its loading state so you can render a skeleton carousel. Once the JSON result lands, you pass items straight into your normal ProductCarousel component. You get abortable HTTP requests, zero quadratic wire bloat, and one serializable message array instead of dual-state gymnastics.

Teams running polyglot backends have a third transport option worth watching. On the Google Developers Blog, engineers have published reference architectures running Python or Go agents on Cloud Run that stream bidirectional A2UI surfaces into React frontends like CopilotKit, validated on the client with Zod schemas. If your agent already lives in Google ADK on Python, streaming declarative UI specs over A2UI saves a rewrite. If your team writes TypeScript end to end, Next.js with AI SDK UI gives you one fewer protocol to debug.

UI TransportWhat Crosses the WireProduction ReadinessBest Fit
AI SDK RSC (@ai-sdk/rsc)Rendered React Server Components via Server ActionsExperimental; non-abortable, flickers on .done(), quadratic wire bloatQuick demos and throwaway prototypes
AI SDK UI (streamText + useChat)Typed JSON tool parts over SSEStable default in Vercel AI SDK 7.0End-to-end TypeScript and Next.js storefronts
A2UI + CopilotKitDeclarative UI specs validated by client Zod schemasEmerging Google reference patternPython or Go agents (such as Google ADK) on Cloud Run

Lock down the widget catalog and Gemini's tool loop

Generative UI does not mean letting a language model invent arbitrary HTML and Tailwind classes on every turn. In a store where real money changes hands, you build a strict, tested catalog of React components and let Gemini choose which ones to populate.

Keep the widget surface small at first. Very Good Ventures built a Gemini 2.5 Flash shopping assistant that handled natural queries like "Show me running shoes" and "I want something under $80" with just three custom widgets: ProductCard, ProductCarousel, and PriceRangeFilter. Add a CartSummary card and a CheckoutConfirmation view, and you have covered almost the entire retail funnel.

The harder architectural work sits behind those tool definitions: search retrieval, schema discipline, and concurrency bounds.

First, Gemini shouldn't guess what is in stock. In a hackathon entry I built for a 10,000-product grocery assistant, text and image queries ran against Vertex AI embeddings and Vector Search rather than stuffing catalog rows into the prompt. Production retail teams take similar database-backed paths. Writing on Google Cloud Community, Abirami Sukumaran detailed a retail architecture pairing AlloyDB embeddings for contextual search with Gemini for intent filtering and relevance validation. On Medium, Mark Fahim described a Cloud Run concierge wiring Gemini function calling straight into the Shopify Storefront and Admin APIs.

Second, cap your tool count and step limits. Google's function-calling guidance recommends keeping the active toolset between 10 and 20 tools before selection accuracy degrades. When I built a live airport-transfer booking system for a UK client, the Gemini loop ran 11 custom tools covering fare calculation, Stripe payments, flight tracking, and calendar sync, right inside that sweet spot. Because an e-commerce agent will chain a catalog search into an inventory check and a promo-code lookup, bound the loop too. Scalekit points out that passing stopWhen: isStepCount(5) in the Vercel AI SDK caps multi-step execution at five turns so a confused prompt cannot spin up a runaway Cloud Run bill.

Third, pick a current model generation, because older models will break your UI props. Veliu benchmarked models on generative UI e-commerce storefront prompts from LMArena and found that Gemini 3, Gemini 2.5 Pro, and Gemini 2.5 Flash hit 0% output errors. Gemini 2.0 Flash failed on 29% of those prompts, and Gemini 2.0 Flash-Lite failed on 60%. A 29% schema failure rate means nearly one in three shoppers sees a crashed React error boundary instead of a product card. Stick to 2.5 Flash or newer, and enforce structured JSON outputs via Zod schemas (or response_schema in generation_config when calling Vertex AI directly).

Reasoning latency matters just as much. A shopper tapping a price filter expects sub-second feedback, not a ten-second chain-of-thought pause. Google's Gemini documentation exposes a numeric thinking_budget parameter across the 2.5 family: gemini-2.5-flash accepts 0 to 24,576 tokens, gemini-2.5-pro requires 128 to 32,768, and gemini-2.5-flash-lite spans 512 to 24,576. Gemini 3.x models replace numeric budgets with thinkingLevel.

If I were tuning the catalog-search route today, I'd test gemini-2.5-flash with thinking_budget set near zero for straightforward filter clicks. I would save deeper reasoning budgets for ambiguous comparison questions like "which of these holds up better on wet limestone?"

Watch Google's API roadmap before locking in your dependencies. Google announced in June 2026 that the Gemini Interactions API (/v1/interactions) is generally available and replaces generateContent as the recommended unified endpoint for multi-turn agentic apps. Check whether your version of @ai-sdk/google targets /v1/interactions under the hood or still wraps generateContent. Where the wrapper lags, you may have to weigh Vercel's ergonomic SSE helpers against calling Google's native client directly.

Cloud Run will not hold your cart in memory

Deploying Next.js onto Google Cloud Run works cleanly once you respect how serverless containers handle memory and HTTP streaming. Set output: 'standalone' in next.config.js so Docker copies only the minimal Node.js 22 production server into Artifact Registry, keeping your container image lean enough for fast cold starts.

Streaming generative UI flips the usual CPU-versus-concurrency math on Cloud Run. Most of the time your Next.js route handler isn't crunching numbers; it is holding an open SSE connection while waiting on Vertex AI tokens and database queries. Google's Cloud Run documentation sets the default request timeout at 5 minutes (configurable up to 60 minutes) and defaults each container instance to 80 concurrent requests, scaling up to 1,000 for streaming workloads. Drop the chat timeout to 60 or 120 seconds, because nobody waits five minutes for a shoe carousel, and test raising instance concurrency past 80 once you measure Next.js memory usage under load.

Watch out for response buffering. Google Cloud's documentation and community answers on Stack Overflow note that standard buffered HTTP responses on Cloud Run hit a hard 32 MiB ceiling unless the server uses Transfer-Encoding: chunked or HTTP streaming. AI SDK UI's toUIMessageStreamResponse() streams over SSE out of the box, bypassing that 32 MiB trap. Just verify that no misconfigured reverse proxy or compression middleware in front of Next.js swallows chunks until the stream closes, keep HTTP/2 end-to-end or chunked flushing active, and send periodic keep-alive comments during slow tool calls.

Statelessness is the sharper operational edge. When traffic spikes on Black Friday, Cloud Run spins up ten new containers in seconds. Turn two of a shopper's conversation will almost certainly hit a different instance than turn one. Never cache cart state, user identity, or partial tool progress in Node.js process memory.

Persist conversation history and cart mutations in Firestore, Redis, or PostgreSQL on every step, keyed to an authenticated session. Treat the checkout tool with the paranoia of a financial ledger rather than a chatbot demo. Gemini must never calculate the final cart total in its head, and two users asking for the last pair of size-43 boots at the same second will race each other.

In that UK booking system I built, we stopped double-bookings by wrapping the availability check and database insert inside a PostgreSQL advisory lock. Bring that same discipline whenever a generative UI button triggers an inventory reservation or payment intent. You can also study standardized commerce boundaries like the open-source ucp-agent pattern on GitHub, which pairs a Next.js storefront with a Cloud Run agent speaking the Universal Commerce Protocol (UCP) to keep identity linking and checkout deterministic.

What breaks mid-stream, and when static filters win

Even with typed SSE streams and Gemini 2.5's clean schema adherence, streaming UI introduces failure modes that plain REST apps never see. Users close browser tabs mid-tool-call, and mobile networks drop packets halfway through a JSON payload, leaving the browser with half a ProductCard prop object. Guard your client components so incomplete tool invocations render safe skeleton states until the final output arrives, and make every mutating tool idempotent so a retried stream doesn't add two jackets to the cart.

Prompt drift over long sessions is subtler. Twenty turns into a styling session, a bloated message history drives up token spend and increases the odds that Gemini calls a filter tool with stale parameters from ten minutes earlier. Prune or summarize older turns on the server before calling streamText, and inject the current canonical cart state from your database as clean system context rather than expecting the model to reconstruct the cart from forty chat messages.

Run the unit economics before committing to the build. Digital Applied estimates that automated e-commerce support and shopping tickets on serverless platforms like Cloud Run cost $0.50 to $2.00 per ticket, compared with $15 to $25 for human agents. Take consultancy cost bands with a healthy grain of salt, because your real margins depend on whether shoppers use the assistant to buy high-margin gear or play twenty questions on your Vertex AI bill.

Draw that product boundary before writing a line of Next.js code. If your catalog has twelve simple products, a fast search bar and static filters will beat an LLM every day of the week on both latency and Cloud Run spend. Generative UI earns its keep when buying takes consultation: comparing specs across dozens of variants, assembling compatible kits, or translating messy human constraints into structured queries. That is where rendering the right interactive card at the right second turns a browsing tab into a paid order.

Frequently asked questions

Why shouldn't I use React Server Components for generative UI in production?

Vercel marks AI SDK RSC as experimental because Next.js Server Actions cannot abort an active stream, components flicker and remount when the stream completes, and payloads suffer from quadratic data transfer overhead. Instead, Vercel AI SDK 7.0 defaults to AI SDK UI, which streams typed JSON tool parts over Server-Sent Events to client-assembled React components.

Which Gemini model works best for generative UI tool calling?

Benchmarks on e-commerce storefront prompts showed that Gemini 2.5 Flash, Gemini 2.5 Pro, and Gemini 3 achieved 0% output schema errors, whereas Gemini 2.0 Flash failed on 29% of prompts. Pairing Gemini 2.5 Flash with Zod schemas and a near-zero thinking budget for filter clicks keeps UI updates fast and prevents broken component props.

How do I manage shopping carts and concurrency on Cloud Run?

Because Cloud Run scales across stateless containers during traffic spikes, you must persist conversation history and cart state in an external database like Firestore, Redis, or PostgreSQL rather than Node.js memory. For checkout and inventory reservations, wrap availability checks and database writes in transactional locks such as PostgreSQL advisory locks, and lower the request timeout from five minutes to 60 or 120 seconds.

How many tools and steps should a shopping assistant agent use?

Google's function-calling guidance recommends keeping the active toolset between 10 and 20 tools before selection accuracy degrades, starting with core widgets such as product cards, carousels, and price filters. You should also cap multi-step loops, such as setting a five-step limit in the Vercel AI SDK, to prevent runaway execution and token costs.

Sources

Book a discovery call

30 minutesGoogle MeetFree