FoundationModels:端侧大语言模型(iOS 26)
本资料介绍如何使用 Apple 的 FoundationModels 框架,将设备端语言模型集成到 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("Device not eligible for Apple Intelligence")
case .unavailable(.appleIntelligenceNotEnabled):
Text("Please enable Apple Intelligence in Settings")
case .unavailable(.modelNotReady):
Text("Model is downloading or not ready")
case .unavailable(let other):
Text("Model unavailable: \(other)")
}
}
}
核心模式:基础会话
// Single-turn: create a new session each time
let session = LanguageModelSession()
let response = try await session.respond(to: "What's a good month to visit Paris?")
print(response.content)
// Multi-turn: reuse session for conversation context
let session = LanguageModelSession(instructions: """
You are a cooking assistant.
Provide recipe suggestions based on ingredients.
Keep suggestions brief and practical.
""")
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 的关键点:
- 定义模型角色("You are a mentor")
- 指定要做什么("Help extract calendar events")
- 设置风格偏好("Respond as briefly as possible")
- 添加安全措施("Respond with 'I can't help with that' for dangerous requests")
核心模式:使用 @Generable 的引导式生成
生成结构化的 Swift 类型而非原始字符串。
1. 定义 Generable 类型
@Generable(description: "Basic profile information about a cat")
struct CatProfile {
var name: String
@Guide(description: "The age of the cat", .range(0...20))
var age: Int
@Guide(description: "A one sentence profile about the cat's personality")
var profile: String
}
2. 请求结构化输出
let response = try await session.respond(
to: "Generate a cute rescue cat",
generating: CatProfile.self
)
// Access structured fields directly
print("Name: \(response.content.name)")
print("Age: \(response.content.age)")
print("Profile: \(response.content.profile)")
支持的 @Guide 约束:
.range(0...20)— 数值范围.count(3)— 数组元素数量description:— 面向生成的语义指导
核心模式:工具调用
让模型为特定领域任务调用自定义代码。
1. 定义 Tool
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 {
// Handle specific tool error
}
}
核心模式:快照流式
使用 PartiallyGenerated 类型为实时 UI 流式输出结构化响应:
@Generable
struct TripIdeas {
@Guide(description: "Ideas for upcoming trips")
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 (all properties 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 限制适用于 instructions + prompt + output 的总和
- 使用 @Generable 获得结构化输出 —— 比解析原始字符串有更强保证
- 使用 GenerationOptions(temperature:) 调节创造性(越高越有创造性)
- 用 Instruments 监控 —— 使用 Xcode Instruments 分析请求性能
应避免的反模式
- 未先检查 model.availability 就创建会话
- 发送超过 4,096 token 上下文窗口的输入
- 在单个会话上尝试并发请求
- 使用 .output 而非 .content 访问响应数据
- 在 @Generable 结构化输出可用时解析原始字符串响应
- 在单个提示词中构建复杂的多步逻辑 —— 拆分为多个聚焦的提示词
- 假设模型始终可用 —— 设备资格与设置各不相同
使用场景
- 面向隐私敏感 App 的端侧文本生成
- 从用户输入中提取结构化数据(表单、自然语言命令)
- 必须离线工作的 AI 辅助功能
- 渐进展示生成内容的流式 UI
- 通过工具调用实现特定领域 AI 动作(搜索、计算、查询)