SKILL.md
唯讀
名稱
foundation-models-on-device
描述
Apple 適用於 iOS 26+ 裝置端 LLM 的 FoundationModels 框架——涵蓋文字生成、搭配 @Generable 的引導式生成、工具呼叫(Tool Calling)與快照串流(Snapshot Streaming)。
FoundationModels:裝置端 LLM (iOS 26)
使用 FoundationModels 框架將 Apple 裝置端語言模型整合至 App 的設計模式。涵蓋文字生成、透過 @Generable 實現的結構化輸出、自訂工具呼叫(Tool Calling)以及快照串流(Snapshot Streaming)——全數於裝置端執行,確保隱私並支援離線運作。
啟用時機
- 利用 Apple Intelligence 在裝置端建構 AI 驅動的功能
- 無需依賴雲端即可生成或摘要文字
- 從自然語言輸入中擷取結構化資料
- 針對特定領域的 AI 操作實作自訂工具呼叫
- 串流傳輸結構化回應以即時更新 UI
- 需要保護隱私的 AI(資料完全不出裝置)
核心模式——可用性檢查
建立 Session 之前,務必先檢查模型的可用狀態:
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)")
}
}
}
核心模式——基礎 Session
// 單輪對話:每次建立新的 Session
let session = LanguageModelSession()
let response = try await session.respond(to: "What's a good month to visit Paris?")
print(response.content)
// 多輪對話:重複使用 Session 以維持對話上下文
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 的關鍵要點:
- 定義模型角色(例如:「你是一位烹飪助手」)
- 明確指定任務(例如:「協助擷取行事曆事件」)
- 設定風格偏好(例如:「盡可能簡短且實用地下達回應」)
- 加入安全防護(例如:遇到危險請求時回應「我無法協助處理該事項」)
核心模式——搭配 @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
)
// 直接存取結構化欄位
print("Name: \(response.content.name)")
print("Age: \(response.content.age)")
print("Profile: \(response.content.profile)")
支援的 @Guide 約束條件
.range(0...20)— 數值範圍.count(3)— 陣列元素數量description:— 針對生成的語意引導(Semantic guidance)
核心模式——工具呼叫(Tool Calling)
讓模型針對特定領域的任務呼叫自訂程式碼:
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. 建立帶有 Tool 的 Session
let session = LanguageModelSession(tools: [RecipeSearchTool()])
let response = try await session.respond(to: "Find me some pasta recipes")
3. 處理 Tool 錯誤
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 {
// 處理特定工具錯誤
}
}
核心模式——快照串流(Snapshot Streaming)
搭配 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 (所有屬性皆為 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 上限 | 裝置端模型的硬性限制;巨量資料應分拆至多個 Session 處理 |
| 快照串流(非增量 Delta) | 易於搭配結構化輸出;每個快照皆為完整的局部狀態(Partial state) |
@Generable 巨集 |
確保結構化生成的編譯期安全性;自動生成 PartiallyGenerated 型別 |
| 單一 Session 每次限單一請求 | isResponding 屬性會防止並行請求;若有需要請建立多個 Session |
使用 response.content(而非 .output) |
正確的 API 規格——始終透過 .content 屬性存取結果 |
最佳實踐
- 在建立 Session 前務必檢查
model.availability——妥善處理所有無法使用的狀況 - 使用
instructions來指引模型行為——其優先權高於提示詞(Prompts) - 發送新請求前檢查
isResponding——每個 Session 一次僅能處理一個請求 - 存取
response.content來取得結果——而非.output - 將大量輸入資料分拆成區塊(Chunks)——4,096 Token 的上限包含 instructions + prompt + 輸出的總和
- 使用
@Generable進行結構化輸出——相比解析原始字串能提供更強的保證 - 使用
GenerationOptions(temperature:)來微調創造力(數值越高代表越有創意) - 使用 Instruments 進行監測——利用 Xcode Instruments 分析請求效能
應避免的反模式(Anti-Patterns)
- 未先檢查
model.availability就直接建立 Session - 發送超出 4,096 Token 上下文視窗(Context window)的輸入
- 企圖在單一 Session 上進行並行請求
- 使用
.output代替.content來讀取回應資料 - 明明可以用
@Generable結構化輸出,卻選擇解析原始字串回應 - 在單一 Prompt 中構建複雜的多步驟邏輯——應拆解為多個焦點明確的 Prompt
- 假設模型隨時可用——實際上裝置資格與使用者設定各有不同
適用場景
- 適用於注重隱私的 App 裝置端文字生成
- 從使用者輸入(表單、自然語言指令)中擷取結構化資料
- 必須在離線狀態下運作的 AI 輔助功能
- 需漸進式顯示生成內容的串流 UI
- 透過工具呼叫(Tool calling)執行特定領域的 AI 操作(搜尋、計算、查表)






