E-commerce Dual-Agent Architecture: From Conversational Interaction to Safety Guardrails

    This article explains how to design a dual-agent e-commerce architecture with separate consumer-facing and merchant-facing agents, defines their responsibility boundaries, and describes the safety mechanisms required before launch. It covers in-conversation UI rendering, cross-session memory, Text-to-SQL boundaries, write-operation staging and approval, payment isolation, price and inventory anchoring, deployment options, and common pitfalls. The core design principle is that the model handles understanding and expression, while business systems handle facts and transactions.

    E-commerce Dual-Agent Architecture: From Conversational Interaction to Safety Guardrails

    This article is intended for technical leads and engineers who need to build e-commerce agents. It explains the responsibility boundaries of the consumer-side and merchant-side agents, along with the safety mechanisms that must be in place before launch. The core design principle is simple: the model handles understanding and expression, while business systems handle facts and transactions.

    1. Responsibility Boundaries of the Dual-Agent Architecture

    An e-commerce agent is typically split into two roles.

    The consumer shopping agent is embedded in the merchant’s app or website. It helps users clarify their needs, search for products, compare specifications, plan shopping lists, and maintain the shopping cart. It faces public users and has minimal permissions. Its main risks are incorrect recommendations and information leakage.

    The merchant operations agent serves operations staff. It handles sales analysis, inventory alerts, replenishment suggestions, and drafting campaign copy. It has access to business data, and its main risks are unauthorized queries and erroneous operations.

    Both sides can share foundational capabilities such as intent understanding, tool invocation, session management, and audit logging, but their permissions must be separated. The two agents should use different service accounts, different data views, and different tool whitelists.

    2. Consumer Side: In-Conversation UI and Memory

    2.1 In-Conversation UI

    Plain text struggles to clearly present specification differences across multiple products. After the agent retrieves products, it should return structured data, and the frontend should render it by type as product cards, comparison tables, or shopping cart components. Below is an example schema; the values are for format illustration only:

    1. {
    2. "type": "product_compare",
    3. "version": "1.0",
    4. "items": [
    5. {
    6. "product_id": "p_1001",
    7. "title": "Phone A",
    8. "price": { "amount": 3999, "currency": "CNY", "source": "product_center" },
    9. "battery_hours": 18
    10. }
    11. ],
    12. "fallback_text": "The battery life comparison between Phone A and Phone B has been generated. Refer to the product detail pages for exact values."
    13. }

    Recommended frontend rendering strategy:

    • Validate type and version first. If the type is unrecognized, output plain text.
    • If non-core fields are missing, render only the fields that are present.
    • If core fields such as price or stock are missing, degrade the entire component to text and show “Information temporarily unavailable.”
    • If rendering throws an exception, fall back to fallback_text so the user still gets the conclusion.

    2.2 Cross-Session Memory

    Preferences such as brand affinity, size, and budget range can be stored in a key-value store and read/written by user_id. Memory must meet the following requirements:

    • Users can view, modify, and delete their own preference profiles.
    • Store only preference information. Do not store sensitive fields such as phone numbers, shipping addresses, or payment information.
    • Recommendation results must still go through price and inventory validation (see Section 5). Memory can influence ranking but cannot replace real-time data.

    3. Building the Merchant Operations Analysis Agent

    3.1 Sales Analysis and Text-to-SQL Boundaries

    After an operations user asks a question in natural language, the agent converts it to SQL and queries the database. Restrictions must be enforced outside the database:

    • Use a read-only account. Prohibit INSERT, UPDATE, DELETE, and DDL statements.
    • Expose only whitelisted tables and views, such as order summary views and SKU daily sales views.
    • Use row-level permissions to limit the query scope so each merchant sees only its own data.
    • Review generated SQL before execution: allow only a single statement, block access to tables outside the whitelist, and set execution timeouts and row-count limits.

    For inventory alerts, monitor stock for each SKU, generate an alert when stock falls below the safety threshold, and let operations staff confirm replenishment quantities.

    3.2 Write-Operation Staging and Approval

    For changes such as marketing copy and price adjustment suggestions, the agent does not write directly to the production database. These changes enter a staging area and move through the following states:

    Draft → Pending Review → Approved → Applied
    Pending Review → Rejected → Draft (can be resubmitted after revision)
    Applied → Rolled Back (a reverse change record is generated)

    Every state change should record the following audit fields:

    Field Description
    operator Account of the initiator or approver
    action create / submit / approve / reject / apply / rollback
    created_at Timestamp, using the same time zone consistently
    diff Content difference before and after the change
    rollback_point Version number before application, used for rollback
    agent_run_id ID of the corresponding agent invocation, for tracing prompts and tool calls

    The approver and the initiator must be different accounts. If the same person submits and approves, there is effectively no approval.

    4. Payment Isolation

    The model does not touch the payment flow. The agent is only responsible for confirming the order before payment; the payment step is handed back to the native system. Before launch, verify each item in the following checklist:

    Before payment

    • The order amount is calculated server-side based on products and discount rules. Amounts passed in from the frontend or the model are never trusted.
    • The order number and amount are signed server-side, and the signature is verified during payment.

    During payment

    • Payment is completed through the native payment SDK. The agent only displays the order summary and does not receive payment credentials.
    • The payee is bound server-side and is not determined by model parameters.

    After payment

    • Payment callbacks must be signature-verified, and order status is updated only from callbacks that pass verification.
    • Payment requests carry an idempotency key to prevent duplicate charges or duplicate order creation.

    5. Price and Inventory Anchoring

    The agent does not generate price or inventory numbers. All product attributes are retrieved through tools, and the tool results must be validated. The example code below uses internal_product_service to represent the enterprise’s internal product center client:

    1. import time
    2. def get_product_snapshot(product_id: str, timeout_s: float = 0.5) -> dict:
    3. """
    4. Fetch price and inventory from the product center or ERP. If retrieval fails or data is abnormal,
    5. return an unavailable status instead of a guessed value.
    6. """
    7. try:
    8. raw = internal_product_service.fetch(product_id, timeout=timeout_s)
    9. except TimeoutError:
    10. return {"status": "unavailable", "reason": "timeout"}
    11. except Exception:
    12. return {"status": "unavailable", "reason": "upstream_error"}
    13. # Consistency checks: price must be a positive integer (in cents), and stock cannot be negative
    14. if not isinstance(raw.price_cents, int) or raw.price_cents <= 0:
    15. return {"status": "unavailable", "reason": "invalid_price"}
    16. if raw.stock < 0:
    17. return {"status": "unavailable", "reason": "invalid_stock"}
    18. return {
    19. "status": "ok",
    20. "product_id": product_id,
    21. "price_cents": raw.price_cents,
    22. "stock": raw.stock,
    23. "source": raw.source,
    24. "fetched_at": time.time(),
    25. }

    Around this tool, the following policies are also needed:

    • Set short timeouts. After a timeout, return degraded copy such as “Price cannot be confirmed right now. Please check the product page later.”
    • Use caching only for list-page display, with a short TTL determined by the business.
    • Do not read from cache during order placement or checkout; always query in real time.
    • Re-validate prices for cart items before checkout, and clearly notify users when a change is detected.

    6. Choosing a Deployment Model

    The trade-offs among the three deployment models are as follows:

    Deployment model Suitable scenarios Permission boundaries Operational cost
    API integration Existing mature backend with a need for fine-grained control over context and tool calls Authentication, rate limiting, and logging are controlled by your own services High; you maintain retries, monitoring, and key rotation yourself
    Agent SDK Complex workflows requiring coordination across multiple services Tool whitelists are defined in code and require code review Medium
    Managed platform Limited team capacity with a desire to reduce model-service operations work Depends on the platform’s tenant isolation and permission capabilities, which must be verified item by item Low, but auditing and security review remain the enterprise’s responsibility

    When choosing a managed platform, confirm at least the following before launch:

    • Whether tenant isolation meets the enterprise’s data requirements.
    • Whether access control can be refined to specific tools and data tables.
    • Whether invocation logs can be fully retained and exported.
    • Whether rate limits and cost caps can be configured.
    • Whether personal information needs to be masked before transmission.

    Reducing underlying operational burden does not mean that security responsibility is transferred.

    7. Scaffolding and Common Mistakes

    Scaffolding can generate project skeletons, business-flow definitions, and basic test suites, reducing manual work during initialization. The time required for business integration, data preparation, and security review does not disappear. The actual timeline depends on data quality, system integration complexity, and compliance requirements.

    Here are a few common mistakes:

    • Letting the model…