Communitygithub.com

foundation-models-on-device

Apple FoundationModelsフレームワークを使用したオンデバイスLLM — iOS 26+でのテキスト生成、@Generableによるガイド付き生成、ツール呼び出し、スナップショットストリーミング。iOS 26+でApple FoundationModelsを使用したオンデバイスLLM機能を追加する際に使用します。

foundation-models-on-device とは?

FoundationModels On-Device LLMスキルは、AppleのFoundationModelsフレームワークを活用して、iOS 26+アプリにオンデバイスの言語モデル機能を統合するためのパターンを提供します。このスキルは、テキスト生成、構造化出力(@Generableマクロによる)、カスタムツール呼び出し、スナップショットストリーミングをカバーしており、すべてデバイス上で実行されるため、プライバシーが保護されオフラインでも動作します。開発者は、モデルの利用可能性を事前にチェックし、セッションを作成して応答を取得するという、明確なコアパターンに従います。@Generableを使用すると、Swiftの強力な型安全性を活かして、生の文字列ではなく、構造化されたSwift型を生成できます。また、Toolプロトコルに準拠したカスタムツールを定義することで、モデルがドメイン固有のタスク(レシピ検索など)を実行できるように拡張できます。スナップショットストリーミング機能は、部分的に生成された構造化データをリアルタイムでUIに反映させることを可能にし、SwiftUIとの統合もスムーズです。このスキルは、プライバシー重視のアプリ、オフライン対応が必要なAI機能、および構造化データ抽出に特に適しています。

対応~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/ECC/tree/main/skills/foundation-models-on-device

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

FoundationModels: オンデバイスLLM(iOS 26)

FoundationModelsフレームワークを使用して、Appleのオンデバイス言語モデルをアプリに統合するためのパターン。テキスト生成、@Generableによる構造化出力、カスタムツール呼び出し、スナップショットストリーミングをカバー。すべてデバイス上で動作するため、プライバシーが保護されオフラインでも使用できます。

アクティベートすべき時

  • Apple Intelligenceをオンデバイスで使用したAI搭載機能の構築
  • クラウド依存なしでのテキスト生成または要約
  • 自然言語入力からの構造化データ抽出
  • ドメイン固有のAIアクションのためのカスタムツール呼び出しの実装
  • リアルタイムUI更新のための構造化レスポンスのストリーミング
  • プライバシーを重視したAIが必要な場合(デバイス外にデータが流出しない)

コアパターン — 利用可能性の確認

セッションを作成する前に、必ずモデルの利用可能性を確認します。

struct GenerativeView: View {
    private var model = SystemLanguageModel.default

    var body: some View {
        switch model.availability {
        case .available:
            ContentView()
        case .unavailable(.deviceNotEligible):
            Text("このデバイスはApple Intelligenceに対応していません")
        case .unavailable(.appleIntelligenceNotEnabled):
            Text("設定でApple Intelligenceを有効にしてください")
        case .unavailable(.modelNotReady):
            Text("モデルがダウンロード中または準備ができていません")
        case .unavailable(let other):
            Text("モデルを利用できません: \(other)")
        }
    }
}

コアパターン — 基本セッション

// シングルターン:リクエストごとに新しいセッションを作成
let session = LanguageModelSession()
let response = try await session.respond(to: "パリに行くのに良い月はいつですか?")
print(response.content)

// マルチターン:会話のコンテキストを維持するためにセッションを再利用
let session = LanguageModelSession(instructions: """
    あなたは料理アシスタントです。
    材料に基づいてレシピの提案を提供します。
    提案は簡潔かつ実用的にしてください。
    """)

let first = try await session.respond(to: "鶏肉と米があります")
let followUp = try await session.respond(to: "ベジタリアン向けのオプションはありますか?")

指示(instructions)の重要なポイント:

  • モデルの役割を定義する(「あなたはメンターです」)
  • 何をすべきかを指定する(「カレンダーイベントの抽出を支援する」)
  • スタイルの設定を行う(「できるだけ簡潔に回答する」)
  • 安全対策を追加する(「危険なリクエストには「お手伝いできません」と回答する」)

コアパターン — @Generableを使ったガイド付き生成

