Pocket How
System features

Foundation Models framework: on-device LLM sessions, @Generable and tools

iOS 26+, iPadOS 26+, macOS 26+. Intermediate. By Cihat Salik, .

Short answer

Check SystemLanguageModel.default.availability, create a LanguageModelSession with short instructions, and ask for a @Generable type instead of free text. Give the model a few Tool types for data it can't know. The on-device context is about 4K tokens, so keep sessions short. iOS 27 adds image attachments and an opt-in Private Cloud Compute model with a 32K context.

The problem

The Foundation Models framework (iOS 26) gives your app the language model behind Apple Intelligence, running on the device, with no API key, no per-token bill and no data leaving the phone. It is also a small model with a small context window, and it is missing on devices without Apple Intelligence or with it turned off. Features built as “send a long prompt, parse the text” fail on all three counts. Features built as short, typed requests with a fallback UI work well.

Check availability first

Every entry point starts with SystemLanguageModel.default.availability. It is either .available or .unavailable with a reason.

import FoundationModels
import SwiftUI

struct SmartSummaryButton: View {
    private let model = SystemLanguageModel.default

    var body: some View {
        switch model.availability {
        case .available:
            SummaryView()
        case .unavailable(.appleIntelligenceNotEnabled):
            Text("Turn on Apple Intelligence in Settings to use summaries.")
        case .unavailable(.modelNotReady):
            Text("The model is still downloading. Try again later.")
        case .unavailable(.deviceNotEligible):
            EmptyView()
        case .unavailable:
            EmptyView()
        }
    }
}

SummaryView is your feature view. On an ineligible device, hide the feature entirely; telling someone to buy a new phone is not a message they want. Mohammad Azam’s guide on AzamSharp makes the same point: decide the fallback UI before writing the prompt.

In Xcode, the scheme’s Run options include a simulated Foundation Models availability setting, so you can test each branch without changing devices.

Run a session

A LanguageModelSession keeps a transcript of the conversation. Every prompt and response stays in it and counts toward the context window. Instructions set the model’s role and are trusted; prompts carry the user’s content.

import FoundationModels

@MainActor
@Observable
final class NoteSummarizer {
    private(set) var summary = ""
    private(set) var failure: String?

    private let session = LanguageModelSession(
        instructions: "You summarize personal notes in two plain sentences. Never add facts."
    )

    func prepare() {
        session.prewarm()
    }

    func summarize(_ note: String) async {
        do {
            let response = try await session.respond(to: note)
            summary = response.content
        } catch {
            failure = error.localizedDescription
        }
    }
}

prewarm() loads the model before the person taps, which removes most of the first-response delay. Azam suggests calling it as soon as the person is likely to use the feature, for example when the screen appears.

A session handles one request at a time. A second call while isResponding is true throws a concurrent-request error, so disable the button while a response is in flight.

Keep instructions and user input apart. Instructions are where you say what the model may and may not do; putting user text there invites prompt injection.

Get typed output with @Generable

Asking for JSON in the prompt and decoding it is fragile. Guided generation is the framework’s answer: mark a type @Generable, describe fields with @Guide, and the framework constrains the model so the output always decodes into that type.

import FoundationModels

@Generable
struct TripPlan {
    @Guide(description: "A short, friendly title for the trip")
    var title: String

    @Guide(.count(3))
    var days: [DayPlan]
}

@Generable
struct DayPlan {
    var morning: String
    var afternoon: String

    @Guide(.range(1...5))
    var effort: Int
}
let session = LanguageModelSession(instructions: "You plan relaxed city trips.")
let plan = try await session.respond(
    to: "Three days in Lisbon in spring, with one rest day.",
    generating: TripPlan.self
).content

plan is a TripPlan. No parsing, no optional unwrapping of missing keys.

Majid Jabrayilov’s structured content post shows the same pattern with a recipe and stresses specific @Guide descriptions. Apple’s context window guide adds a counterweight: the type’s schema and every @Guide description are sent to the model and use tokens. Apple’s advice is to start without guides, use clear property names, and add guides only where the name is ambiguous or you need a constraint such as .range or .maximumCount. This article sides with Apple on cost: short descriptions, and only where they change the output.

Two more points from the community are worth knowing. Azam notes that the model fills every property, even ones your UI never shows, so a lean type is a fast type. And properties generate in declaration order, so put the field that others depend on (a title, a category) first.

Stream partial results

For anything longer than a sentence, stream. streamResponse yields snapshots whose content is the type’s PartiallyGenerated form, with every property optional until it arrives.

import FoundationModels

@MainActor
@Observable
final class TripPlanner {
    private(set) var draft: TripPlan.PartiallyGenerated?

    func plan(_ request: String) async throws {
        let session = LanguageModelSession(instructions: "You plan relaxed city trips.")
        let stream = session.streamResponse(to: request, generating: TripPlan.self)
        for try await snapshot in stream {
            draft = snapshot.content
        }
    }
}

SwiftUI views read draft?.title and draft?.days and fill in as text arrives. Give the list stable identity so rows don’t jump as later fields appear.

Give the model tools

The model knows nothing about your user’s data. A Tool lets it ask. The protocol (iOS 26, Sendable) needs a name, a description, an Arguments type the model fills in, and call(arguments:), whose output goes back into the conversation.

import FoundationModels

struct PantryTool: Tool {
    let name = "searchPantry"
    let description = "Looks up ingredients the person already has at home."

    @Generable
    struct Arguments {
        @Guide(description: "One ingredient name, singular")
        let ingredient: String
    }

    let pantry: PantryStore

