Explore practical applications of the Persona SDK across various domains. From predicting click-through rates to simulating voting behavior, these examples demonstrate the power of AI-driven persona generation.
CTR Prediction for Marketing
Model audience segments and predict click-through rates for marketing campaigns:
ctr-prediction.ts
1import { PersonaGroup, PersonaBuilder } from '@jamesaphoenix/persona-sdk';2import { z } from 'zod';3
4// Create target audience for a fitness app campaign5const audience = new PersonaGroup('Fitness App Target Audience');6
7// Generate diverse audience with correlations8await audience.generateWithCorrelations(1000, {9 attributes: {10 age: new NormalDistribution(32, 8),11 income: new NormalDistribution(65000, 20000),12 fitnessLevel: new CategoricalDistribution([13 { value: 'beginner', probability: 0.3 },14 { value: 'intermediate', probability: 0.5 },15 { value: 'advanced', probability: 0.2 }16 ]),17 deviceType: new CategoricalDistribution([18 { value: 'iOS', probability: 0.45 },19 { value: 'Android', probability: 0.55 }20 ])21 },22 correlations: [23 { attribute1: 'age', attribute2: 'income', correlation: 0.4 },24 { attribute1: 'fitnessLevel', attribute2: 'income', correlation: 0.3 }25 ]26});27
28// Define CTR prediction schema29const CTRPredictionSchema = z.object({30 overallCTR: z.number().describe('Expected CTR as percentage'),31 segmentCTRs: z.array(z.object({32 segment: z.string(),33 criteria: z.string(),34 expectedCTR: z.number(),35 audienceSize: z.number()36 })),37 topPerformingAd: z.object({38 headline: z.string(),39 description: z.string(),40 targetSegment: z.string()41 }),42 recommendations: z.array(z.string())43});44
45// Generate CTR predictions46const predictions = await audience.generateStructuredOutput(47 CTRPredictionSchema,48 `Analyze this audience for a fitness app marketing campaign. 49 The app costs $9.99/month and focuses on personalized workout plans.50 Predict CTR for different segments and recommend ad strategies.`51);52
53console.log('Overall Expected CTR:', predictions.overallCTR + '%');54console.log('Top Segment:', predictions.segmentCTRs[0]);55console.log('Best Ad:', predictions.topPerformingAd);56
57// Test specific ad variations58const adVariations = [59 'Get Fit in 15 Minutes a Day',60 'Personalized Workouts for Your Goals',61 'Join 1M+ Users Getting Stronger'62];63
64for (const headline of adVariations) {65 const response = await audience.testCampaign(headline, {66 budget: 10000,67 duration: '7 days',68 targeting: { minAge: 25, maxAge: 45 }69 });70 71 console.log(`"${headline}": ${response.expectedCTR}% CTR`);72}
Engagement Analysis for Content
Predict and analyze engagement for different content strategies:
engagement-analysis.ts
1// Create audience for a tech blog2const techAudience = new PersonaGroup('Tech Blog Readers');3
4// Generate realistic tech audience5await techAudience.generateFromDistributions(500, {6 age: new NormalDistribution(28, 6),7 occupation: new CategoricalDistribution([8 { value: 'Software Engineer', probability: 0.4 },9 { value: 'Product Manager', probability: 0.2 },10 { value: 'Designer', probability: 0.15 },11 { value: 'Student', probability: 0.15 },12 { value: 'Other Tech', probability: 0.1 }13 ]),14 interests: new MultiCategoricalDistribution([15 { value: ['AI', 'Machine Learning'], probability: 0.6 },16 { value: ['Web Development'], probability: 0.5 },17 { value: ['Cloud Computing'], probability: 0.4 },18 { value: ['Blockchain'], probability: 0.3 },19 { value: ['Mobile Dev'], probability: 0.35 }20 ])21});22
23// Test different content hooks24const contentHooks = [25 {26 title: '10 AI Tools That Will 10x Your Productivity',27 category: 'AI',28 style: 'listicle'29 },30 {31 title: 'Why Rust is the Future of Systems Programming',32 category: 'Programming Languages',33 style: 'opinion'34 },35 {36 title: 'Building a $1M SaaS: My Journey',37 category: 'Entrepreneurship',38 style: 'case study'39 }40];41
42const EngagementSchema = z.object({43 expectedViews: z.number(),44 expectedComments: z.number(),45 expectedShares: z.number(),46 engagementRate: z.number(),47 audienceSegments: z.array(z.object({48 segment: z.string(),49 interest: z.number().min(0).max(10),50 likelihood: z.number().min(0).max(1)51 })),52 sentimentBreakdown: z.object({53 positive: z.number(),54 neutral: z.number(),55 negative: z.number()56 })57});58
59for (const content of contentHooks) {60 const engagement = await techAudience.generateStructuredOutput(61 EngagementSchema,62 `Predict engagement metrics for this blog post:63 Title: ${content.title}64 Category: ${content.category}65 Style: ${content.style}66 67 Analyze expected views, comments, shares, and sentiment.`68 );69 70 console.log(`\n"${content.title}":`);71 console.log(`Expected Engagement Rate: ${engagement.engagementRate}%`);72 console.log(`Views: ${engagement.expectedViews}, Comments: ${engagement.expectedComments}`);73 console.log(`Top Interested Segment: ${engagement.audienceSegments[0].segment}`);74}
Voting & Polling Systems
Simulate voting behavior and predict election outcomes:
voting-simulation.ts
1// Create a diverse voter population2const voterPopulation = new PersonaGroup('City Voters');3
4// Generate voters with realistic demographics5await voterPopulation.generateWithCorrelations(10000, {6 attributes: {7 age: new NormalDistribution(45, 15),8 income: new LogNormalDistribution(50000, 30000),9 education: new CategoricalDistribution([10 { value: 'High School', probability: 0.3 },11 { value: 'Bachelor', probability: 0.4 },12 { value: 'Graduate', probability: 0.3 }13 ]),14 politicalLeaning: new NormalDistribution(0, 1), // -2 (left) to +2 (right)15 district: new CategoricalDistribution([16 { value: 'Downtown', probability: 0.25 },17 { value: 'Suburbs', probability: 0.45 },18 { value: 'Rural', probability: 0.3 }19 ])20 },21 correlations: [22 { attribute1: 'age', attribute2: 'politicalLeaning', correlation: 0.3 },23 { attribute1: 'education', attribute2: 'income', correlation: 0.5 },24 { attribute1: 'district', attribute2: 'politicalLeaning', correlation: 0.4 }25 ]26});27
28// Define voting schema29const VotingResultSchema = z.object({30 results: z.array(z.object({31 candidate: z.string(),32 votePercentage: z.number(),33 voteCount: z.number()34 })),35 turnout: z.number(),36 demographicBreakdown: z.array(z.object({37 demographic: z.string(),38 turnoutRate: z.number(),39 candidatePreferences: z.record(z.number())40 })),41 swingFactors: z.array(z.string()),42 confidence: z.number()43});44
45// Simulate election46const candidates = [47 { name: 'Sarah Johnson', platform: 'Progressive', focus: 'Climate, Healthcare' },48 { name: 'Michael Chen', platform: 'Moderate', focus: 'Economy, Education' },49 { name: 'Robert Smith', platform: 'Conservative', focus: 'Taxes, Security' }50];51
52const electionResults = await voterPopulation.generateStructuredOutput(53 VotingResultSchema,54 `Simulate a mayoral election with these candidates:55 ${candidates.map(c => `${c.name} (${c.platform}): ${c.focus}`).join('\n')}56 57 Consider voter demographics, political leanings, and district preferences.58 Estimate turnout and breakdown by demographics.`59);60
61console.log('Election Results:');62electionResults.results.forEach(r => {63 console.log(`${r.candidate}: ${r.votePercentage}% (${r.voteCount} votes)`);64});65
66console.log(`\nTurnout: ${electionResults.turnout}%`);67console.log('Key Swing Factors:', electionResults.swingFactors);68
69// Run multiple simulations for confidence intervals70const simulations = [];71for (let i = 0; i < 100; i++) {72 const result = await voterPopulation.simulateElection(candidates);73 simulations.push(result);74}75
76// Calculate confidence intervals77const confidenceIntervals = calculateConfidenceIntervals(simulations);78console.log('95% Confidence Intervals:', confidenceIntervals);
Market Research Survey Simulation
Generate statistically valid survey responses for market research:
survey-simulation.ts
1// Create target market for a new product2const targetMarket = new PersonaGroup('Smart Home Device Market');3
4// Generate diverse consumer base5await targetMarket.generateWithCorrelations(2000, {6 attributes: {7 age: new NormalDistribution(38, 12),8 householdIncome: new LogNormalDistribution(75000, 35000),9 techSavviness: new BetaDistribution(3, 2), // 0-1 scale, skewed high10 homeOwnership: new BernoulliDistribution(0.65),11 familySize: new PoissonDistribution(2.5),12 currentSmartDevices: new PoissonDistribution(3)13 },14 correlations: [15 { attribute1: 'age', attribute2: 'homeOwnership', correlation: 0.5 },16 { attribute1: 'householdIncome', attribute2: 'techSavviness', correlation: 0.4 },17 { attribute1: 'techSavviness', attribute2: 'currentSmartDevices', correlation: 0.7 }18 ]19});20
21// Define survey response schema22const SurveyResponseSchema = z.object({23 productInterest: z.object({24 veryInterested: z.number(),25 interested: z.number(),26 neutral: z.number(),27 notInterested: z.number()28 }),29 pricePoints: z.array(z.object({30 price: z.number(),31 willingToPay: z.number(),32 perceivesAsGoodValue: z.number()33 })),34 topFeatures: z.array(z.object({35 feature: z.string(),36 importance: z.number(),37 percentageWhoWant: z.number()38 })),39 purchaseTimeline: z.object({40 immediate: z.number(),41 within3Months: z.number(),42 within6Months: z.number(),43 withinYear: z.number(),44 noPlans: z.number()45 }),46 barriers: z.array(z.object({47 barrier: z.string(),48 percentageAffected: z.number()49 }))50});51
52// Run survey simulation53const surveyResults = await targetMarket.generateStructuredOutput(54 SurveyResponseSchema,55 `Simulate survey responses for a new smart home security system:56 - AI-powered threat detection57 - Mobile app control58 - Professional monitoring option59 - Integration with existing smart home devices60 61 Test price points: $199, $299, $39962 Analyze interest, price sensitivity, desired features, and purchase barriers.`63);64
65console.log('Product Interest:');66console.log(`Very Interested: ${surveyResults.productInterest.veryInterested}%`);67console.log(`Interested: ${surveyResults.productInterest.interested}%`);68
69console.log('\nPrice Sensitivity:');70surveyResults.pricePoints.forEach(pp => {71 console.log(`$${pp.price}: ${pp.willingToPay}% willing to pay`);72});73
74console.log('\nTop Desired Features:');75surveyResults.topFeatures.slice(0, 5).forEach((f, i) => {76 console.log(`${i + 1}. ${f.feature} (importance: ${f.importance}/10)`);77});78
79// Generate individual responses for deeper analysis80const individualResponses = await targetMarket.generateSurveyResponses({81 questions: [82 'How likely are you to purchase this product?',83 'What is your main concern about smart home security?',84 'What would make you choose our product over competitors?'85 ],86 responseFormat: 'detailed',87 sampleSize: 50088});89
90// Analyze correlations in responses91const correlationAnalysis = analyzeResponseCorrelations(individualResponses);92console.log('\nKey Insights:', correlationAnalysis.insights);
🎯 Use Cases
- • A/B Testing Simulation
- • Customer Segmentation
- • Product-Market Fit Analysis
- • Sentiment Prediction
- • User Journey Mapping
- • Conversion Optimization
📊 Benefits
- • Reduce research costs
- • Faster insights generation
- • Test edge cases safely
- • Validate hypotheses
- • Scale analysis instantly
- • Reproducible results
💡 Integration Tips
- • Start Small: Test with 100-500 personas before scaling up
- • Validate Assumptions: Compare results with real data when available
- • Use Correlations: Model realistic relationships between attributes
- • Iterate: Refine your models based on outcomes
- • Document: Keep track of your distribution parameters and assumptions