生の文字列ではなく、構造化されたSwift型を生成します。

1. Generable型の定義

@Generable(description: "猫の基本プロフィール情報")
struct CatProfile {
    var name: String

    @Guide(description: "猫の年齢", .range(0...20))
    var age: Int

    @Guide(description: "猫の性格を一文で表すプロフィール")
    var profile: String
}

2. 構造化出力のリクエスト

let response = try await session.respond(
    to: "かわいい保護猫を生成してください",
    generating: CatProfile.self
)

// 構造化されたフィールドに直接アクセス
print("名前: \(response.content.name)")
print("年齢: \(response.content.age)")
print("プロフィール: \(response.content.profile)")

サポートされている@Guide制約

  • .range(0...20) — 数値の範囲
  • .count(3) — 配列要素数
  • description: — 生成のための意味的なガイダンス

コアパターン — ツール呼び出し

モデルがドメイン固有のタスクのためにカスタムコードを呼び出せるようにします。

1. ツールの定義

struct RecipeSearchTool: Tool {
    let name = "recipe_search"
    let description = "指定された用語に一致するレシピを検索し、結果のリストを返します。"

    @Generable
    struct Arguments {
        var searchTerm: String
        var numberOfResults: Int
    }

    func call(arguments: Arguments) async throws -> ToolOutput {
        let recipes = await searchRecipes(
            term: arguments.searchTerm,
            limit: arguments.numberOfResults
        )
        return .string(recipes.map { "- \($0.name): \($0.description)" }.joined(separator: "\n"))
    }
}

2. ツールを使用したセッションの作成

let session = LanguageModelSession(tools: [RecipeSearchTool()])
let response = try await session.respond(to: "パスタのレシピをいくつか見つけてください")

3. ツールエラーの処理

do {
    let answer = try await session.respond(to: "トマトスープのレシピを見つけてください。")
} catch let error as LanguageModelSession.ToolCallError {
    print(error.tool.name)
    if case .databaseIsEmpty = error.underlyingError as? RecipeSearchToolError {
        // 特定のツールエラーを処理
    }
}

コアパターン — スナップショットストリーミング

PartiallyGenerated型を使用して、構造化された応答をリアルタイムUI向けにストリーミングします。

@Generable
struct TripIdeas {
    @Guide(description: "今後の旅行のアイデア")
    var ideas: [String]
}

let stream = session.streamResponse(
    to: "エキサイティングな旅行のアイデアをいくつか教えてください?",
    generating: TripIdeas.self
)

for try await partial in stream {
    // partial: TripIdeas.PartiallyGenerated(すべてのプロパティはOptional)
    print(partial)
}

SwiftUI統合

@State private var partialResult: TripIdeas.PartiallyGenerated?
@State private var errorMessage: String?

var body: some View {
    List {
        ForEach(partialResult?.ideas ?? [], id: \.self) { idea in
            Text(idea)
        }
    }
    .overlay {
        if let errorMessage { Text(errorMessage).foregroundStyle(.red) }
    }
    .task {
        do {
            let stream = session.streamResponse(to: prompt, generating: TripIdeas.self)
            for try await partial in stream {
                partialResult = partial
            }
        } catch {
            errorMessage = error.localizedDescription
        }
    }
}

主要な設計上の決定

決定根拠
オンデバイス実行プライバシー — デバイス外にデータが流出せず、オフラインで動作
4,096トークン制限オンデバイスモデルの制約;大きなデータはセッション間で分割
スナップショットストリーミング(差分ではない)構造化出力に適している;各スナップショットは完全な部分状態
@Generableマクロ構造化生成のためのコンパイル時の安全性;PartiallyGenerated型を自動生成
セッションごとに単一リクエストisRespondingが同時リクエストを防ぐ;必要に応じて複数セッションを作成
response.content(.outputではなく)正しいAPI — 結果には常に.contentプロパティ経由でアクセス

