Skip to main content

工作流自动化

Shopify Flow 是一个可视化自动化平台,让商家和开发者能够创建由商店事件触发的工作流。与 AI 结合后,Flow 的功能会大幅增强——不再是僵化的 if/then 规则,工作流可以根据上下文、模式和预测做出细致的决策。本课程涵盖 AI 增强型 Flow 自动化的架构,并逐步介绍五种生产环境模式。

什么是 Shopify Flow?

Shopify Flow 适用于所有 Shopify 方案。它使用触发器-条件-动作模型:事件触发工作流,条件筛选哪些事件继续执行,动作则执行预期的结果。开发者可以通过其应用使用自定义触发器、条件和动作来扩展 Flow。

Shopify Flow + AI 集成模式

将 AI 集成到 Flow 工作流中有三种主要模式:

模式 1:AI 作为条件

使用 AI 模型来评估工作流是否应该继续执行。AI 不使用硬编码规则,而是评估上下文并返回决策。

模式 2:AI 作为动作

触发器和条件使用标准的 Flow 逻辑,但动作涉及 AI 生成的内容或决策。

模式 3:AI 作为编排器

AI 评估整个上下文并决定执行多个可能工作流中的哪一个。这是最强大的模式,但需要谨慎的错误处理。

使用 AI 构建自定义 Flow 动作

要在 Flow 中添加 AI 驱动的动作,您需要在 Shopify 应用中创建 Flow action extension。以下是完整的设置:

# shopify.extension.toml
[extension]
type = "flow_action"
name = "AI Product Description Generator"
handle = "ai-product-description"

[[extension.settings]]
key = "tone"
type = "single_line_text_field"
name = "Writing Tone"
description = "The tone for generated descriptions (e.g., professional, casual, luxurious)"

[[extension.settings]]
key = "max_length"
type = "number_integer"
name = "Maximum Length"
description = "Maximum character count for the generated description"
// extensions/flow-ai-action/src/index.ts
import { ActionHandler } from '@shopify/flow-extensions';
import Anthropic from '@anthropic-ai/sdk';

const anthropic = new Anthropic();

export const handler: ActionHandler = async (payload) => {
const { product_title, product_type, product_vendor, tags, tone, max_length } = payload;

const response = await anthropic.messages.create({
model: 'claude-sonnet-4-20250514',
max_tokens: parseInt(max_length) || 500,
messages: [
{
role: 'user',
content: `Write a product description for an e-commerce store.

Product: ${product_title}
Type: ${product_type}
Brand: ${product_vendor}
Tags: ${tags?.join(', ')}
Tone: ${tone || 'professional'}
Max length: ${max_length || 300} characters

Requirements:
- Lead with the primary benefit
- Include relevant keywords naturally for SEO
- End with a subtle call to action
- Do not use generic filler phrases like "high quality" without specifics`,
},
],
});

const description = response.content[0].type === 'text'
? response.content[0].text
: '';

// 将结果返回给 Flow 供下一个动作使用
return {
generated_description: description,
};
};

自动化库存管理

AI 驱动的库存管理超越了简单的再订购点警报。它能预测需求、识别滞销库存并建议行动方案。

需求预测工作流

// src/workflows/inventory-forecasting.ts
interface InventoryForecast {
productId: string;
currentStock: number;
predictedDemand: number; // Units expected to sell in next 14 days
reorderPoint: number;
recommendedOrderQuantity: number;
confidence: number;
reasoning: string;
}

export async function generateInventoryForecasts(
shopId: string
): Promise<InventoryForecast[]> {
// Gather historical data
const salesHistory = await db.orders.aggregate({
shopId,
period: '90d',
groupBy: 'product_variant',
});

const seasonalTrends = await db.analytics.getSeasonalPatterns(shopId);
const currentInventory = await shopifyAdmin.getInventoryLevels(shopId);

// Use AI to generate forecasts with reasoning
const response = await anthropic.messages.create({
model: 'claude-sonnet-4-20250514',
max_tokens: 4000,
messages: [
{
role: 'user',
content: `Analyze this inventory data and generate demand forecasts.

Sales History (last 90 days):
${JSON.stringify(salesHistory, null, 2)}

Seasonal Patterns:
${JSON.stringify(seasonalTrends, null, 2)}

Current Inventory Levels:
${JSON.stringify(currentInventory, null, 2)}

Current Date: ${new Date().toISOString().split('T')[0]}

For each product variant, provide:
1. Predicted demand for the next 14 days
2. Whether current stock is sufficient
3. Recommended reorder quantity (if needed)
4. Confidence level (0-1) and reasoning

Return as a JSON array.`,
},
],
});

return JSON.parse(
response.content[0].type === 'text' ? response.content[0].text : '[]'
);
}
不要盲目自动补货

