Skip to main content

AI Messages

PrismGamificationIntelligence uses Apple Intelligence (FoundationModels) to generate personalized, context-aware messages — celebrations, motivation, streak alerts, and recommendations. All processing happens on-device.

Setup

Default (Apple Intelligence)
let intelligence = PrismGamificationIntelligence()
Custom Configuration
let intelligence = PrismGamificationIntelligence(
    configuration: PrismAppleIntelligenceConfiguration(/* ... */)
)
Custom Provider
let intelligence = PrismGamificationIntelligence(
    provider: myCustomProvider // any PrismLanguageIntelligenceProvider
)

Availability Check

Check Availability
let available = await intelligence.isAvailable()
Returns true when the underlying language model is ready on the device.

Message Kinds

Seven message categories for different gamification moments:
KindDescription
.challengeCompletedCelebration for completing a challenge
.challengeProgressMotivational nudge for in-progress challenges
.streakMotivationDaily streak encouragement
.streakAtRiskUrgent alert when streak might break
.badgeUnlockedBadge unlock celebration
.leaderboardUpdateLeaderboard position commentary
.challengeRecommendationPersonalized next-challenge suggestion

Generating Messages

Single Message

Generate
let message = try await intelligence.generateMessage(
    kind: .challengeCompleted,
    context: PrismGamificationContext(
        entityID: "tenWorkouts",
        challengeTitle: "Ten Workouts",
        points: 50,
        totalPoints: 120
    )
)

print(message.content)
// "You crushed 10 workouts and earned 50 points! 💪"

Batch Generation

Batch
let messages = await intelligence.generateMessages([
    (kind: .challengeCompleted, context: completionCtx),
    (kind: .streakMotivation, context: streakCtx),
    (kind: .badgeUnlocked, context: badgeCtx)
])
// Failed generations are silently skipped

With Automatic Fallback

Auto-Fallback
let message = await intelligence.messageWithFallback(
    kind: .streakMotivation,
    context: PrismGamificationContext(
        entityID: "daily",
        currentStreak: 14,
        longestStreak: 21
    )
)
// AI-generated if available, static fallback otherwise

Static Fallback Only

Fallback
let message = await intelligence.fallbackMessage(
    kind: .badgeUnlocked,
    context: PrismGamificationContext(
        entityID: "fitnessFreak",
        badgeTitle: "Fitness Freak",
        badgeTier: "silver"
    )
)
// "Silver badge "Fitness Freak" unlocked!"

PrismGamificationContext

Provide context for richer, more relevant AI messages:
PropertyTypeUsed By
entityIDStringAll kinds
challengeTitleString?Challenge kinds
currentValueInt?.challengeProgress
goalValueInt?.challengeProgress
pointsInt?.challengeCompleted
totalPointsInt?.challengeCompleted, .challengeRecommendation
currentStreakInt?Streak kinds
longestStreakInt?.streakMotivation
badgeTitleString?.badgeUnlocked
badgeTierString?.badgeUnlocked
rankInt?.leaderboardUpdate
previousRankInt?.leaderboardUpdate
scoreInt?.leaderboardUpdate
completedChallengesInt?.challengeRecommendation
activeCategories[String]?.challengeRecommendation

PrismGamificationMessage

PropertyTypeDescription
idStringUnique message identifier
kindPrismGamificationMessageKindMessage category
contentStringGenerated text
entityIDStringRelated entity
generatedAtDateWhen generated

Prompt Builder

PrismGamificationPromptBuilder builds context-aware prompts for each message kind. The system instructions configure the AI as a gamification coach:
  • 1–2 sentences max
  • Enthusiastic but not excessive
  • Max 1 emoji
  • References specific achievements
  • Under 100 characters when possible
Custom Prompts
let builder = PrismGamificationPromptBuilder()
let prompt = builder.prompt(
    for: .challengeCompleted,
    context: myContext
)
let system = builder.systemInstructions

Fallback System

PrismGamificationFallbacks provides static messages for every kind — no AI required:
Fallbacks
let text = PrismGamificationFallbacks.message(
    for: .streakAtRisk,
    context: PrismGamificationContext(
        entityID: "daily",
        currentStreak: 7
    )
)
// "Your 7-day streak is at risk! Log activity today."
Fallbacks use context data to build meaningful messages without AI processing.
Use messageWithFallback in production — it tries AI first and falls back gracefully. Reserve generateMessage for when you want to handle errors yourself.

Integration Pattern

Event-Driven Messages
for await event in manager.events {
    switch event {
    case .completed(let id, let points):
        let msg = await intelligence.messageWithFallback(
            kind: .challengeCompleted,
            context: PrismGamificationContext(
                entityID: id,
                challengeTitle: id,
                points: points
            )
        )
        showToast(msg.content)

    case .streakExtended(let id, let count):
        let msg = await intelligence.messageWithFallback(
            kind: .streakMotivation,
            context: PrismGamificationContext(
                entityID: id,
                currentStreak: count
            )
        )
        showToast(msg.content)

    case .badgeUnlocked(let id, let tier):
        let msg = await intelligence.messageWithFallback(
            kind: .badgeUnlocked,
            context: PrismGamificationContext(
                entityID: id,
                badgeTitle: id,
                badgeTier: tier
            )
        )
        showCelebration(msg.content)

    default: break
    }
}