Communitygithub.com

FoundationModels: 设备端 LLM (iOS 26)

Apple FoundationModels 框架,用于设备端 LLM —— 文本生成、通过 @Generable 进行引导式生成、工具调用以及在 iOS 26+ 中的快照流式传输。当需要在 iOS 26+ 上使用 Apple FoundationModels 添加设备端 LLM 功能时使用。

FoundationModels: 设备端 LLM (iOS 26) 是什么?

此技能详细介绍了如何利用 Apple 的 FoundationModels 框架在设备端集成大型语言模型(LLM)。其核心优势在于所有推理均在本地完成,保证了用户隐私并支持离线使用。技能覆盖四大核心模式:首先,通过语言模型会话(`LanguageModelSession`)执行基础的文本生成与多轮对话。其次,使用 `@Generable` 宏定义 Swift 类型,引导模型生成结构化数据(如 JSON 对象),从而摒弃脆弱的字符串解析。第三,支持自定义工具调用(Tool Calling),允许模型与 App 内特定领域的功能(如搜索 API)进行交互。最后,技能描述了快照流式传输(Snapshot Streaming)模式,该模式会生成 `PartiallyGenerated` 类型,特别适用于在 SwiftUI 中实现实时、逐步更新的 UI。同时,还详细说明了关键的 `@Guide` 约束(如范围、数组计数)以及处理模型可用性、错误和并发的最佳实践与反模式。此技能特别适用于需要在 iOS 26+ 上构建注重隐私、支持离线且具备复杂 AI 能力的开发者。

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

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

FoundationModels: 设备端 LLM (iOS 26) 是做什么的?

使用 FoundationModels 框架将 Apple 的设备端语言模型集成到 App 中的模式。涵盖文本生成、使用 @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 类型

@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 Token 限制设备端模型约束;跨会话分块处理大数据
快照流式传输(非增量)适用于结构化输出;每个快照都是一个完整的部分状态
@Generable 宏为结构化生成提供编译时安全性;自动生成 PartiallyGenerated 类型
单次请求与会话isResponding 防止并发请求;如果需要,可创建多个会话
response.content(非 .output)正确的 API——始终通过 .content 属性访问结果

最佳实践

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

应避免的反模式

  • 在未先检查 model.availability 的情况下创建会话
  • 发送超过 4,096 Token 上下文窗口的输入
  • 在单个会话上尝试并发请求
  • 使用 .output 而不是 .content 来访问响应数据
  • 在 @Generable 结构化输出可行的情况下,解析原始字符串响应
  • 在单个提示词中构建复杂的多步骤逻辑——应拆分为多个聚焦的提示词
  • 假设模型始终可用——设备资格和设置各不相同

使用场景

  • 针对隐私敏感型 App 的设备端文本生成
  • 从用户输入(表单、自然语言命令)中提取结构化数据
  • 必须能够离线工作的 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/claude-api

Anthropic Claude API patterns for Python and TypeScript. Covers Messages API, streaming, tool use, vision, extended thinking, batches, prompt caching, and Claude Agent SDK. Use when building applications with the Claude API or Anthropic SDKs.

affaan-m/everything-claude-code

End-to-end marketing campaign planning and execution. Covers audience research, positioning, campaign angle definition, landing page copy, email sequences, social posts, ad copy, short-form video scripts, and content calendars. Use as the orchestration layer for multi-channel product launches. Use when planning or executing a multi-channel product launch, or producing landing page, email, social, or ad copy.

affaan-m/everything-claude-code

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/everything-claude-code-conventions

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/frontend-design

Create distinctive, production-grade frontend interfaces with high design quality. Use when the user asks to build web components, pages, or applications and the visual direction matters as much as the code quality.

affaan-m/gget

gget CLI and Python workflow for quick genomic database queries, sequence lookup, BLAST-style searches, enrichment checks, and reproducible bioinformatics evidence logs.

affaan-m/literature-review

Systematic literature-review workflow for academic, biomedical, technical, and scientific topics, including search planning, source screening, synthesis, citation checks, and evidence logging.

affaan-m/motion-ui

Production-ready UI motion system for React/Next.js. Use when implementing animations, transitions, or motion patterns.

affaan-m/project-guidelines-example

Example project-specific skill template based on a real production application.

affaan-m/pubmed-database

Direct PubMed and NCBI E-utilities search workflows for biomedical literature, MeSH queries, PMID lookup, citation retrieval, and API-backed literature monitoring.

affaan-m/scholar-evaluation

Structured scholarly-work evaluation for papers, proposals, literature reviews, methods sections, evidence quality, citation support, and research-writing feedback.

affaan-m/uspto-database

USPTO patent and trademark data workflow for official record lookup, PatentSearch queries, TSDR checks, assignment data, and reproducible IP research logs.

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.

相关技能