Building practical AI
Deepak Kumar Tiwari

Deepak Kumar Tiwari

Technology & AI Leader · Building practical systems

Production workflows / Guide 30

A Retail Replenishment Agent That Orders Against Inventory Position

Build a retail replenishment agent that accounts for available stock, confirmed inbound orders, lead times, and pack sizes while keeping purchase approval explicit.

Illustrative engineering guide. Examples are not client deployments, production-ready integrations, or evidence of measured results. Validate the design with your domain and security owners.

Reference workflow: Store-SKU inventory snapshot; Demand and lead-time calculation; Pack and capacity constraint checks; Buyer-approved purchase proposal; Order acknowledgment reconciliation.
Reference workflow. Steps identify responsibilities, not necessarily separate agents. Branches and recovery paths are explained below. Open full-size diagram.

A retail replenishment agent should prevent the same shortage from generating two purchase orders. Imagine a hypothetical grocery buyer who sees six units on the shelf, twenty-four units already ordered, and a supplier email warning that half the shipment will be late. Ordering from shelf quantity alone can overstock the store; counting all inbound units as certain can cause a stockout. The useful assistant explains inventory position and uncertainty before asking a buyer to approve a bounded order.

Define the Stock You Are Planning Against

Choose a planning grain such as tenant, store, SKU, and delivery date. Keep sellable stock, committed stock, damaged or quarantined units, confirmed inbound quantities, and expected arrival dates distinct. Physical stock, shelf stock, and available-to-sell stock answer different questions. A backroom case may solve a shelf gap without a supplier purchase.

Shopify’s InventoryLevel documentation explicitly represents quantities at an item-location pair and distinguishes inventory states. The same modeling discipline is useful outside Shopify. Avoid subtracting committed units twice if the source’s available quantity already excludes them. Document the source-to-planning mapping with examples that a buyer can verify.

An LLM can interpret the supplier’s delay message, summarize a demand exception, and explain a proposal. Deterministic software must calculate quantities, apply pack sizes, enforce budgets, and manage purchase-order identity. Forecasting should use an evaluated statistical model or transparent baseline, not an improvised number produced inside a chat response.

Start With a Transparent Reorder Calculation

For a first implementation, use an order-up-to policy over lead time plus review interval. Estimate demand during that horizon, add a reviewed safety allowance, and subtract inventory position. Count inbound units only according to an explicit arrival and confidence policy. Orders arriving after the needed date do not protect that earlier demand window.

The following executable Python illustrates integer-unit arithmetic for a single SKU. It is not a complete purchasing policy or demand forecast.

