Repository Public License
1import Foundation23// MARK: - Identifiers45public enum LocalRuntimeIdentifier {6 /// Apple's on-device system language model (FoundationModels framework).7 public static let appleFoundationModels = "apple.foundation-models"8 /// The id an MLX runtime must use. No such runtime is part of this package: see `LocalModelRuntime`.9 public static let mlx = "mlx"10}1112public enum LocalModelIdentifier {13 public static let appleSystemModel = "apple.system-language-model"14}1516// MARK: - Device1718/// What this device can offer for on-device generation.19public struct DeviceCapability: Sendable, Hashable, Codable {20 public enum Platform: String, Sendable, Hashable, Codable {21 case macOS, iOS, iPadOS, visionOS, other22 }2324 public var physicalMemoryBytes: UInt6425 public var platform: Platform26 public var isSimulator: Bool2728 public init(physicalMemoryBytes: UInt64, platform: Platform, isSimulator: Bool = false) {29 self.physicalMemoryBytes = physicalMemoryBytes; self.platform = platform; self.isSimulator = isSimulator30 }3132 /// Devices sold as "8 GB" report slightly less than 8 GiB, hence a threshold below it. With less memory even a33 /// small quantised model leaves too little for the browser itself.34 public static let minimumMemoryBytes: UInt64 = 7_000_000_0003536 /// Whether local models are offered at all on this device.37 public var offersLocalModels: Bool { !isSimulator && physicalMemoryBytes >= Self.minimumMemoryBytes }3839 /// Why local models are not offered, for the UI. `nil` when they are.40 public var unavailabilityReason: String? {41 if isSimulator { return "On-device models are not available in the Simulator." }42 if physicalMemoryBytes < Self.minimumMemoryBytes {43 return "On-device models need a device with at least 8 GB of memory. This one has \(Self.gigabytes(physicalMemoryBytes))."44 }45 return nil46 }4748 /// The share of physical memory one model may claim. iOS and iPadOS terminate an app long before it reaches49 /// the physical total; macOS can swap but generation then becomes unusably slow.50 public var modelMemoryBudgetBytes: UInt64 {51 let share: Double = platform == .macOS ? 0.6 : 0.452 return UInt64(Double(physicalMemoryBytes) * share)53 }5455 /// Whether a model with this memory requirement may be loaded. `nil` means the runtime does not know (a model56 /// managed by the system): it is allowed whenever local models are offered.57 public func canLoad(memoryRequirementBytes: UInt64?) -> Bool {58 guard offersLocalModels else { return false }59 guard let memoryRequirementBytes else { return true }60 return memoryRequirementBytes <= modelMemoryBudgetBytes61 }6263 public static var current: DeviceCapability {64 let memory = ProcessInfo.processInfo.physicalMemory65 #if targetEnvironment(simulator)66 let simulator = true67 #else68 let simulator = false69 #endif70 #if os(macOS)71 return DeviceCapability(physicalMemoryBytes: memory, platform: .macOS, isSimulator: simulator)72 #elseif os(visionOS)73 return DeviceCapability(physicalMemoryBytes: memory, platform: .visionOS, isSimulator: simulator)74 #elseif os(iOS)75 // Read without UIKit: an iPad reports "iPad…" as its hardware model (and its simulator through the environment).76 var size = 077 sysctlbyname("hw.machine", nil, &size, nil, 0)78 var machine = [UInt8](repeating: 0, count: max(size, 1))79 sysctlbyname("hw.machine", &machine, &size, nil, 0)80 let name = ProcessInfo.processInfo.environment["SIMULATOR_MODEL_IDENTIFIER"] ?? String(decoding: machine.prefix { $0 != 0 }, as: UTF8.self)81 return DeviceCapability(physicalMemoryBytes: memory, platform: name.hasPrefix("iPad") ? .iPadOS : .iOS, isSimulator: simulator)82 #else83 return DeviceCapability(physicalMemoryBytes: memory, platform: .other, isSimulator: simulator)84 #endif85 }8687 static func gigabytes(_ bytes: UInt64) -> String { String(format: "%.1f GB", Double(bytes) / 1_073_741_824) }88}8990// MARK: - Runtime9192public struct LocalModelDescriptor: Sendable, Hashable, Codable, Identifiable {93 public var id: String94 public var displayName: String95 public var contextLength: Int?96 public var supportsTools: Bool97 public var supportsImages: Bool9899 public init(id: String, displayName: String, contextLength: Int? = nil, supportsTools: Bool = false, supportsImages: Bool = false) {100 self.id = id; self.displayName = displayName; self.contextLength = contextLength101 self.supportsTools = supportsTools; self.supportsImages = supportsImages102 }103}104105public enum LocalRuntimeAvailability: Sendable, Hashable {106 case available107 /// Not usable now; the reason is written for the user.108 case unavailable(reason: String)109}110111/// The seam between this package and an engine that runs a model on the device.112///113/// ProviderKit ships one implementation, over Apple's FoundationModels framework (`AppleOnDeviceModel`). An MLX114/// engine is deliberately not here: this package has no third-party dependency, and MLX is one. A separate optional115/// package (for example `NavigatorMLX`, depending on `mlx-swift` and on ProviderKit) implements this protocol with116/// `id == LocalRuntimeIdentifier.mlx`, and the app passes an instance to `ProviderRegistry`. Until one is passed,117/// `LocalCapabilityReport` says "MLX runtime not installed". What such a package has to do is described in118/// docs/AI_PROVIDERS.md.119public protocol LocalModelRuntime: Sendable {120 /// Stable identifier (`LocalRuntimeIdentifier`).121 var id: String { get }122 var displayName: String { get }123124 /// Whether the runtime can generate right now on this device.125 func availability() async -> LocalRuntimeAvailability126127 /// Models that are present on the device and ready to load. Never a catalogue of things that could be downloaded.128 func availableModels() async throws -> [LocalModelDescriptor]129130 /// Estimated resident memory needed to run `modelID`, in bytes: weights plus working memory at the model's131 /// context length. `nil` when the system manages the model and the app cannot know.132 func memoryRequirement(for modelID: String) async -> UInt64?133134 /// Loads the model into memory. Loading an already loaded model is not an error.135 func load(modelID: String) async throws136137 /// Releases the model's memory. Unloading a model that is not loaded is not an error.138 func unload(modelID: String) async139140 /// Generates one response. Emits `ChatEvent`s; `started` and `finished` are added by `LocalProvider` when the141 /// runtime does not send them. `usage` is emitted only if the engine really counts tokens. Terminating the142 /// stream must stop generation.143 func generate(_ request: ChatRequest) -> AsyncThrowingStream<ChatEvent, Error>144}145146// MARK: - Capability report147148/// What the settings screen shows under "On this device". Built from facts only: a runtime that was not handed to149/// the app is reported as not installed.150public struct LocalCapabilityReport: Sendable, Hashable {151 public struct RuntimeStatus: Sendable, Hashable, Identifiable {152 public var id: String153 public var displayName: String154 /// Whether an implementation of this runtime is linked into the app.155 public var isInstalled: Bool156 /// Whether it can generate now.157 public var isAvailable: Bool158 /// One sentence for the user.159 public var message: String160 }161162 public var device: DeviceCapability163 public var offersLocalModels: Bool164 /// Why local models are not offered on this device; `nil` when they are.165 public var deviceMessage: String?166 public var runtimes: [RuntimeStatus]167168 /// Whether at least one runtime can generate now.169 public var hasUsableRuntime: Bool { offersLocalModels && runtimes.contains { $0.isAvailable } }170171 public static let mlxNotInstalledMessage = "MLX runtime not installed"172173 /// Builds the report. The Apple and MLX rows are always present so the UI can say what is missing.174 public static func make(runtimes: [any LocalModelRuntime], device: DeviceCapability = .current) async -> LocalCapabilityReport {175 var rows: [RuntimeStatus] = []176 for runtime in runtimes {177 guard device.offersLocalModels else {178 rows.append(RuntimeStatus(id: runtime.id, displayName: runtime.displayName, isInstalled: true, isAvailable: false,179 message: device.unavailabilityReason ?? "Not available on this device."))180 continue181 }182 switch await runtime.availability() {183 case .available:184 rows.append(RuntimeStatus(id: runtime.id, displayName: runtime.displayName, isInstalled: true, isAvailable: true, message: "Ready."))185 case .unavailable(let reason):186 rows.append(RuntimeStatus(id: runtime.id, displayName: runtime.displayName, isInstalled: true, isAvailable: false, message: reason))187 }188 }189 if !rows.contains(where: { $0.id == LocalRuntimeIdentifier.appleFoundationModels }) {190 rows.insert(RuntimeStatus(id: LocalRuntimeIdentifier.appleFoundationModels, displayName: "Apple Intelligence", isInstalled: false,191 isAvailable: false, message: AppleOnDeviceModel.unavailableReason ?? "Apple on-device model runtime not registered."), at: 0)192 }193 if !rows.contains(where: { $0.id == LocalRuntimeIdentifier.mlx }) {194 rows.append(RuntimeStatus(id: LocalRuntimeIdentifier.mlx, displayName: "MLX", isInstalled: false, isAvailable: false, message: mlxNotInstalledMessage))195 }196 return LocalCapabilityReport(device: device, offersLocalModels: device.offersLocalModels, deviceMessage: device.unavailabilityReason, runtimes: rows)197 }198}199200// MARK: - Provider201202/// A `ChatProvider` over a `LocalModelRuntime`. Nothing leaves the device.203public struct LocalProvider: ChatProvider {204 public let family: ProviderFamily = .local205 private let runtime: any LocalModelRuntime206 private let device: DeviceCapability207208 public init(runtime: any LocalModelRuntime, device: DeviceCapability = .current) {209 self.runtime = runtime; self.device = device210 }211212 /// Throws unless the device offers local models and the runtime is available.213 private func checkAvailable() async throws {214 if let reason = device.unavailabilityReason { throw ProviderError.local(reason) }215 if case .unavailable(let reason) = await runtime.availability() { throw ProviderError.local(reason) }216 }217218 public func listModels() async throws -> [ModelInfo] {219 try await checkAvailable()220 return try await runtime.availableModels().map {221 ModelInfo(id: $0.id, displayName: $0.displayName, contextLength: $0.contextLength, supportsTools: $0.supportsTools, supportsImages: $0.supportsImages)222 }223 }224225 public func testConnection() async throws -> ConnectionReport {226 let started = Date()227 let models = try await listModels()228 return ConnectionReport(family: family, summary: "\(runtime.displayName) is ready. \(models.count) on-device model\(models.count == 1 ? "" : "s").",229 modelCount: models.count, latencyMilliseconds: Int(Date().timeIntervalSince(started) * 1_000))230 }231232 public func stream(_ request: ChatRequest) -> AsyncThrowingStream<ChatEvent, Error> {233 let runtime = runtime, device = device234 return makeEventStream(secrets: SecretBox()) { continuation in235 if let reason = device.unavailabilityReason { throw ProviderError.local(reason) }236 if case .unavailable(let reason) = await runtime.availability() { throw ProviderError.local(reason) }237 let requirement = await runtime.memoryRequirement(for: request.model)238 guard device.canLoad(memoryRequirementBytes: requirement) else {239 throw ProviderError.local("“\(request.model)” needs about \(DeviceCapability.gigabytes(requirement ?? 0)) of memory; this device can give a model \(DeviceCapability.gigabytes(device.modelMemoryBudgetBytes)).")240 }241 try await runtime.load(modelID: request.model)242 var started = false, finished = false243 for try await event in runtime.generate(request) {244 if case .started = event { started = true } else if !started { started = true; continuation.yield(.started(ResponseStart(model: request.model))) }245 if case .finished = event { finished = true }246 continuation.yield(event)247 }248 try Task.checkCancellation()249 if !started { continuation.yield(.started(ResponseStart(model: request.model))) }250 if !finished { continuation.yield(.finished(.unknown)) }251 }252 }253}254