/swift:foundation-models-on-devicefrom swift
Integrates Apple's FoundationModels framework for on-device LLM in iOS 26+ apps. Covers text generation, guided structured output with @Generable, tool calling, and snapshot streaming for privacy-preserving AI.
Ships in swift. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Patterns for integrating Apple's on-device language model into apps using the FoundationModels framework. Covers text generation, structured output with @Generable, custom tool calling, and snapshot streaming — all running on-device for privacy and offline support.
Always check model availability before creating a 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: \(String(describing: 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?")
Key points for instructions:
Generate structured Swift types instead of raw strings:
@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
}
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)")
.range(0...20) — numeric range.count(3) — array element countdescription: — semantic guidance for generationLet the model invoke custom code for domain-specific tasks.
The Tool protocol has two associated types: Arguments (a @Generable type the model fills in) and Output (anything conforming to PromptRepresentable — String, a @Generable type, or GeneratedContent). call(arguments:) returns Output directly. There is no ToolOutput type in the shipping SDK — it existed only in early iOS 26 seeds; Transcript.ToolOutput is an unrelated transcript-entry struct.
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 -> String {
let recipes = await searchRecipes(
term: arguments.searchTerm,
limit: arguments.numberOfResults
)
return recipes.map { "- \($0.name): \($0.description)" }.joined(separator: "\n")
}
}
let session = LanguageModelSession(tools: [RecipeSearchTool()])
let response = try await session.respond(to: "Find me some pasta recipes")
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
}
}
Stream structured responses for real-time UI with PartiallyGenerated types. The stream yields ResponseStream<Content>.Snapshot elements — the partial value lives in snapshot.content (with snapshot.rawContent holding the raw GeneratedContent):
@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 snapshot in stream {
// snapshot.content: TripIdeas.PartiallyGenerated (all properties Optional)
print(snapshot.content)
}
@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 snapshot in stream {
partialResult = snapshot.content
}
} catch {
errorMessage = error.localizedDescription
}
}
}
| Decision | Rationale |
|---|---|
| On-device execution | Privacy — no data leaves the device; works offline |
Context window: query contextSize | SystemLanguageModel.default.contextSize reports the limit (4,096 on current OS releases); query it instead of hardcoding, and chunk large data across sessions |
| Snapshot streaming (not deltas) | Structured output friendly; each snapshot is a complete partial state |
@Generable macro | Compile-time safety for structured generation; auto-generates PartiallyGenerated type |
| Single request per session | isResponding prevents concurrent requests; create multiple sessions if needed |
response.content (not .output) | Correct API — always access results via .content property |
model.availability before creating a session — handle all unavailability casesinstructions to guide model behavior — they take priority over promptsisResponding before sending a new request — sessions handle one request at a timeresponse.content for results — not .outputmodel.contextSize (4,096 today, back-deployed to iOS 26.0) instead of hardcoding, and on iOS 26.4+ measure inputs with model.tokenCount(for:) (overloads for prompt, instructions, tools, schema, and transcript entries)@Generable for structured output — stronger guarantees than parsing raw stringsGenerationOptions(temperature:) to tune creativity (higher = more creative)LanguageModelError, SystemLanguageModel.Error, LanguageModelSession.Error (none exist in the 26.x SDK) — and relaxes guardrails that over-blocked benign contentmodel.availability firstcontextSize.output instead of .content to access response data@Generable structured output would workWhat SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
apple-intelligence, on-device-llm, foundation-models, ios-26, swift
Other plugins' skills for the same job
4 skills in this plugin
/liquid-glass-designApple native iOS 26 (SwiftUI/UIKit/WidgetKit) — NOT web CSS glassmorphism/backdrop-filter. iOS 26 Liquid Glass design system — dynamic glass material with blur, reflection, and interactive morphing via glassEffect/UIGlassEffect. Use when building or migrating native Apple apps to the iOS 26 glass design language; for glassmorphism on web pages use ui-ux-pro-max instead./swift-concurrency-6-2Swift 6.2 Approachable Concurrency — single-threaded by default, @concurrent for explicit background offloading, isolated conformances for main actor types. Use when migrating a project to Swift 6.2 concurrency, adopting @concurrent or MainActor-default inference, or resolving data-race safety compiler errors ("sending X risks causing data races")./npx claudepluginhub davie521/claude-skills --plugin swift