ベストプラクティス

  • model.availabilityを常に確認 する — セッション作成前にすべての利用不可ケースを処理
  • instructionsを使用 してモデルの動作をガイドする — プロンプトより優先される
  • 新しいリクエストを送信する前にisRespondingを確認 する — セッションは一度に1つのリクエストを処理
  • 結果にはresponse.contentにアクセス する — .outputではない
  • 大きな入力はチャンクに分割する — 4,096トークン制限は指示 + プロンプト + 出力の合計に適用
  • 構造化出力には@Generableを使用 する — 生の文字列をパースするよりも強力な保証
  • GenerationOptions(temperature:)を使用 して創造性を調整する(値が高いほど創造的)
  • Instrumentsでモニタリングする — Xcode Instrumentsを使用してリクエストのパフォーマンスをプロファイリング

避けるべきアンチパターン

  • model.availabilityを確認せずにセッションを作成する
  • 4,096トークンのコンテキストウィンドウを超える入力を送信する
  • 単一セッションで同時リクエストを試みる
  • 応答データにアクセスする際に.contentの代わりに.outputを使用する
  • @Generableによる構造化出力が機能する場合に、生の文字列応答をパースする
  • 複雑なマルチステップロジックを単一のプロンプトに構築する — 複数の焦点を絞ったプロンプトに分割する
  • モデルが常に利用可能であると想定する — デバイスの適合性と設定は異なる

使用すべき時

  • プライバシー重視のアプリ向けオンデバイステキスト生成
  • ユーザー入力からの構造化データ抽出(フォーム、自然言語コマンド)
  • オフラインでも動作する必要があるAI支援機能
  • 生成されたコンテンツを段階的に表示するストリーミングUI
  • ツール呼び出しによるドメイン固有のAIアクション(検索、計算、ルックアップ)

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/content-engine

Create platform-native content systems for X, LinkedIn, TikTok, YouTube, newsletters, and repurposed multi-platform campaigns. Use when the user wants social posts, threads, scripts, content calendars, or one source asset adapted cleanly across platforms.

affaan-m/ECC

Multi-platform content distribution across X, LinkedIn, Threads, and Bluesky. Adapts content per platform using content-engine patterns. Never posts identical content cross-platform. Use when the user wants to distribute content across social platforms.

affaan-m/fal-ai-media

Unified media generation via fal.ai MCP — image, video, and audio. Covers text-to-image (Nano Banana), text/image-to-video (Seedance, Kling, Veo 3), text-to-speech (CSM-1B), and video-to-audio (ThinkSound). Use when the user wants to generate images, videos, or audio with AI.

affaan-m/manim-video

日本語翻訳:このファイルは manim-video 用の日本語翻訳が必要です

affaan-m/remotion-video-creation

Remotion のベストプラクティス - React で動画を作成する。3D、アニメーション、音声、字幕、チャート、トランジションなどをカバーするドメイン固有の29のルール。

affaan-m/video-editing

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

agent-self-evaluation

Use after completing any non-trivial task. The agent self-rates its output on 5 axes — accuracy, completeness, clarity, actionability, conciseness — with concrete evidence per criterion. Produces a structured 1-5 scorecard with specific improvement suggestions.

agent-sort

Build an evidence-backed ECC install plan for a specific repo by sorting skills, commands, rules, hooks, and extras into DAILY vs LIBRARY buckets using parallel repo-aware review passes. Use when ECC should be trimmed to what a project actually needs instead of loading the full bundle.

ai-first-engineering

Engineering operating model for teams where AI agents generate a large share of implementation output. Use when setting team process, review gates, or ownership rules for a codebase largely written by agents.

ai-regression-testing

Regression testing strategies for AI-assisted development. Sandbox-mode API testing without database dependencies, automated bug-check workflows, and patterns to catch AI blind spots where the same model writes and reviews code. Use when adding regression coverage to AI-assisted code, or when the same model both wrote and reviewed a change.

android-clean-architecture

Clean Architecture patterns for Android and Kotlin Multiplatform projects — module structure, dependency rules, UseCases, Repositories, and data layer patterns. Use when structuring modules, layers, or data flow in an Android or KMP project.

angular-developer

Generates Angular code and provides architectural guidance. Trigger when creating projects, components, or services, or for best practices on reactivity (signals, linkedSignal, resource), forms, dependency injection, routing, SSR, accessibility (ARIA), animations, styling (component styles, Tailwind CSS), testing, or CLI tooling.

関連スキル