AI 需求预测功能强大但并非完美。对于高价值的库存决策,务必包含人工审核步骤。使用 Flow 将补货建议以 Sidekick Pulse 通知的方式发送给商家,而不是自动下达采购订单。

使用 AI 进行客户分群

传统分群使用僵化的规则(消费超过 $500、订购 3 次以上)。AI 分群能识别商家可能从未想到的细致行为模式。

// src/workflows/customer-segmentation.ts
export async function segmentCustomers(shopId: string) {
const customers = await shopifyAdmin.getCustomers(shopId, {
fields: ['id', 'email', 'orders_count', 'total_spent', 'tags',
'created_at', 'last_order_date', 'average_order_value'],
limit: 1000,
});

const response = await anthropic.messages.create({
model: 'claude-sonnet-4-20250514',
max_tokens: 3000,
messages: [
{
role: 'user',
content: `Analyze these customers and create meaningful segments for an e-commerce store.

Customer Data:
${JSON.stringify(customers, null, 2)}

Create 5-8 segments. For each segment:
- Name (merchant-friendly, e.g., "Loyal Champions" not "Cluster 3")
- Criteria (what defines this segment)
- Size (number of customers)
- Customer IDs belonging to this segment
- Recommended marketing action

Focus on actionable segments that a merchant can target with specific campaigns.
Return as JSON.`,
},
],
});

const segments = JSON.parse(
response.content[0].type === 'text' ? response.content[0].text : '[]'
);

// 通过 Admin API 将分群标签应用到客户
for (const segment of segments) {
for (const customerId of segment.customerIds) {
await shopifyAdmin.addCustomerTag(customerId, `segment:${segment.name}`);
}
}

return segments;
}

AI 可能识别的分群示例

分群条件行动
周末战士80% 以上的订单在周六至周日下单,平均消费 $75在周五晚间排程电子邮件营销活动
送礼达人多个配送地址,在节日前后有消费高峰推广礼品包装和礼品卡
浏览重度放弃者每笔订单浏览超过 10 次,购物车放弃率高触发比较指南和决策支持内容
一次性购买风险30 天前单次购买,无回访记录在客户流失前发送有针对性的挽回优惠
加购就绪持续购买中阶产品且参与度高呈现高阶产品推荐

动态定价

定价透明度

动态定价必须以负责任的方式实施。许多司法管辖区对价格歧视有相关法规。务必确保您的定价逻辑透明、不基于受保护特征进行歧视,并符合当地法律。使用 AI 进行基于需求的定价,而非基于客户的定价。

AI 驱动的动态定价根据需求信号、竞争、库存水平和市场状况调整产品价格。

// src/workflows/dynamic-pricing.ts
interface PricingRecommendation {
variantId: string;
currentPrice: number;
recommendedPrice: number;
reasoning: string;
expectedImpact: string;
}

export async function generatePricingRecommendations(
shopId: string,
productIds: string[]
): Promise<PricingRecommendation[]> {
const products = await shopifyAdmin.getProducts(shopId, productIds);
const salesVelocity = await db.analytics.getSalesVelocity(shopId, productIds);
const inventoryLevels = await shopifyAdmin.getInventoryLevels(shopId);

const response = await anthropic.messages.create({
model: 'claude-sonnet-4-20250514',
max_tokens: 2000,
messages: [
{
role: 'user',
content: `Recommend pricing adjustments based on this data.

Rules:
- Never increase price more than 15% above the base price
- Never decrease price more than 30% below the base price
- Prioritize clearing slow-moving inventory
- Consider margin floors (never price below cost + 10%)

Products and current data:
${JSON.stringify({ products, salesVelocity, inventoryLevels }, null, 2)}

For each product, recommend a price adjustment with reasoning.
Return as JSON array.`,
},
],
});

return JSON.parse(
response.content[0].type === 'text' ? response.content[0].text : '[]'
);
}