    func call(arguments: Arguments) async throws -> String {
        let matches = await pantry.items(named: arguments.ingredient)
        return matches.isEmpty
            ? "None at home."
            : matches.map { "\($0.name): \($0.quantity)" }.joined(separator: ", ")
    }
}

PantryStore is an actor in your app. Register tools on the session:

let session = LanguageModelSession(
    tools: [PantryTool(pantry: pantryStore)],
    instructions: "Suggest dinners. Use searchPantry to check what the person has before suggesting."
)

Apple gives specific limits in the context window guide: keep tool descriptions to short phrases, give the model no more than three to five tools per request, and skip tools when the data is always needed. If every request needs the pantry, read it yourself and put it in the prompt. Tools are for decisions the model makes.

Live inside the context window

Apple documents the on-device context window as 4,096 tokens per session, covering instructions, prompts, tool definitions and outputs, schemas and responses. A token is about three to four characters in English and about one character in Chinese, Japanese, Korean or Vietnamese. When the session is full it throws, and it will not answer again.

import FoundationModels

func respondWithRecovery(_ session: LanguageModelSession, prompt: String) async throws -> (LanguageModelSession, String) {
    do {
        return (session, try await session.respond(to: prompt).content)
    } catch LanguageModelSession.GenerationError.exceededContextWindowSize {
        let entries = session.transcript
        let kept = [entries.first, entries.last].compactMap { $0 }
        let fresh = LanguageModelSession(transcript: Transcript(entries: kept))
        return (fresh, try await fresh.respond(to: prompt).content)
    }
}

Keeping the first entry preserves the instructions and the last keeps the latest turn, the approach Apple’s guide recommends. For long documents, Apple’s guide recommends splitting into chunks, summarizing each in a fresh session, and summarizing the summaries.

Starting with iOS 26.4, per Apple’s WWDC26 session What’s new in the Foundation Models framework, SystemLanguageModel has contextSize and tokenCount(for:), so you can measure a prompt before you send it. Read contextSize at runtime instead of hard-coding 4,096; the session’s own sample printed a larger number, so the size can differ between model versions. The Foundation Models instrument in Instruments shows token use per request, which is the fastest way to find a bloated schema.

Federico Viticci ran into this wall from the user side. In his MacStories notes on the Shortcuts Use Model action, both Apple models failed on 43 unread RSS items with context errors where a cloud model succeeded. Design for that limit from the start.

Errors you should handle

On the iOS 26 SDK, generation throws LanguageModelSession.GenerationError. The cases you will meet:

  • exceededContextWindowSize: start a new session, as above.
  • guardrailViolation: the safety system blocked the prompt or output. Show a neutral message; do not retry the same text in a loop.
  • unsupportedLanguageOrLocale: check SystemLanguageModel.default.supportedLanguages before offering the feature.
  • concurrentRequests: you called the session while it was responding.
  • rateLimited: back off, especially for work started from the background.

Apple’s documentation marks GenerationError deprecated in the 27 SDKs: apps built with Xcode 27 receive LanguageModelError (and model-specific errors) instead, with cases such as contextSizeExceeded. If you build with Xcode 27 and still support iOS 26, handle both behind one function.

Privacy

The on-device model runs locally and works offline, so prompts and responses stay on the device. You still owe people clarity. Say in the UI when text is generated, let people edit or discard it, and never present a generated answer as a fact from your service. Apple’s Private Cloud Compute model, below, keeps the same privacy model on the server side: Apple says prompts are not stored and independent researchers can verify that.

What changed in iOS 27

The WWDC26 session and Apple’s updated documentation list these additions. All need #available(iOS 27.0, *).

  • Image input. Attachment lets a prompt include a UIImage, CGImage, Core Image or Core Video buffer, or a file URL. Larger images cost more tokens and time. Majid’s multimodal post builds a plate scanner that returns a @Generable classification from a photo.
  • Private Cloud Compute. PrivateCloudComputeLanguageModel gives a 32K context and reasoning levels (.light, .moderate, .deep) through ContextOptions. Apple’s PCC guide says it needs a managed entitlement you request from Apple, a network connection, and a device that supports Apple Intelligence. People get a daily request limit, higher with iCloud+, and the model exposes quotaUsage so you can show where they stand.
  • A model protocol. LanguageModel is adopted by both Apple models, so a session takes either one with the same API.
  • Usage reporting. Responses report input, cached, output and reasoning token counts.
  • Built-in tools and dynamic profiles, plus watchOS 27 support, per the session.

Switching models is one line, with a fallback for older systems and offline use:

import FoundationModels

func makeSession(instructions: String) -> LanguageModelSession {
    if #available(iOS 27.0, *) {
        let cloud = PrivateCloudComputeLanguageModel()
        if case .available = cloud.availability {
            return LanguageModelSession(model: cloud, instructions: instructions)
        }
    }
    return LanguageModelSession(instructions: instructions)
}

Apple’s guidance is to start on-device, measure quality with the new Evaluations framework, and move to PCC only when the feature needs the context or reasoning. If a PCC request fails for lack of network, retry on the device model.

Checklist

Decision Recommendation
Device without Apple Intelligence Hide the feature, keep the app fully usable
Output your code reads @Generable type, not parsed text
Long output streamResponse with PartiallyGenerated
App data the model needs every time Put it in the prompt
App data the model sometimes needs A Tool, three to five at most
Long input Chunk across fresh sessions
Needs more than about 4K tokens PCC on iOS 27, with on-device fallback
Images Attachment on iOS 27

Version your prompts. Apple ships model updates with OS releases, and a prompt tuned for one version can drift on the next. Keep a small set of sample inputs and expected outputs, and run them after every OS update.

Sources and further reading

Read next