Patterns
AI Integration Patterns
Patterns for integrating AI into Business-as-Code applications
Patterns for embedding AI intelligence throughout your autonomous business.
AI Operations
The SDK provides four core AI operations:
// @errors: 7006
// @strict: true
import { ai } from 'sdk.do'
// 1. Generate content - TypeScript infers return type
const content = await ai.generate('blog-post', {
topic: 'AI in Business',
length: 1500,
})
// ^?
// 2. Make decisions - Return type includes decision + reasoning
const decision = await ai.decide('pricing-strategy', {
product: { cost: 50, market: 'premium' },
competition: { avgPrice: 100 },
})
// ^?
// 3. Recommend items - Generic return type based on 'type' parameter
const items = await ai.recommend({
type: $.Product,
for: customer,
context: { preferences: ['tech', 'gadgets'] },
})
// ^?
// 4. Analyze data - Analysis result is strongly typed
const insights = await ai.analyze('customer-churn', {
customer,
metrics: { engagement: 0.3, lastActive: '2024-01-15' },
})
// ^?Content Generation Pattern
AI generates semantic content:
// Product descriptions
const description = await ai.generate('product-description', {
product: {
name: 'Wireless Headphones',
features: ['noise-cancelling', 'bluetooth', '40-hour battery'],
category: 'Electronics',
},
tone: 'professional',
length: 'medium',
includes: ['features', 'benefits', 'use-cases'],
})
// Marketing copy
const campaign = await ai.generate('marketing-campaign', {
product,
audience: 'tech-enthusiasts',
channels: ['email', 'social'],
goal: 'product-launch',
})
// Email content
const email = await ai.generate('email-content', {
type: 'welcome',
customer,
tone: 'friendly',
include: ['getting-started', 'resources', 'support'],
})
// Blog posts
const blogPost = await ai.generate('blog-post', {
topic: 'How to Choose Wireless Headphones',
keywords: ['headphones', 'audio', 'wireless'],
length: 1500,
style: 'educational',
})Use when:
- Creating consistent branded content
- Personalizing at scale
- Generating variations for A/B testing
- Producing content in multiple languages
Decision-Making Pattern
AI makes business decisions:
// @errors: 7006
// @strict: true
import { ai, $, db, send } from 'sdk.do'
declare const product: any
declare const findCompetitors: (p: any) => Promise<any[]>
declare const analyzeDemand: (p: any) => Promise<any>
declare const analyzeSeasonality: (p: any) => Promise<any>
declare const estimateStockoutCost: (p: any) => number
declare const ticket: any
// Pricing decisions - AI returns structured decision with reasoning
const pricing = await ai.decide('product-pricing', {
product,
costs: {
manufacturing: 25,
shipping: 5,
overhead: 10,
},
market: {
competitors: await findCompetitors(product),
demand: await analyzeDemand(product),
},
strategy: 'balanced', // 'aggressive' | 'conservative' | 'balanced'
targetMargin: 0.4,
})
// ^?
// Decision object has typed properties
console.log({
recommendedPrice: pricing.recommendedPrice,
confidence: pricing.confidence,
reasoning: pricing.explanation,
projectedSales: pricing.projectedImpact,
})
// Inventory decisions - Boolean and quantity inference
const inventory = await ai.decide('inventory-reorder', {
product,
currentStock: product.inventory,
reorderPoint: product.reorderPoint,
salesHistory: await db.analyze('sales-velocity', {
product,
timeRange: '90d',
}),
seasonality: await analyzeSeasonality(product),
leadTime: product.supplier.leadTime,
costOfStockout: estimateStockoutCost(product),
})
// ^?
// TypeScript knows inventory decision shape
if (inventory.shouldReorder) {
// ^?
await $.PurchaseOrder.create({
product,
quantity: inventory.recommendedQuantity,
urgency: inventory.urgency,
})
}
// Routing decisions - selectedAgent is typed
const route = await ai.decide('support-ticket-routing', {
ticket,
agents: await db.list($.Person, {
where: { role: 'support-agent', status: 'available' },
}),
factors: ['expertise', 'workload', 'customer-history'],
})
// ^?
await send($.Ticket.assign, {
ticket,
agent: route.selectedAgent,
// ^?
reason: route.reasoning,
})Use when:
- Multiple viable options exist
- Decision involves trade-offs
- Context changes frequently
- Human rules are complex/incomplete
Recommendation Pattern
AI recommends items for users:
// Product recommendations
const recommendations = await ai.recommend({
type: $.Product,
for: customer,
strategy: 'personalized',
context: {
recentViews: await db.related(customer, $.viewed, $.Product),
purchases: await db.related(customer, $.purchased, $.Product),
preferences: customer.interests,
},
limit: 5,
})
// Content recommendations
const articles = await ai.recommend({
type: $.Article,
for: customer,
strategy: 'related-content',
basedOn: currentArticle,
limit: 3,
})
// Next best action
const nextAction = await ai.recommend({
type: $.Action,
for: user,
strategy: 'next-best-action',
context: {
completedActions: await db.related(user, $.completed, $.Action),
goals: user.goals,
timeAvailable: '30min',
},
limit: 1,
})
// Feature recommendations
const features = await ai.recommend({
type: $.Feature,
for: customer,
strategy: 'feature-adoption',
context: {
currentPlan: customer.subscription.plan,
usage: await analyzeUsage(customer),
goals: customer.goals,
},
limit: 3,
})Use when:
- Personalization improves outcomes
- Surfacing relevant content/products
- Guiding user journey
- Increasing engagement/conversion
Analysis Pattern
AI analyzes data for insights:
// Customer analysis
const customerInsights = await ai.analyze('customer-profile', {
customer,
history: {
orders: await db.related(customer, $.placed, $.Order),
support: await db.related(customer, $.submitted, $.SupportTicket),
engagement: await db.metrics($.Event, { customer }),
},
})
console.log({
segment: customerInsights.segment,
lifetimeValue: customerInsights.ltv,
churnRisk: customerInsights.churnRisk,
preferences: customerInsights.preferences,
nextBestOffer: customerInsights.recommendation,
})
// Sentiment analysis
const sentiment = await ai.analyze('sentiment', {
text: review.content,
context: {
product: review.product,
rating: review.rating,
},
})
// Anomaly detection
const anomaly = await ai.analyze('anomaly-detection', {
metric: 'order-volume',
timeseries: await db.timeseries($.Order, {
groupBy: 'day',
last: '30d',
}),
threshold: 2, // Standard deviations
})
if (anomaly.detected) {
await send($.Alert.send, {
type: 'anomaly-detected',
metric: 'order-volume',
details: anomaly.details,
})
}
// Trend analysis
const trends = await ai.analyze('market-trends', {
category: product.category,
competitors: await findCompetitors(product),
timeseries: await getMarketData(product.category),
})Use when:
- Extracting insights from data
- Detecting patterns/anomalies
- Understanding sentiment/intent
- Forecasting trends
Hybrid Decision Pattern
Combine AI with business rules:
// AI provides recommendations, rules apply constraints
async function determineShipping(order: Order) {
// Get AI recommendation
const aiDecision = await ai.decide('shipping-method', {
order,
destination: order.shippingAddress,
urgency: order.requestedDelivery,
})
// Apply business rules
let shippingMethod = aiDecision.recommended
// Rule 1: Premium customers always get express
if (order.customer.membershipLevel === 'premium') {
shippingMethod = 'express'
}
// Rule 2: International orders require customs
if (isInternational(order.shippingAddress)) {
shippingMethod = 'international-' + shippingMethod
}
// Rule 3: Heavy items require freight
const weight = calculateWeight(order.items)
if (weight > 50) {
shippingMethod = 'freight'
}
return {
method: shippingMethod,
aiRecommendation: aiDecision.recommended,
rulesApplied: getRulesApplied(),
cost: calculateShippingCost(shippingMethod),
}
}Progressive Enhancement Pattern
Start simple, add AI gradually:
// Version 1: Rule-based
function determineDiscount(customer: Person): number {
if (customer.orderCount > 10) return 0.10
if (customer.lifetimeValue > 1000) return 0.15
return 0
}
// Version 2: AI-assisted (AI suggests, human approves)
async function determineDi scountAI(customer: Person): Promise<number> {
const suggestion = await ai.decide('customer-discount', {
customer,
history: await getCustomerHistory(customer)
})
if (suggestion.confidence > 0.9) {
return suggestion.discount
} else {
// Low confidence, use rule-based fallback
return determineDiscount(customer)
}
}
// Version 3: Fully autonomous (within constraints)
async function determineDiscountAutonomous(customer: Person): Promise<number> {
const decision = await ai.decide('customer-discount', {
customer,
history: await getCustomerHistory(customer),
constraints: {
min: 0,
max: 0.25 // Never more than 25%
}
})
return decision.discount
}A/B Testing Pattern
AI runs and analyzes experiments:
// AI creates variants
const variants = await ai.generate('ab-test-variants', {
control: {
headline: 'Welcome to Our Store',
cta: 'Shop Now',
},
variations: 3,
optimize: 'conversion',
})
// Assign users to variants
on($.Customer.visits, async (visit) => {
const assignment = await ai.decide('ab-test-assignment', {
test: 'homepage-v2',
user: visit.customer,
variants: variants,
})
await send($.UI.render, {
customer: visit.customer,
variant: assignment.variant,
trackingId: assignment.trackingId,
})
})
// AI analyzes results
const analysis = await ai.analyze('ab-test-results', {
test: 'homepage-v2',
metrics: await db.metrics($.Conversion, {
test: 'homepage-v2',
timeRange: '7d',
}),
})
if (analysis.significant && analysis.winner) {
// AI found a winner
await send($.ABTest.conclude, {
test: 'homepage-v2',
winner: analysis.winner,
improvement: analysis.lift,
})
}Feedback Loop Pattern
AI learns from outcomes:
// Make prediction
const prediction = await ai.decide('churn-prediction', {
customer,
features: await extractFeatures(customer),
})
// Log prediction
await db.create($.Prediction, {
type: 'churn',
customer: customer.$id,
predicted: prediction.willChurn,
confidence: prediction.confidence,
timestamp: new Date(),
})
// Observe actual outcome
on($.Subscription.cancelled, async (sub) => {
const predictions = await db.list($.Prediction, {
where: {
type: 'churn',
customer: sub.customer.$id,
timestamp: { $gte: subDays(new Date(), 30) },
},
})
// Update with actual outcome
for (const pred of predictions) {
await db.update($.Prediction, pred.$id, {
actual: true,
correct: pred.predicted === true,
})
// Send feedback to AI
await ai.learn({
predictionId: pred.$id,
predicted: pred.predicted,
actual: true,
features: pred.features,
})
}
})
// Monitor model performance
const performance = await db.aggregate($.Prediction, {
where: {
type: 'churn',
timestamp: { $gte: subDays(new Date(), 30) },
},
aggregations: {
accuracy: {
$avg: { $cond: ['$correct', 1, 0] },
},
total: { $count: '*' },
},
})
console.log(`Churn prediction accuracy: ${performance.accuracy}`)Ensemble Pattern
Combine multiple AI approaches:
// Get predictions from multiple models
async function ensembleDecision(context: any) {
const [gptDecision, claudeDecision, localModelDecision] = await Promise.all([
ai.decide('pricing', context, { model: 'gpt-5' }),
ai.decide('pricing', context, { model: 'claude-sonnet-4.5' }),
ai.decide('pricing', context, { model: 'local-pricing-model' }),
])
// Weighted average based on confidence
const decisions = [gptDecision, claudeDecision, localModelDecision]
const totalConfidence = decisions.reduce((sum, d) => sum + d.confidence, 0)
const weightedPrice = decisions.reduce((sum, d) => {
return sum + (d.price * d.confidence) / totalConfidence
}, 0)
return {
price: weightedPrice,
confidence: Math.max(...decisions.map((d) => d.confidence)),
models: decisions.map((d) => ({
model: d.model,
price: d.price,
confidence: d.confidence,
})),
}
}Explainable AI Pattern
Make AI decisions transparent:
// AI decision with explanation
const decision = await ai.decide('loan-approval', {
applicant,
requestedAmount: 50000,
explainability: 'high',
})
console.log({
approved: decision.approved,
confidence: decision.confidence,
// Why this decision?
reasoning: decision.explanation,
// What factors mattered?
factors: decision.factors.map((f) => ({
name: f.name,
impact: f.impact,
value: f.value,
})),
// What would change the decision?
counterfactuals: decision.counterfactuals,
})
// Store explanation for audit
await db.create($.AIDecision, {
type: 'loan-approval',
subject: applicant.$id,
decision: decision.approved,
explanation: decision.explanation,
factors: decision.factors,
model: decision.model,
timestamp: new Date(),
})Human-in-the-Loop Pattern
Escalate uncertain decisions:
// AI decides, but escalates when unsure
async function makeDecisionWithEscalation(context: any) {
const decision = await ai.decide('fraud-detection', context)
if (decision.confidence > 0.95) {
// High confidence, act autonomously
return decision.action
} else if (decision.confidence > 0.7) {
// Medium confidence, log and act
await db.create($.ReviewLog, {
decision,
autoApproved: true,
reviewBy: addHours(new Date(), 24),
})
return decision.action
} else {
// Low confidence, require human review
await send($.Review.request, {
type: 'fraud-detection',
context,
aiSuggestion: decision,
urgency: decision.riskLevel,
})
// Wait for human decision
const humanDecision = await waitForReview(context.$id)
return humanDecision.action
}
}Best Practices
1. Provide Rich Context
// Good: Complete semantic context
const decision = await ai.decide('pricing', {
product: {
$type: 'Product',
name: 'Wireless Mouse',
category: 'Electronics',
brand: 'TechCo',
features: ['wireless', 'ergonomic'],
costs: { manufacturing: 15, shipping: 3 }
},
market: {
competitors: [...], // Full competitor products
demand: {...}, // Demand metrics
trends: {...} // Market trends
},
business: {
targetMargin: 0.40,
inventory: 150,
strategy: 'balanced'
}
})
// Avoid: Minimal context
const decision = await ai.decide('pricing', {
product: 'mouse',
cost: 18
})2. Set Confidence Thresholds
const CONFIDENCE_THRESHOLDS = {
auto: 0.95, // Act autonomously
review: 0.7, // Log and review later
escalate: 0, // Require human decision
}
const decision = await ai.decide(type, context)
if (decision.confidence >= CONFIDENCE_THRESHOLDS.auto) {
await executeDecision(decision)
} else if (decision.confidence >= CONFIDENCE_THRESHOLDS.review) {
await logForReview(decision)
await executeDecision(decision)
} else {
await escalateToHuman(decision)
}3. Monitor Performance
// Track AI decision outcomes
on($.AIDecision.made, async (decision) => {
await db.create($.DecisionLog, {
type: decision.type,
input: decision.context,
output: decision.result,
confidence: decision.confidence,
timestamp: new Date(),
})
})
// Measure accuracy
setInterval(async () => {
const performance = await db.analyze('ai-performance', {
decisionType: 'pricing',
timeRange: '30d',
metrics: ['accuracy', 'impact', 'confidence-calibration'],
})
if (performance.accuracy < 0.8) {
await send($.Alert.send, {
type: 'ai-performance-degraded',
details: performance,
})
}
}, 86400000) // Daily4. Version Your Prompts
// Version prompts for reproducibility
const PROMPTS = {
'pricing-v1': 'Analyze this product and recommend a price...',
'pricing-v2': 'Consider market dynamics and recommend...',
'pricing-v3': 'Optimize for customer lifetime value...',
}
async function decide(type: string, context: any, version = 'latest') {
const prompt = version === 'latest' ? PROMPTS[`${type}-v${getLatestVersion(type)}`] : PROMPTS[`${type}-${version}`]
return await ai.decide(type, context, { prompt, version })
}Summary
AI integration patterns enable:
- Content Generation - Automated, personalized content
- Decision-Making - Intelligent business decisions
- Recommendations - Personalized suggestions
- Analysis - Data insights and predictions
- Hybrid Approach - AI + business rules
- Feedback Loops - Continuous improvement
- Explainability - Transparent decisions
- HITL - Human oversight when needed
Start with simple AI integrations and gradually increase autonomy as confidence grows.
Next: Use Cases →