워크플로우 자동화
Shopify Flow는 판매자와 개발자가 스토어 이벤트에 의해 트리거되는 워크플로우를 생성할 수 있는 시각적 자동화 플랫폼입니다. AI와 결합하면 Flow는 극적으로 강력해집니다 -- 경직된 if/then 규칙 대신, 워크플로우가 컨텍스트, 패턴, 예측에 기반한 섬세한 결정을 내릴 수 있습니다. 이 레슨에서는 AI 강화 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 : '{}'
);
}
단일 위치에서 전체 주문을 처리할 수 없는 경우, 2단계 라우팅 전략을 구현하세요. 먼저 단일 위치를 찾으려고 시도합니다. 실패하면 AI를 사용하여 배송 횟수를 최소화하면서 총 배송비를 최소화하는 최적의 분할을 결정합니다(고객은 더 적은 수의 패키지를 선호합니다).
Flow에서 모두 연결하기
이러한 AI 기반 액션은 앱에서 Flow 액션으로 등록됩니다. 판매자는 Flow 편집기에서 시각적으로 이들을 연결합니다:
- 트리거: 주문 생성
- 조건: 주문 금액 > $50
- 액션: AI 사기 검사 (여러분의 확장 기능)
- 조건: 사기 점수 < 0.3
- 액션: AI 주문 라우팅 (여러분의 확장 기능)
- 액션: AI 구매 후 이메일 시퀀스 (여러분의 확장 기능)
- 액션: 고객 세그먼트 태그 업데이트 (여러분의 확장 기능)
각 액션은 독립적으로 작동하며, Flow의 컨텍스트에서 데이터를 수신하고, 후속 액션이 사용할 수 있는 결과를 반환합니다.
이제 네 가지 핵심 Agentic 패턴을 모두 다루었습니다. 다음 모듈 앱 구축에서는 이러한 패턴을 적절한 아키텍처, 인증, 배포를 갖춘 프로덕션 Shopify 앱으로 패키징하는 방법을 배웁니다.