FOUNDATION MODELS FRAMEWORK · SWIFT · PYTHON
Foundation Models 框架:为你的应用提供端侧 LLM 会话
Foundation Models 框架是 Apple 为 Apple Intelligence 背后模型提供的原生 API。你创建一个会话,按需声明希望返回的 Swift 类型,添加模型可调用的工具,然后流式获取回答——不需要分发权重、不需要服务器、没有 token 费用。WWDC26 新增了图像输入、Dynamic Profiles、可插拔的 LanguageModel 协议、Python SDK 与评测框架。
用 Swift 创建第一个会话
先检查可用性,再用指令创建会话并提问。结构化生成把自由文本变成带类型的 Swift 值,这正是让该框架适合解析收据、表单与截图的关键特性。
import FoundationModels
// Check that Apple Intelligence and the on-device model are available first.
guard case .available = SystemLanguageModel.default.availability else { return }
let session = LanguageModelSession(instructions: "You are a concise assistant.")
let answer = try await session.respond(to: "Summarise this receipt in one sentence.")
print(answer.content)
// Guided generation: the model fills a Swift type instead of free text.
@Generable
struct Receipt {
@Guide(description: "Merchant name") var merchant: String
@Guide(description: "Total amount in the receipt currency") var total: Double
}
let receipt = try await session.respond(to: "Extract the merchant and total.", generating: Receipt.self).content 选择模型后端(WWDC26)
会话现在可以由任何遵循 LanguageModel 协议的对象驱动。端侧系统模型仍是默认;Private Cloud Compute 在同样的隐私保证下提供 Apple 服务器模型;CoreAILanguageModel 与 MLXLanguageModel 在本地运行开放模型;Claude、Gemini 等云提供方也能在同一 API 之后接入。
// WWDC26: any provider can back a session through the LanguageModel protocol.
let session = LanguageModelSession(model: SystemLanguageModel.default) // on-device AFM 3 Core
// let session = LanguageModelSession(model: PrivateCloudComputeLanguageModel()) // Apple server models
// let session = LanguageModelSession(model: MLXLanguageModel(...)) // open-source local models
// Third-party cloud providers can conform to LanguageModel and plug in the same way. 图像、工具与 Dynamic Profiles
多模态提示允许把图像与文字一起传入,让模型回答关于照片的问题——与 FastVLM 相同的任务,现在由系统模型完成。Vision 框架的 OCR、条码识别等能力可以作为可调用工具暴露给模型。Dynamic Profiles 允许在持续的会话中切换模型、工具与指令,这正是应用从端侧快速回答切换到服务器模型而不丢失上下文的方式。
Python SDK、fm 命令行与评测
WWDC26 第 334 场介绍了 Python SDK 与 fm 命令行工具,可在 Mac 上用脚本调用系统模型;第 298/299/335 场介绍了用于发布前测试提示词的评测框架。先用它们快速原型化提示词设计,再把最优提示移植到 Swift。
什么时候改用 FastVLM
当应用运行在 Apple Intelligence 设备上、希望零下载且由系统管理推理时使用该框架。当你需要特定的开放模型、跨平台(包括 Web 与 Linux)、可控的量化与延迟,或需要支持较旧设备时,使用 FastVLM(通过 MLX、Core ML 或浏览器)。
常见问题
框架可以离线使用吗?
SystemLanguageModel 可以:推理在设备上完成。Private Cloud Compute 与第三方提供方需要网络连接。
API 和 Core ML 一样吗?
不一样。Core ML(及其 WWDC26 的继任者 Core AI)运行你自行转换并分发的模型。Foundation Models 框架是更高层的会话 API,面向 Apple 提供的模型——自 WWDC26 起也可面向任何遵循 LanguageModel 协议的提供方。