Repository Public License
1import Foundation2#if canImport(FoundationModels)3import FoundationModels4#endif56/// Entry point to Apple's on-device system language model.7///8/// The FoundationModels framework exists in the SDK this package is built with (Xcode 27.2: macOS 26+, iOS 26+).9/// The package still deploys to macOS 15 / iOS 18, so the runtime is created only behind an availability check, and10/// whether the model can actually be used (eligible hardware, Apple Intelligence switched on, model downloaded) is11/// asked from the system at run time and reported as it is.12public enum AppleOnDeviceModel {13 /// The runtime, or `nil` when this build or this OS version does not have the framework.14 public static func makeRuntime() -> (any LocalModelRuntime)? {15 #if canImport(FoundationModels)16 if #available(macOS 26.0, iOS 26.0, visionOS 26.0, *) { return FoundationModelsRuntime() }17 #endif18 return nil19 }2021 /// Why `makeRuntime()` returns `nil`; `nil` when it returns a runtime.22 public static var unavailableReason: String? {23 #if canImport(FoundationModels)24 if #available(macOS 26.0, iOS 26.0, visionOS 26.0, *) { return nil }25 return "Apple's on-device model needs macOS 26, iOS 26 or later."26 #else27 return "This build does not include Apple's on-device model framework."28 #endif29 }30}3132#if canImport(FoundationModels)33/// `LocalModelRuntime` over `SystemLanguageModel`.34///35/// Limits, stated rather than hidden: text only (no images); no tool calling (the framework runs tools itself from36/// compile-time `Tool` types and does not hand calls back to the caller, so a request with tools is refused); no37/// token usage (the framework reports none); a small context window managed by the system.38@available(macOS 26.0, iOS 26.0, visionOS 26.0, *)39struct FoundationModelsRuntime: LocalModelRuntime {40 let id = LocalRuntimeIdentifier.appleFoundationModels41 let displayName = "Apple Intelligence"4243 func availability() async -> LocalRuntimeAvailability {44 switch SystemLanguageModel.default.availability {45 case .available: return .available46 case .unavailable(.deviceNotEligible): return .unavailable(reason: "This device does not support Apple Intelligence.")47 case .unavailable(.appleIntelligenceNotEnabled): return .unavailable(reason: "Apple Intelligence is turned off in System Settings.")48 case .unavailable(.modelNotReady): return .unavailable(reason: "The on-device model is still downloading or preparing. Try again later.")49 case .unavailable: return .unavailable(reason: "The on-device model is not available right now.")50 }51 }5253 func availableModels() async throws -> [LocalModelDescriptor] {54 guard case .available = await availability() else { return [] }55 return [LocalModelDescriptor(id: LocalModelIdentifier.appleSystemModel, displayName: "Apple on-device model", supportsTools: false, supportsImages: false)]56 }5758 /// The system owns the model's memory; the app has no figure to report.59 func memoryRequirement(for modelID: String) async -> UInt64? { nil }6061 func load(modelID: String) async throws {62 guard modelID == LocalModelIdentifier.appleSystemModel else { throw ProviderError.modelNotFound(model: modelID) }63 if case .unavailable(let reason) = await availability() { throw ProviderError.local(reason) }64 }6566 func unload(modelID: String) async {}6768 func generate(_ request: ChatRequest) -> AsyncThrowingStream<ChatEvent, Error> {69 AsyncThrowingStream(bufferingPolicy: .unbounded) { continuation in70 let task = Task {71 do {72 guard request.tools.isEmpty else { throw ProviderError.unsupported("The Apple on-device model cannot call the browser's tools. Choose another provider for agent tasks.") }73 guard !request.conversation.contains(where: { !$0.images.isEmpty }) else {74 throw ProviderError.unsupported("The Apple on-device model cannot read images.")75 }76 let session = LanguageModelSession(model: .default, instructions: request.combinedSystem)77 let options = FoundationModels.GenerationOptions(temperature: request.options.temperature, maximumResponseTokens: request.options.maxOutputTokens)78 continuation.yield(.started(ResponseStart(model: LocalModelIdentifier.appleSystemModel)))79 // Snapshots carry the whole text so far; the neutral stream carries deltas.80 var emitted = ""81 for try await snapshot in session.streamResponse(to: Self.prompt(request.conversation), options: options) {82 let text = snapshot.content83 guard text.count > emitted.count, text.hasPrefix(emitted) else { continue }84 continuation.yield(.textDelta(String(text.dropFirst(emitted.count))))85 emitted = text86 }87 try Task.checkCancellation()88 continuation.yield(.finished(.endOfTurn))89 continuation.finish()90 } catch let error as LanguageModelSession.GenerationError {91 switch error {92 case .exceededContextWindowSize: continuation.finish(throwing: ProviderError.contextTooLong("The on-device model's context window is too small for this request."))93 case .guardrailViolation: continuation.finish(throwing: ProviderError.contentFiltered("The on-device model declined this request."))94 case .unsupportedLanguageOrLocale: continuation.finish(throwing: ProviderError.local("The on-device model does not support this language."))95 case .assetsUnavailable: continuation.finish(throwing: ProviderError.local("The on-device model is not ready. Try again later."))96 default: continuation.finish(throwing: ProviderError.local("The on-device model could not answer."))97 }98 } catch {99 continuation.finish(throwing: ProviderError.wrap(error))100 }101 }102 continuation.onTermination = { _ in task.cancel() }103 }104 }105106 /// A session is created per request, so earlier turns are given to the model as a labelled transcript.107 static func prompt(_ messages: [ChatMessage]) -> String {108 guard messages.count > 1 else { return messages.first?.text ?? "" }109 let lines = messages.map { message -> String in110 switch message.role {111 case .assistant: "Assistant: \(message.text)"112 case .tool: "Tool result: \(message.text)"113 case .user, .system: "User: \(message.text)"114 }115 }116 return lines.joined(separator: "\n\n") + "\n\nAssistant:"117 }118}119#endif120