Communitygithub.com

foundation-models-on-device

Apple FoundationModels框架,用于iOS 26+上的设备端LLM——文本生成、基于@Generable的引导式生成、工具调用和快照流式处理。在需要为iOS 26+应用添加设备端LLM功能时使用。

foundation-models-on-device 是什么?

该技能详细介绍了如何基于Apple FoundationModels框架在iOS 26+上集成设备端大语言模型(LLM)。它涵盖了核心模式,包括基础会话、使用@Generable宏的结构化输出、自定义工具调用以及快照流式处理。所有这些功能均在设备端运行,确保用户隐私和离线可用性。开发者可以学习如何检查模型可用性、设置会话指令、定义可生成(Generable)的Swift类型以获取结构化数据,以及创建自定义工具供模型调用。技能文档还提供了关键的设计决策、最佳实践和应避免的反模式,帮助开发者高效利用设备端AI能力。

兼容平台~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: 设备端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: "有素食选择吗?")

关于指令的关键点:

  • 定义模型的角色(“你是一名导师”)
  • 指定要做什么(“帮助提取日历事件”)
  • 设置风格偏好(“尽可能简短地回答”)
  • 添加安全措施(对于危险请求,回复“我无法帮助处理此问题”)

核心模式 —— 使用@Generable的引导式生成

生成结构化的Swift类型,而不是原始字符串:

1. 定义可生成类型

@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
        }
    }
}

关键设计决策

决策理由
设备端执行隐私保护——数据不离开设备;支持离线使用
4096 token限制设备端模型约束;跨会话分块处理大数据
快照流式(非增量流)对结构化输出友好;每个快照都是完整的局部状态
@Generable宏编译时安全的结构化生成;自动生成PartiallyGenerated类型
单次请求/会话isResponding防止并发请求;如需可创建多个会话
response.content(而非.output)正确的API——始终通过.content属性访问结果

最佳实践

  • 始终检查model.availability 后再创建会话——处理所有不可用情况
  • 使用instructions 指导模型行为——它们比提示词优先级更高
  • 在发送新请求前检查isResponding ——每个会话一次只处理一个请求
  • 访问response.content 获取结果——而非.output
  • 将大输入拆分为多个块 —— 4096 token限制适用于指令+提示词+输出的总和
  • 使用@Generable 进行结构化输出——比解析原始字符串更可靠
  • 使用GenerationOptions(temperature:) 调节创造力(更高=更有创意)
  • 使用Instruments监控 ——使用Xcode Instruments分析请求性能

应避免的反模式

  • 不先检查model.availability就创建会话
  • 发送超出4096 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.

相关技能