🍽️

Appleの「Foundation Models Framework」で食事と運動のアドバイスをする

に公開

はじめに

以前から、摂取カロリーと消費カロリーやPFCバランスを見るためのiOSアプリを個人で開発していました。iOS 26でApple Intelligenceのモデルをサードパーティのアプリでも使うことができるようになったので、それを使った機能を作ってみようと思い立ちました。
https://github.com/Shakshi3104/Calories

この記事では、Foundation Models Frameworkを用いて、ヘルスケアに記録されている情報から食事と運動のアドバイスをする機能を作ってみたので紹介します。

Foundation Models Frameworkとは

Foundation Models Frameworkは、Apple Intelligenceで使われているAppleのオンデバイスLLMをアプリでも使うためのフレームワークです。
https://developer.apple.com/documentation/FoundationModels

「便利だな」と思った特徴として、@Generableマクロがあります。これはモデルの出力をstructで定義できて、アプリ内で使いやすい形でモデルから出力を得ることができます。

@Generable(description: "Basic profile information about a cat")
struct CatProfile {
    // A guide isn't necessary for basic fields.
    var name: String


    @Guide(description: "The age of the cat", .range(0...20))
    var age: Int


    @Guide(description: "A one sentence profile about the cat's personality")
    var profile: String
}

https://developer.apple.com/documentation/foundationmodels/generating-swift-data-structures-with-guided-generation

アドバイス機能を実装

出力の定義

@Generableを使って、モデルの出力を定義します。今回は、以下のように全体的なアドバイスと食事・運動のそれぞれのアドバイスの、3つのテキストを出力させます。

import FoundationModels

@Generable
struct DailyAdvice {
    /// Overall comment
    var generalComment: String
    /// Advice about dietary
    var dietarySuggestion: String
    /// Advice about exercise
    var exerciseSuggestion: String
}

モデルの出力部分

モデルに出力させる部分だけ、ピックアップして紹介します。
LanguageModelSession(instructions: )で、モデルに役割を伝えるプロンプトを渡しています。
プロンプトには、1日の目標三大栄養素の数値とその日の現段階の数値を渡して、アドバイスを生成させています。

// 役割を伝えるプロンプト (いわゆるシステムプロンプト)
let instructions = """
あなたは親切で知識豊富なフィットネス&栄養コーチです。
ユーザーの目標と現在の状況に基づき、目標達成のための食事と運動に関するアドバイスを生成してください。
提案は具体的で、ポジティブな言葉遣いを心がけてください。
"""

let session = LanguageModelSession(instructions: instructions)

// プロンプト
let prompt = """
以下のユーザー状況を分析し、アドバイスを生成してください。

# ユーザーの目標
- 1日の目標炭水化物: \(basicNutritionGoal.carbohydrates) g
- 1日の目標タンパク質: \(basicNutritionGoal.protein) g
- 1日の目標脂質: \(basicNutritionGoal.fatTotal) g

# 現在の状況
- 現在の炭水化物: \(currentNutrition.carbohydrates) g
- 現在のタンパク質: \(currentNutrition.protein) g
- 現在の脂質: \(currentNutrition.fatTotal) g
"""

do {
    // モデルの実行
    let generatedAdvice = try await session.respond(to: prompt, generating: DailyAdvice.self).content
    self.advice = generatedAdvice
} catch {
    print("Can't generate advice: \(error)")
}
全体のコード

今回は、SwiftUIで使うためにObservableObjectで実装しました。ViewModelの全体は、以下のような感じです。

import FoundationModels

@MainActor
class AdviceViewModel: ObservableObject {
    @Published var advice: DailyAdvice?
    @Published var isLoading: Bool = true
    
    func isFoundationModelsAvailable() -> Bool {
        switch SystemLanguageModel.default.availability {
        case .available:
            print("Foundation Models are available.")
        case .unavailable(.deviceNotEligible):
            print("Foundation Models are not available on this device.")
        case .unavailable(.appleIntelligenceNotEnabled):
            print("Foundation Models are not available: Apple Intelligence is not enabled.")
        case .unavailable(.modelNotReady):
            print("Foundation Models are not available: Model is not ready.")
        @unknown default:
            print("Foundation Models are not available. (Unknown case)")
        }
        
        return SystemLanguageModel.default.isAvailable
    }
    
