Skip to main content

ワークフロー自動化

Shopify Flowは、マーチャントと開発者がストアイベントによってトリガーされるワークフローを作成できるビジュアル自動化プラットフォームです。AIと組み合わせると、Flowは劇的に強力になります——硬直したif/thenルールの代わりに、コンテキスト、パターン、予測に基づいた繊細な判断をワークフローが行えるようになります。このレッスンでは、AI強化型Flow自動化のアーキテクチャを解説し、5つの本番パターンを順を追って説明します。

Shopify Flowとは?

Shopify Flowはすべてのshopifyプランで利用可能です。トリガー-条件-アクションモデルを使用します:イベントがワークフローをトリガーし、条件がどのイベントを進行させるかをフィルタリングし、アクションが目的の結果を実行します。開発者はアプリを通じてカスタムトリガー、条件、アクションでFlowを拡張できます。

Shopify Flow + AI統合パターン

AIをFlowワークフローに統合するための3つの主要パターンがあります:

パターン1:条件としてのAI

AIモデルを使用して、ワークフローを進行させるべきかどうかを評価します。ハードコードされたルールの代わりに、AIがコンテキストを評価して判断を返します。

パターン2:アクションとしてのAI

トリガーと条件は標準的なFlowロジックですが、アクションにはAI生成のコンテンツや判断が含まれます。

パターン3:オーケストレーターとしてのAI

AIが全体のコンテキストを評価し、複数の可能なワークフローのうちどれを実行するかを決定します。これは最も強力なパターンですが、慎重なエラー処理が必要です。

AIによるカスタムFlowアクションの構築

AI搭載のアクションをFlowに追加するには、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 : '{}'
);
}
分割出荷の処理

単一のロケーションで注文全体をフルフィルメントできない場合、2パスのルーティング戦略を実装してください。まず単一ロケーションを見つけようとします。それが失敗した場合、AIを使用して、出荷回数を最小限に保ちながら総送料を最小化する最適な分割を決定してください(顧客はパッケージが少ない方を好みます)。

Flowですべてを接続する

これらのAI搭載アクションは、アプリのFlowアクションとして登録されます。マーチャントはFlowエディターでビジュアルにそれらを組み合わせます:

  1. トリガー:注文作成
  2. 条件:注文額 > $50
  3. アクション:AI不正チェック(あなたのエクステンション)
  4. 条件:不正スコア < 0.3
  5. アクション:AI注文ルーティング(あなたのエクステンション)
  6. アクション:AI購入後メールシーケンス(あなたのエクステンション)
  7. アクション:顧客セグメントタグの更新(あなたのエクステンション)

各アクションは独立して動作し、Flowのコンテキストからデータを受け取り、後続のアクションが使用できる結果を返します。

次のステップ

これで4つのコアAgenticパターンをすべてカバーしました。次のモジュールアプリの構築では、これらのパターンを適切なアーキテクチャ、認証、デプロイメントを備えた本番Shopifyアプリにパッケージ化する方法を学びます。