翻篇收录说明
翻篇网页快照

Building Conversational Commerce with Multi-Agent Swarms on GCP: A Working Prototype - Google Developers Blog

https://developers.googleblog.com/building-conversational-commerce-with-multi-agent-swarms-on-gcp-a-working-prototype/

最近抓取:2026-12-01 17:27:02(北京时间)

最近内容变化:2026-12-01 17:27:02(北京时间)

这是最近一次有效抓取的文本快照,不含网页脚本、图片和动态交互内容。实际网页可能已更新。

访问原网页

页面简介

Learn how to build a Conversational User Interface (CUI) using AI in this step-by-step guide.

正文摘录

Building Conversational Commerce with Multi-Agent Swarms on GCP: A Working Prototype OCT. 27, 2026 Prateek Khushalani Software Engineer Share Facebook Twitter LinkedIn Mail Introduction: From Blueprint to Working PrototypeImagine ordering your weekly groceries as naturally as texting a friend:"Hey, we're out of milk and eggs. Can you also add some snacks for Friday movie night?"In our previous post, Building Conversational Commerce with Multi-Agent Swarms on GCP, we shared the architectural blueprint for conversational commerce—proposing a 3-layer decoupled design (Ingress, Memory, and Cognition) to solve messaging timeouts, state tracking, and response reliability.While blueprints establish the architecture on paper, production readiness demands working software. In this post, we take that blueprint and bring it to life with a functional prototype called HappyDelivery.Using LangGraph, Gemini, FastAPI, and Google Cloud, we'll walk through the code, the state machine, deterministic financial tools, and an automated verification suite that demonstrates how this multi-agent swarm operates in practice.1. The Prototype Stack: 3 Layers, 3 DiagramsTo build a reliable commerce swarm, we implemented three decoupled layers that handle the journey of every customer text message: Let's examine how each layer functions in code with its own dedicated architecture.Layer 1: Ingress Layer (Omni-Channel Webhook Gateway on GKE/Cloud Run + Cloud Pub/Sub)A frequent question when designing conversational commerce is: how does a message sent by a customer on their smartphone actually land in Layer 1, and can this architecture support messaging platforms beyond WhatsApp?How Client Devices Connect to Layer 1End users do not communicate directly with your Google Cloud servers. Instead, customer messages traverse an operator ecosystem before landing on your webhook: Supporting Multiple Messaging Channels: WhatsApp, RCS, Apple Messages, and SMSEvery major consumer messaging platform operates on the exact same fundamental contract: an asynchronous HTTPS POST webhook delivery with a strict HTTP acknowledgement timeout:WhatsApp (Meta Cloud API): Requires a prompt HTTP 200 OK acknowledgement and validating the X-Hub-Signature-256 header against your Meta App Secret using HMAC-SHA256. If your server times out or returns a non-200 status, Meta marks delivery as failed and initiates exponential backoff retries (for up to 7 days), which can trigger duplicate order deliveries.Google RCS Business Messaging (RBM): Delivered via Google Cloud Pub/Sub push or HTTPS webhooks authenticated via OAuth2 / Service Account JWT bearer tokens or payload HMAC signature verification (X-Goog-Signature). Requires returning HTTP 200 promptly to avoid webhook delivery retries.Apple Messages for Business (AMB): Delivered through an Apple-approved Messaging Service Provider (MSP). Authenticated via provider webhook signatures, JSON Web Signatures (JWS), or Mutual TLS (mTLS) with prompt HTTP 200 OK acknowledgement expectations.SMS / MMS (Twilio, Sinch, Infobip): Standard form-encoded or JSON POST webhooks signed with vendor-specific HMAC tokens (e.g., X-Twilio-Signature).While the payload schemas and cryptographic headers differ slightly between platforms, Layer 1 abstracts away all client differences:Security & Signature Verifier: Routes incoming requests through platform-specific signature validators (MetaHmacValidator, RcsJwtValidator, AppleJwsValidator, TwilioHmacValidator).Payload Normalization Adapter: Ingests vendor-specific payloads and transforms them into a unified, channel-agnostic canonical schema (CommonMessageEvent): { "channel": "whatsapp", # or "rcs", "apple_messages", "sms" "sender_id": "+1xxxxxxxxxx", # Verified E.164 phone number "text": "Out of milk & eggs", "timestamp": 1773428900, "raw_metadata": {...} } Python Copied Sub-150ms Asynchronous Handshake: Queues the canonical message onto Google Cloud Pub/Sub and returns HTTP 200 OK in < 150ms.This ensures the rest of your system—Session Store (Layer 2) and Agent Swarm (Layer 3)—operates on clean, normalized data without caring whether the shopper sent their message from an iPhone, an Android RCS chat, or a WhatsApp thread.Layer 2: Session & Cart Layer (Cloud Memorystore Redis)Messaging platforms are completely stateless: every text message arrives as an isolated webhook event. To provide a coherent shopping experience, the system must instantly reconstruct the customer's full context without having to re-read or re-parse days of chat logs on every turn.We use Cloud Memorystore (Redis) keyed by the customer's verified phone number (session:{phone_number}) to store active state: Real-World Customer Journeys (CUJs) Powered by this LayerThe Asynchronous Shopping Trip (Pause & Resume): In real life, people don't complete an order in one sitting. A customer might text at 9:00 AM: "Add a gallon of milk to my cart", close WhatsApp to catch a train, and reply at 2:00 PM: "Also add bread and eggs, and what's my total?" Because session state is cached in Redis, the system instantly restores their active cart ([Milk]) and recalculates totals without losing a beat.Contextual Guardrails (Dietary Preferences & Addresses): If a user's profile specifies dietary_preferences: ["Nut-Free"], the Inventory Agent automatically respects that preference when recommending movie night snacks—without the user having to re-declare their allergy in every text message.Safe, Tokenized Checkout: The customer profile holds tokenized payment references (customer_id: "cust_9821", payment_ref: "Visa ending in 4242"). The LLM only ever reads the friendly masked label, while the transaction tools pass the tokenized customer ID to Stripe. Raw credit card numbers never touch chat prompts or logs.💡 Scale & Performance: What QPS Can the Base Infrastructure Handle?A common question in conversational commerce is whether state lookups will introduce latency. Here is what the baseline infrastructure supports:Raw Throughput: A single, baseline Google Cloud Memorystore for Redis instance (Basic Tier, 1–5 GB memory) easily delivers 10,000 to 50,000+ QPS with sub-millisecond (< 1ms) read/write latencies.Conversational QPS: Each chat turn requires 2–3 Redis operations (session fetch, cart mutation, state commit). This means a single standard Redis instance comfortably handles 3,000 to 15,000 active conversational turns per second before needing Redis Cluster horizontal sharding or read replicas.Memory Capacity: An active session payload (profile + active cart + preferences) takes ~2 KB to 5 KB of serialized JSON. A modest 5 GB Redis instance can hold over 1,000,000 concurrent active shopping carts in memory simultaneously.Key Takeaway: In practice, the Session & Cart Layer will never be the bottleneck—it easily outpaces upstream webhook inference and downstream LLM inference.Layer 3: Agent Swarm Layer (Multi-Agent Orchestration with Gemini)Rather than relying on a single monolithic prompt to handle every task, we separate reasoning into a swarm of specialized agents: Supervisor (Gemini Flash): Acts as a low-latency router, classifying the customer's request and delegating it to the right specialist.Profile Specialist: Retrieves personal preferences and issues secure single-use auth links for new buyers.Inventory Specialist (Gemini Pro): Bound to warehouse tools; queries stock, recommends pairing items, and mutates the cart.Transaction Specialist (Gemini Pro): Bound to payment tools; calculates totals deterministically and initiates charges.2. From Architecture to Code: Building the 3 LayersNow that we have seen the high-level design of the three layers, let's look at the actual Python prototype code that brings each layer to life.Layer 1 Prototype: Omni-Channel FastAPI Ingress & Security NormalizationThe goal of this service is simple: verify authenticity across any inbound channel, normalize the payload into a canonical schema, and get off the critical path in < 150ms.Here is our implementation showing how multiple messaging channels (WhatsApp, RCS, Apple Messages, SMS) are handled by pluggable adapters: import hashlib, hmac, json, time from typing import Any, Dict, Optional from pydantic import BaseModel class CommonMessageEvent(BaseModel): """Channel-agnostic canonical representation of an inbound customer message.""" channel: str # "whatsapp", "rcs", "apple_messages", "sms" sender_id: str # E.164 phone number: "+1xxxxxxxxxx" text: str timestamp: float raw_metadata: Dict[str, Any] class HappyDeliveryIngressService: """Omni-Channel FastAPI Ingress with cryptographic verification and async queueing.""" def __init__(self, meta_secret: str, rcs_secret: str = ""): self.meta_secret = meta_secret self.rcs_secret = rcs_secret self.publisher = CloudPubSubPublisher() def verify_whatsapp_signature(self, payload_bytes: bytes, sig_header: str) -> bool: """Verifies X-Hub-Signature-256 header using constant-time comparison.""" if not sig_header or not sig_header.startswith("sha256="): return False expected_hash = hmac.new( self.meta_secret.encode("utf-8"), payload_bytes, hashlib.sha256 ).hexdigest() provided_hash = sig_header.split("sha256=")[1] return hmac.compare_digest(expected_hash, provided_hash) def normalize_payload(self, channel: str, raw_payload: Dict[str, Any]) -> Optional[CommonMessageEvent]: """Extracts sender and message text into a canonical schema.""" if channel == "whatsapp": # Meta Graph Webhook structure entry = raw_payload.get("entry", [{}])[0] change = entry.get("changes", [{}])[0].get("value", {}) message = change.get("messages", [{}])[0] return CommonMessageEvent( channel="whatsapp", sender_id=message.get("from", ""), text=message.get("text", {}).get("body", ""), timestamp=float(message.get("timestamp", time.time())), raw_metadata={"message_id": message.get("id")}, ) elif channel == "rcs": # Google RCS Business Messaging structure return CommonMessageEvent( channel="rcs", sender_id=raw_payload.get("senderPhoneNumber", ""), text=raw_payload.