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 應用程式。