def proposed_units(target_units, sellable_units, confirmed_inbound_units,
                   case_pack, capacity_units):
    values = (target_units, sellable_units, confirmed_inbound_units,
              capacity_units)
    if any(type(v) is not int or v < 0 for v in values):
        raise ValueError("Expected nonnegative integer units")
    if type(case_pack) is not int or case_pack <= 0:
        raise ValueError("Invalid case pack")
    position = sellable_units + confirmed_inbound_units
    shortage = max(0, target_units - position)
    rounded = ((shortage + case_pack - 1) // case_pack) * case_pack
    if position + rounded > capacity_units:
        return {"status": "buyer_review", "units": rounded}
    return {"status": "proposal", "units": rounded}

assert proposed_units(40, 6, 24, 12, 60)["units"] == 12
assert proposed_units(40, 6, 12, 12, 60)["units"] == 24
assert proposed_units(40, 6, 24, 12, 40)["status"] == "buyer_review"

The example assumes inbound units arrive within the planning horizon and that sellable stock is already net of commitments. Capacity is a deliberately conservative unit-level check; real storage constraints may depend on time, volume, temperature zone, and multiple SKUs. Production also needs minimum order values, supplier calendars, shelf life, tax, currency, and buyer authorization. Do not treat the returned proposal as permission to order.

Make Demand Uncertainty Visible

Begin with a simple baseline, such as weekday-adjusted recent sales, and compare it with more complex forecasts through rolling historical backtests. Keep forecast version, training cutoff, horizon, and error distribution with each proposal. A promotion or holiday needs an explicit event feature or buyer override, not a model’s vague claim that demand will surge.

Observed sales during a stockout underestimate demand. Label censored periods rather than teaching the forecast that shoppers stopped wanting the item. Likewise, a store closure is not ordinary low demand. If inventory records are unreliable, request a cycle count or mark the recommendation uncertain before optimizing order quantity.

For perishables, expected sales before expiry constrain the useful quantity. A full case that exceeds likely sell-through may require a transfer, smaller supplier pack, or buyer exception. The assistant should expose that conflict instead of rounding up and declaring the problem solved. Do not infer food safety from appearance or a textual note; quality release remains with authorized staff.

The minimum workflow combines inventory and order readers, a forecast calculator, a policy evaluator, and a buyer review queue. One coordinator can explain exceptions. A supplier-document specialist sub-agent earns its complexity only when it extracts delivery commitments from varied formats with evidence references. It must not independently negotiate terms or send purchase orders.

Preserve Purchase Identity Through Failure

Create a proposal with store-SKU scope, source versions, calculation inputs, supplier, requested date, quantity, and budget impact. Approval binds to those values. Re-read inventory and existing orders before submission; another buyer’s purchase may eliminate the shortage. A changed pack size or price should invalidate the old approval and trigger a revised proposal.

Use a durable operation key and a unique internal purchase reference. PostgreSQL constraints can enforce uniqueness in your own records, but they cannot prevent duplicate orders in a supplier system by themselves. The adapter must use supported idempotency or reconcile by the external reference after uncertain delivery.

If a supplier accepts an order but the response is lost, mark submission uncertain and query before retrying. If only half the quantity is acknowledged, preserve requested, accepted, and outstanding quantities separately. Never treat the entire order as confirmed inbound. Cancellation is a new approved operation, not deletion of the original purchase history.

Server-side authorization scopes buyers to tenants, stores, suppliers, and spend limits. Keep supplier credentials outside model context, and segregate one merchant’s demand and prices from another’s caches. Supplier emails and catalog descriptions are untrusted input. OWASP’s LLM security project explains why a message demanding a larger order must not override budget or approval controls.

Acceptance Tests That Reflect Buying Work

Use the following cases as release gates:

  • Available inventory already excludes committed units. The adapter does not subtract commitments again or inflate the shortage.
  • An inbound shipment moves beyond the planning horizon. Its units stop protecting the earlier demand window and the proposal explains why.
  • Case-pack rounding exceeds storage capacity. The system requests buyer review rather than submitting an infeasible order.
  • A supplier accepts an order and the response is lost. Reconciliation discovers the same reference and prevents a second purchase.
  • A malicious supplier email requests an unauthorized store export and doubled quantity. Neither read scope nor purchasing limits change.

Baseline buyer planning minutes, stockout duration, emergency purchases, and waste by category. Measure unit fill rate as units fulfilled divided by units demanded where demand is observable; identify estimates used for lost sales separately. Measure proposal correction rate as buyer-changed proposals divided by reviewed proposals, recording why changes were needed.

Guardrails include expired or wasted units, excess inventory value, duplicate purchases, and budget overruns. Compare forecast error through rolling backtests before a shadow buying pilot. Then allow buyer-approved orders for a small nonperishable category. Proposed service-level improvements are hypotheses, not achieved results, and should be evaluated against carrying cost rather than maximized blindly.

The data quality guide explains how late and duplicated records distort this calculation. The procurement negotiation guide covers commercial terms beyond replenishment arithmetic. Data Engineering & Analytics Platforms supports reliable inventory evidence. Start with one store-SKU contract and reconcile its available, incoming, and committed states before building a more sophisticated forecast.

Sources