    func generateAdvice(currentNutrition: BasicNutrition, basicNutritionGoal: BasicNutritionGoal) async {
        isLoading = true
        defer {
            print("Generated advice.")
            isLoading = false
        }
        
        let instructions = """
        あなたは親切で知識豊富なフィットネス&栄養コーチです。
        ユーザーの目標と現在の状況に基づき、目標達成のための食事と運動に関するアドバイスを生成してください。
        提案は具体的で、ポジティブな言葉遣いを心がけてください。
        """
        
        let session = LanguageModelSession(instructions: instructions)
        
        let prompt = """
        以下のユーザー状況を分析し、アドバイスを生成してください。

        # ユーザーの目標
        - 1日の目標炭水化物: \(basicNutritionGoal.carbohydrates) g
        - 1日の目標タンパク質: \(basicNutritionGoal.protein) g
        - 1日の目標脂質: \(basicNutritionGoal.fatTotal) g
        
        # 現在の状況
        - 現在の炭水化物: \(currentNutrition.carbohydrates) g
        - 現在のタンパク質: \(currentNutrition.protein) g
        - 現在の脂質: \(currentNutrition.fatTotal) g
        """
        
        do {
            print("Generating advice...")
            // Use '.respond(to:generating:)' method for LanguageModelSession.
            let generatedAdvice = try await session.respond(to: prompt, generating: DailyAdvice.self).content
            self.advice = generatedAdvice
            print("Advice: \(generatedAdvice)")
        } catch {
            print("Can't generate advice: \(error)")
        }
    }
}

UIの実装

モデルの出力が実装できたので、SwiftUIでUIも実装します。先ほど実装した関数をTask内で呼び出しているので、アドバイスが表示される画面が表示されたら生成が始まるようになっています。生成には少し時間がかかるので、待ち時間にはアニメーションを表示するようにしました。

全体のコード
/// A view with animations to show while waiting for an AI response.
struct AIThinkingView: View {
    private let phrases = ["Analyzing data...", "Crafting advice...", "Finding suggestions..."]
    @State private var currentPhrase: String
    @State private var isAnimating = false

    init() {
        _currentPhrase = State(initialValue: phrases.first ?? "Thinking...")
    }

    var body: some View {
        VStack(spacing: 20) {
            Image(systemName: "sparkles")
                .font(.system(size: 50))
                .foregroundStyle(.tint)
                .scaleEffect(isAnimating ? 1.2 : 1.0)
                .rotationEffect(.degrees(isAnimating ? 10 : -5))
                .animation(
                    .easeInOut(duration: 1.5).repeatForever(autoreverses: true),
                    value: isAnimating
                )

            Text(currentPhrase)
                .font(.headline)
                .foregroundColor(.secondary)
                .transition(.opacity.animation(.easeInOut))
        }
        .task {
            isAnimating = true
            
            // Cycle through text every 2 seconds
            var index = 0
            while !Task.isCancelled {
                withAnimation {
                    currentPhrase = phrases[index]
                }
                index = (index + 1) % phrases.count
                try? await Task.sleep(for: .seconds(2))
            }
        }
    }
}


@available(iOS 26.0, *)
struct AdviceView: View {
    @StateObject var adviceViewModel: AdviceViewModel
    var currentNutrition: BasicNutrition
    var basicNutritionGoal: BasicNutritionGoal
    
    var body: some View {
        List {
            if adviceViewModel.isLoading {
                HStack {
                    Spacer()
                    AIThinkingView()
                    Spacer()
                }
                .listRowBackground(Color.clear)
            } else {
                Section {
                    VStack {
                        HStack(spacing: 10) {
                            HealthValueView(name: "Protein", value: currentNutrition.protein, unit: "g", color: .proteinPink)
                            
                            Divider()
                            
                            HealthValueView(name: "Fat", value: currentNutrition.fatTotal, unit: "g", color: .fatSkyBlue)
                            
                            Divider()
                            
                            HealthValueView(name: "Carbohydrates", value: currentNutrition.carbohydrates, unit: "g", color: .carbohydratesBlue)
                        }
                    }
                }
                if let advice = adviceViewModel.advice {
                    Section {
                        Text(advice.generalComment)
                    }
                    
                    Section("Dietary") {
                        Text(advice.dietarySuggestion)
                    }
                    
                    Section("Exercise") {
                        Text(advice.exerciseSuggestion)
                    }
                } else {
                    Text("Unable to generate advice. Please try again later.")
                }
            }
        }
        .task {
            await adviceViewModel.generateAdvice(currentNutrition: currentNutrition, basicNutritionGoal: basicNutritionGoal)
        }
    }
}

まとめ

今回は、Foundation Models Frameworkを使って食事と運動のアドバイスをする機能を実装してみました。簡単にオンデバイスLLMを使った機能を取り入れることができるので、とても良いなと思います。
シンプルなプロンプトで試してみたのでプロンプトの工夫や、カロリーや歩数などの入力させるデータを増やして、より実用的なアドバイスを返してくるようにしてみたいです!

参考

https://zenn.dev/lancers/articles/6be34c9ba461fc
https://zenn.dev/5enxia/articles/2061169fff00cd
https://zenn.dev/azookey/articles/153b1bf4da1119

Discussion