Communitygithub.com

FoundationModels:裝置端大型語言模型(iOS 26)

使用 Apple FoundationModels 框架為 iOS 26+ 應用程式加入裝置端 LLM 功能,支援文字生成、透過 @Generable 進行引導生成、工具呼叫和快照串流。

FoundationModels:裝置端大型語言模型(iOS 26) 是什麼?

這個技能提供將 Apple 裝置端語言模型整合至應用程式的完整模式,使用 FoundationModels 框架,專為 iOS 26 及其後續版本設計。核心優勢在於所有處理都在裝置上執行,確保隱私保護並支援離線運作,這對於需要處理敏感資料或必須在無網路環境下提供 AI 功能的開發者來說至關重要。功能包含基本文字生成、使用 @Generable 巨集從自然語言生成結構化 Swift 類型(如從使用者輸入中提取日期或清單)、定義自訂工具讓模型在特定領域執行搜尋或計算等程式碼,以及使用 PartiallyGenerated 類型進行快照串流,實現即時 UI 更新。文件也詳細說明可用性檢查、每個會話只能處理一個請求、4,096 個 token 的上下文限制等關鍵設計決策,並提供避免常見陷阱的建議。支援 Apple Intelligence 的 iOS 26 以上裝置皆可適用。

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

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

FoundationModels:裝置端大型語言模型(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: "What's a good month to visit Paris?")
print(response.content)

// 多輪對話:重複使用會話以保留對話上下文
let session = LanguageModelSession(instructions: """
    你是一位烹飪助手。
    根據食材提供食譜建議。
    建議應簡短且實用。
    """)

let first = try await session.respond(to: "I have chicken and rice")
let followUp = try await session.respond(to: "What about a vegetarian option?")

關於 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: "Generate a cute rescue cat",
    generating: CatProfile.self
)

// 直接存取結構化欄位
print("Name: \(response.content.name)")
print("Age: \(response.content.age)")
print("Profile: \(response.content.profile)")

支援的 @Guide 約束條件

  • .range(0...20) — 數值範圍
  • .count(3) — 陣列元素數量
  • description: — 用於生成的語意引導

核心模式 — 工具呼叫

讓模型為特定領域任務呼叫自訂程式碼:

1. 定義工具

struct RecipeSearchTool: Tool {
    let name = "recipe_search"
    let description = "Search for recipes matching a given term and return a list of results."

    @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: "Find me some pasta recipes")

3. 處理工具錯誤

do {
    let answer = try await session.respond(to: "Find a recipe for tomato soup.")
} 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: "What are some exciting trip ideas?",
    generating: TripIdeas.self
)

for try await partial in stream {
    // partial: TripIdeas.PartiallyGenerated(所有屬性皆為可選)
    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 個 token 限制裝置端模型限制;跨會話將大型資料分塊處理
快照串流(非差異串流)友善於結構化輸出;每個快照都是一個完整的部分狀態
@Generable 巨集編譯期安全性,確保結構化生成;自動生成 PartiallyGenerated 類型
每個會話單一請求isResponding 可防止並發請求;如有需要可建立多個會話
response.content(非 .output)正確 API — 始終透過 .content 屬性存取結果

最佳做法

  • 始終檢查 model.availability 在建立會話之前 — 處理所有不可用的情況
  • 使用 instructions 引導模型行為 — 它們的優先級高於提示詞
  • 傳送新請求前檢查 isResponding — 每個會話一次只處理一個請求
  • 結果請存取 response.content — 而非 .output
  • 將大型輸入分塊處理 — 4,096 個 token 限制適用於 instructions + prompt + output 的總和
  • 使用 @Generable 進行結構化輸出 — 比解析原始字串有更強的保證
  • 使用 GenerationOptions(temperature:) 調整創造力(數值越高越有創造力)
  • 使用 Instruments 監控 — 使用 Xcode Instruments 分析請求效能

應避免的反模式

  • 未先檢查 model.availability 就建立會話
  • 傳送超出 4,096 個 token 上下文視窗的輸入
  • 在單一會話中嘗試並發請求
  • 使用 .output 而非 .content 存取回應資料
  • 在可以透過 @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.

相關技能