How an AI Platform Replaces 150+ Lines of Code for E‑commerce Promotion Risk Detection

The article explains how a natural‑language‑driven AI platform, with pre‑configured agents and parameterized calls, can replace a complex 150‑line SKU‑combination risk‑checking algorithm in e‑commerce, dramatically improving readability, maintainability, development speed, and business value while reducing cost and response time.

DaTaobao Tech
DaTaobao Tech
DaTaobao Tech
How an AI Platform Replaces 150+ Lines of Code for E‑commerce Promotion Risk Detection

Background

A business scenario requires checking multi‑SKU promotional pricing to avoid loss when the final price of a high‑price SKU falls below a baseline. The traditional solution involves writing 150+ lines of hard‑coded JavaScript that filters SKUs, finds the highest and lowest prices, calculates discounts, and flags risky items.

Problems with the Traditional Approach

Code complexity: 150‑200 lines with nested loops.

High learning curve: New developers must read and understand the intricate logic.

Maintenance pain: Any rule change (e.g., discount formula) forces code edits, testing, and redeployment.

Why AI?

Large language models excel at multi‑step reasoning and calculation, making them ideal for translating business rules expressed in natural language into executable logic.

AI Platform Solution

The AI platform provides three core capabilities:

Pre‑installed agents : Ready‑made Prompt templates (e.g., a data‑analysis agent) that encapsulate expert knowledge.

Parameterized invocation : Business parameters (job, data, type, definition) are passed to the agent without writing Prompt code.

Configuration management : Agent URLs are stored in a central configuration center, allowing version switches without code changes.

Using these features, the same risk‑checking logic can be expressed as a concise natural‑language description, letting the AI perform the reasoning and return structured results.

Step‑by‑Step Implementation

1. Choose the appropriate agent

For data analysis, select the platform’s "Data Analyst" agent, which already contains Prompt templates for tasks such as "multi‑SKU price risk detection".

2. Fill in parameters and invoke the AI

const result = await aiService.callAI({
  apiKey: 'dataAnalysisApi',
  sessionId: `task-${taskId}-${timestamp}`,
  variableMap: {
    job: `检查商品的组合计算风险
背景: 商品多规格, 活动每件优惠, 用户组合购买
步骤:
1. 筛选有效规格(库存>0, 状态正常)
2. 找最高价和最低价
3. 获取基准价(为空则调用工具)
4. 循环计算组合场景(1个高价+N个低价)
5. 判断是否超出阈值`,
    data: JSON.stringify([/* 商品数据数组 */]),
    type: 'JSON',
    definition: `[{"has_risk":"是否有风险","item_id":"商品 id","high_sku_id":"风险规格 id","low_sku_id":"组合规格 id","low_sku_num_min":"最小组合数量","loss_amount_min":"最小损失","low_sku_num_max":"最大组合数量","loss_amount_max":"最大损失"}]`
  },
  isJsonObject: true
});

3. Parse the AI response

function parseResponse(response) {
  let output = response.data?.content || response.data?.runLog?.output || response.output;
  output = output.replace(/```json
/g, '').replace(/
```/g, '');
  try { return JSON.parse(output); } catch (e) { return {}; }
}

The service layer calls parseResponse so business code stays clean.

4. Batch processing for large data sets

const batchSize = 3;
const batches = chunkArray(items, batchSize);
for (const batch of batches) {
  const batchResult = await aiService.callAI({
    apiKey: 'dataAnalysisApi',
    sessionId: `task-${taskId}-batch-${i}`,
    variableMap: {
      job: /* same job description */,
      data: JSON.stringify(batch),
      type: 'JSON',
      definition: /* same definition */
    }
  });
  riskItems.push(...batchResult.data);
}

This strategy keeps each request small (3‑5 items), ensuring stability, accuracy, and controllable token cost.

MCP (Model Context Protocol) Integration

When a required field such as base_price is missing, the AI can automatically invoke a registered MCP tool to fetch the data:

{
  "name": "queryBasePriceByItemId",
  "description": "根据商品ID查询基准价",
  "parameters": {
    "type": "object",
    "properties": { "item_id": { "type": "string", "description": "商品ID" } },
    "required": ["item_id"]
  },
  "implementation": { "type": "rpc", "service": "com.example.PriceService", "method": "queryBasePrice", "version": "1.0.0" }
}

The platform can generate this MCP definition with a single click, avoiding manual JSON Schema writing.

Version Management via Configuration Center

{
  "agentConfig": {
    "dataAnalysisApi": "https://.../agent_id/stable",
    "dataAnalysisApi_beta": "https://.../agent_id/beta"
  }
}

Business code selects the appropriate version at runtime, enabling gray releases and instant rollbacks without redeploying.

Benefits and Business Value

Development time reduced from 3‑5 days to 1‑2 days.

Code size shrank from ~150 lines to ~30 lines of invocation code.

Rule updates now require only parameter changes (minutes) instead of full code changes (days).

Readability improves dramatically; any stakeholder can understand the natural‑language rule.

Fast iteration: new agent versions are deployed centrally and take effect instantly.

Cost control: batch size and timeout (5‑10 s) keep token usage predictable.

Practical Recommendations

Prefer the platform’s one‑click MCP generation when the RPC interface is already registered.

Ensure the underlying services are stable to avoid AI timeouts.

Set reasonable request timeouts (5‑10 s) to prevent hanging.

Monitor key metrics (success rate, latency, cost) in a unified observability platform.

Design clear job prompts and output definition schemas to guide the AI.

When to Use AI vs. Traditional Code

AI is suitable for complex multi‑step reasoning, frequently changing business rules, and scenarios where data sources are scattered and need on‑demand fetching. It is less appropriate for millisecond‑level latency, simple threshold checks, or ultra‑high‑cost‑sensitivity use cases.

Conclusion

The AI platform turns a hard‑coded 150‑line risk‑checking routine into a concise, maintainable, and configurable workflow, delivering faster development, lower maintenance overhead, and clearer business logic while keeping costs under control.

e-commerceAIMCPlow-codeRisk Detection
DaTaobao Tech
Written by

DaTaobao Tech

Official account of DaTaobao Technology

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.