一键导入
foundation-models
On-device LLM integration using Apple's Foundation Models framework. Use when implementing AI text generation, structured output, or tool calling.
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
菜单
On-device LLM integration using Apple's Foundation Models framework. Use when implementing AI text generation, structured output, or tool calling.
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
基于 SOC 职业分类
| name | foundation-models |
| description | On-device LLM integration using Apple's Foundation Models framework. Use when implementing AI text generation, structured output, or tool calling. |
| allowed-tools | ["Read","Write","Edit","Glob","Grep","Bash","AskUserQuestion"] |
Integrate Apple's on-device LLM into your apps for privacy-preserving AI features.
import FoundationModels
struct IntelligentView: View {
private var model = SystemLanguageModel.default
var body: some View {
switch model.availability {
case .available:
ContentView()
case .unavailable(.deviceNotEligible):
UnsupportedDeviceView()
case .unavailable(.appleIntelligenceNotEnabled):
EnableIntelligenceView()
case .unavailable(.modelNotReady):
ModelDownloadingView()
case .unavailable(let reason):
ErrorView(reason: reason)
}
}
}
// Simple session
let session = LanguageModelSession()
// Session with instructions
let session = LanguageModelSession(instructions: """
You are a helpful cooking assistant.
Provide concise, practical advice for home cooks.
""")
let response = try await session.respond(to: "What's a quick dinner idea?")
print(response.content)
Instructions set the model's persona and constraints. They're prioritized over prompts.
[Role] + [Task] + [Style] + [Safety]
Example:
let instructions = """
You are a fitness coach specializing in home workouts.
Help users create exercise routines based on their equipment and goals.
Keep responses under 100 words and use bullet points for exercises.
Decline requests for medical advice and suggest consulting a doctor.
"""
| Component | Purpose | Example |
|---|---|---|
| Role | Define persona | "You are a travel expert" |
| Task | What to do | "Help plan itineraries" |
| Style | Output format | "Use bullet points, be concise" |
| Safety | Boundaries | "Don't provide medical advice" |
Prompts are user inputs. Make them:
| Principle | Bad | Good |
|---|---|---|
| Specific | "Help with cooking" | "Suggest a 30-minute vegetarian dinner" |
| Constrained | "Tell me about dogs" | "Describe Golden Retrievers in 3 sentences" |
| Focused | "I need help with many things" | "What ingredients substitute for eggs in baking?" |
Question Pattern:
let prompt = "What are three ways to reduce food waste at home?"
Command Pattern:
let prompt = "Create a weekly meal plan for a family of four, budget-friendly."
Extraction Pattern:
let prompt = """
Extract the following from this email:
- Sender name
- Meeting date
- Action items
Email: \(emailContent)
"""
Transformation Pattern:
let prompt = "Rewrite this text to be more formal: \(casualText)"
Get typed Swift data instead of raw strings.
@Generable(description: "A recipe suggestion")
struct Recipe {
var name: String
@Guide(description: "Cooking time in minutes", .range(5...180))
var cookingTime: Int
@Guide(description: "Difficulty level", .options(["Easy", "Medium", "Hard"]))
var difficulty: String
@Guide(description: "List of ingredients", .count(3...15))
var ingredients: [String]
@Guide(description: "Step-by-step instructions")
var instructions: [String]
}
| Constraint | Use Case | Example |
|---|---|---|
.range(min...max) | Numeric bounds | .range(1...100) |
.options([...]) | Enum-like choices | .options(["Low", "Medium", "High"]) |
.count(n) | Exact array length | .count(5) |
.count(min...max) | Array length range | .count(3...10) |
let session = LanguageModelSession(instructions: """
You are a recipe assistant. Generate practical, home-cook friendly recipes.
""")
let recipe = try await session.respond(
to: "Suggest a quick pasta dish",
generating: Recipe.self
)
print("Recipe: \(recipe.content.name)")
print("Time: \(recipe.content.cookingTime) minutes")
print("Ingredients: \(recipe.content.ingredients.joined(separator: ", "))")
@Generable(description: "A travel itinerary")
struct Itinerary {
var destination: String
@Guide(description: "Daily activities for the trip")
var days: [DayPlan]
}
@Generable(description: "Activities for one day")
struct DayPlan {
var dayNumber: Int
@Guide(description: "Morning activity")
var morning: String
@Guide(description: "Afternoon activity")
var afternoon: String
@Guide(description: "Evening activity")
var evening: String
}
Let the model call your code to access data or perform actions.
struct WeatherTool: Tool {
let name = "getWeather"
let description = "Get current weather for a location"
struct Arguments: Codable {
var location: String
}
func call(arguments: Arguments) async throws -> ToolOutput {
let weather = await WeatherService.shared.fetch(for: arguments.location)
return .string("Temperature: \(weather.temp)°F, Conditions: \(weather.conditions)")
}
}
let weatherTool = WeatherTool()
let session = LanguageModelSession(
instructions: "You help users plan outdoor activities based on weather.",
tools: [weatherTool]
)
// Model automatically calls tool when needed
let response = try await session.respond(
to: "Should I go hiking in San Francisco today?"
)
do {
let response = try await session.respond(to: prompt)
} catch let error as LanguageModelSession.ToolCallError {
print("Tool '\(error.tool.name)' failed: \(error.underlyingError)")
} catch {
print("Generation error: \(error)")
}
Show responses as they generate for better UX.
@Generable
struct StoryIdea {
var title: String
@Guide(description: "A brief plot summary")
var plot: String
@Guide(description: "Main characters", .count(2...4))
var characters: [String]
}
struct StreamingView: View {
@State private var partial: StoryIdea.PartiallyGenerated?
@State private var isGenerating = false
var body: some View {
VStack(alignment: .leading) {
if let partial {
if let title = partial.title {
Text(title).font(.headline)
}
if let plot = partial.plot {
Text(plot)
}
if let characters = partial.characters {
ForEach(characters, id: \.self) { char in
Text("• \(char)")
}
}
}
Button("Generate Story Idea") {
Task { await generateStory() }
}
.disabled(isGenerating)
}
}
func generateStory() async {
isGenerating = true
defer { isGenerating = false }
let session = LanguageModelSession()
let stream = session.streamResponse(
to: "Create a sci-fi story idea",
generating: StoryIdea.self
)
for try await snapshot in stream {
partial = snapshot
}
}
}
Reuse sessions to maintain context.
class ChatViewModel: ObservableObject {
private var session: LanguageModelSession?
@Published var messages: [ChatMessage] = []
func startConversation() {
session = LanguageModelSession(instructions: """
You are a helpful assistant. Remember context from earlier in our conversation.
""")
}
func send(_ message: String) async throws {
guard let session else { return }
messages.append(ChatMessage(role: .user, content: message))
let response = try await session.respond(to: message)
messages.append(ChatMessage(role: .assistant, content: response.content))
}
}
do {
let response = try await session.respond(to: prompt)
} catch LanguageModelSession.GenerationError.exceededContextWindowSize {
// Context too large (>4,096 tokens)
// Solution: Start new session, break into smaller requests
} catch LanguageModelSession.GenerationError.cancelled {
// Request was cancelled
} catch {
print("Unexpected error: \(error)")
}
The model supports 4,096 tokens per session (~12,000-16,000 characters).
| Component | Typical Tokens |
|---|---|
| Instructions | 50-200 |
| User prompt | 50-500 |
| Tool descriptions | 50-100 each |
| Response | 100-1000 |
// Break content into chunks
func processLargeDocument(_ document: String) async throws -> [Summary] {
let chunks = document.split(every: 10000) // ~2500 tokens per chunk
var summaries: [Summary] = []
for chunk in chunks {
let session = LanguageModelSession() // New session per chunk
let summary = try await session.respond(
to: "Summarize this section: \(chunk)",
generating: Summary.self
)
summaries.append(summary.content)
}
return summaries
}
let options = GenerationOptions(
temperature: 0.7 // 0.0 = deterministic, 2.0 = creative
)
let response = try await session.respond(
to: prompt,
options: options
)
| Temperature | Use Case |
|---|---|
| 0.0-0.3 | Factual extraction, data processing |
| 0.5-0.7 | Balanced creativity and accuracy |
| 1.0-2.0 | Creative writing, brainstorming |
@Generable
struct EventDetails {
var title: String
var date: String?
var time: String?
var location: String?
var attendees: [String]
}
let session = LanguageModelSession(instructions: """
Extract event details from text. Use nil for missing information.
""")
let event = try await session.respond(
to: "Extract: Team lunch next Friday at noon in Conference Room B with John and Sarah",
generating: EventDetails.self
)
let session = LanguageModelSession(instructions: """
Summarize text concisely. Focus on key points and actionable items.
Maximum 3 bullet points.
""")
let response = try await session.respond(
to: "Summarize this email: \(longEmail)"
)
@Generable
struct Classification {
@Guide(description: "Category", .options(["Bug", "Feature", "Question", "Other"]))
var category: String
@Guide(description: "Priority", .options(["Low", "Medium", "High"]))
var priority: String
@Guide(description: "Brief summary")
var summary: String
}
let result = try await session.respond(
to: "Classify this support ticket: \(ticketText)",
generating: Classification.self
)
Before shipping:
App Store optimization skills for descriptions, screenshots, keywords, and review responses. Use when user needs help with App Store presence, ASO, or customer communication.
Apple Intelligence skills for on-device AI features including Foundation Models, Visual Intelligence, and intelligent assistants. Use when implementing AI-powered features.
Use when fixing VoiceOver issues, Dynamic Type violations, color contrast failures, touch target problems, keyboard navigation gaps, or Reduce Motion support - comprehensive accessibility diagnostics with WCAG compliance, Accessibility Inspector workflows, and App Store Review preparation for iOS/macOS
Use when structuring app entry points, managing authentication flows, switching root views, handling scene lifecycle, or asking 'how do I structure my @main', 'where does auth state live', 'how do I prevent screen flicker on launch', 'when should I modularize' - app-level composition patterns for iOS 26+
Use when making app surface in Spotlight search, Siri suggestions, or system experiences - covers the 6-step strategy combining App Intents, App Shortcuts, Core Spotlight, and NSUserActivity to feed the system metadata for iOS 16+
Use when integrating App Intents for Siri, Apple Intelligence, Shortcuts, Spotlight, or system experiences - covers AppIntent, AppEntity, parameter handling, entity queries, background execution, authentication, and debugging common integration issues for iOS 16+