自动化营销

结合 Flow 触发器与 AI,创建能够响应实时商店事件的营销活动。

购后电子邮件序列

// Flow trigger: Order Created
// This action generates a personalized follow-up email sequence

export async function generatePostPurchaseSequence(order: Order) {
const response = await anthropic.messages.create({
model: 'claude-sonnet-4-20250514',
max_tokens: 2000,
messages: [
{
role: 'user',
content: `Create a 3-email post-purchase sequence for this order.

Order details:
- Products: ${order.lineItems.map((i) => i.title).join(', ')}
- Total: ${order.totalPrice}
- Customer name: ${order.customer.firstName}
- Is first order: ${order.customer.ordersCount === 1}

Email 1: Thank you (send immediately)
Email 2: Usage tips for purchased products (send day 3)
Email 3: Complementary product recommendation (send day 7)

For each email, provide: subject line, preview text, and body (HTML).
Keep tone warm and helpful. Do not be pushy about the upsell.`,
},
],
});

return JSON.parse(
response.content[0].type === 'text' ? response.content[0].text : '[]'
);
}

订单路由优化

对于拥有多个配送地点的商家,AI 可以根据距离、库存水平、运费和配送速度来优化由哪个仓库来处理每笔订单。

// src/workflows/order-routing.ts
interface RoutingDecision {
orderId: string;
assignedLocationId: string;
locationName: string;
estimatedShippingCost: number;
estimatedDeliveryDays: number;
reasoning: string;
}

export async function routeOrder(order: Order): Promise<RoutingDecision> {
const locations = await shopifyAdmin.getLocations();
const inventoryByLocation = await shopifyAdmin.getInventoryByLocation(
order.lineItems.map((i) => i.variantId)
);
const customerAddress = order.shippingAddress;

const response = await anthropic.messages.create({
model: 'claude-sonnet-4-20250514',
max_tokens: 500,
messages: [
{
role: 'user',
content: `Select the optimal fulfillment location for this order.

Fulfillment Locations:
${JSON.stringify(locations, null, 2)}

Inventory by Location:
${JSON.stringify(inventoryByLocation, null, 2)}

Ship-to Address: ${customerAddress.city}, ${customerAddress.province}, ${customerAddress.country}

Order Items: ${order.lineItems.map((i) => `${i.title} (qty: ${i.quantity}, variant: ${i.variantId})`).join(', ')}

Optimization priorities:
1. All items must be in stock at the chosen location (no split shipments if possible)
2. Minimize shipping distance to customer
3. Balance load across warehouses (prefer locations with higher stock levels)

Return JSON with: assignedLocationId, locationName, estimatedShippingCost, estimatedDeliveryDays, reasoning.`,
},
],
});

return JSON.parse(
response.content[0].type === 'text' ? response.content[0].text : '{}'
);
}
拆分出货处理

当没有单一地点能够完成整笔订单时,实施两阶段路由策略。首先,尝试找到单一地点。如果失败,使用 AI 来确定最佳拆分方式,以最小化总运费同时将出货次数降到最低(客户偏好较少的包裹)。

在 Flow 中整合所有环节

这些 AI 驱动的动作在您的应用中注册为 Flow action。商家随后可以在 Flow 编辑器中以可视化方式将它们串联起来:

  1. 触发器:订单创建
  2. 条件:订单金额 > $50
  3. 动作:AI 欺诈检查(您的扩展)
  4. 条件:欺诈分数 < 0.3
  5. 动作:AI 订单路由(您的扩展)
  6. 动作:AI 购后电子邮件序列(您的扩展)
  7. 动作:更新客户分群标签(您的扩展)

每个动作独立运作,从 Flow 的上下文中接收数据,并返回后续动作可以使用的结果。

后续步骤

您现在已经学习了四种核心 Agentic 模式。在下一个模块 构建应用 中,您将学习如何将这些模式打包成具有适当架构、认证和部署的生产级 Shopify 应用。