SPB Git

Repository Public

OnDeviceProviders.swift 7.4 KB 147 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Docs9// File             : Packages/ORIXDocsAI/Sources/DocLocalModels/OnDeviceProviders.swift10// Description      : The two on-device providers of ORIX Docs 2 and how they11//                    join the provider hub: Apple Intelligence (the system12//                    language model through the FoundationModels framework,13//                    macOS 26 or later) and MLX models from the local library.14//                    The Apple adapter is ORIX Astra's15//                    `AppleFoundationProvider` (availability-checked, `#if16//                    canImport(FoundationModels)`): it declares text only, the17//                    context size the system reports, no tool calling and no18//                    images, and it has no code path to any server: when the19//                    system model is unavailable the request fails with the20//                    reason, it is never rerouted.21// Module           : DocLocalModels22// Repository       : https://git.spboucher.ai/orix-docs23// Created          : 2026-11-2224// Last Modified    : 2026-11-2225//26// =============================================================================27// AUTHOR & PROFESSIONAL AFFILIATION28// =============================================================================29//30// Author           : Simon-Pierre Boucher31// Position         : Professor of Finance32// Institution      : Université du Québec en Outaouais (UQO)33// Department       : Département des sciences administratives34// Organization     : SP Boucher35//36// Website          : https://spboucher.ai37// Git              : https://git.spboucher.ai38//39// =============================================================================40// OFFICIAL CONTACT DIRECTORY41// =============================================================================42//43// General          : info@spboucher.ai44// Professional     : contact@spboucher.ai45// Direct           : simon@spboucher.ai46// Research         : research@spboucher.ai47// Development      : dev@spboucher.ai48// Support          : support@spboucher.ai49// Security/Admin   : admin@spboucher.ai50// Notifications    : notifications@spboucher.ai51//52// Preferred Contact: support@spboucher.ai53//54// =============================================================================55// COPYRIGHT & INTELLECTUAL PROPERTY56// =============================================================================57//58// Copyright (c) 202659// Simon-Pierre Boucher60//61// All rights reserved where applicable.62//63// This file is governed by the applicable project license,64// copyright notices, institutional agreements and relevant law.65//66// Unless expressly authorized by the applicable license or67// rights holder, copying, redistribution, sublicensing,68// publication and commercial exploitation are not permitted.69//70// Existing third-party rights and notices remain unaffected.71//72// =============================================================================73// CONFIDENTIALITY & SECURITY74// =============================================================================75//76// Classification   : Public77// Distribution     : Public repository; use is governed by the project license78// Security Contact : admin@spboucher.ai79//80// Access to this source does not independently grant permission81// to redistribute or disclose confidential materials.82//83// Do not embed credentials, private keys, access tokens,84// certificates or confidential personal information.85//86// =============================================================================87// LICENSE & MAINTENANCE88// =============================================================================89//90// License          : None specified (no license file in this repository)91// Maintainer       : Simon-Pierre Boucher92// Technical Contact: dev@spboucher.ai93//94// =============================================================================95// END OF SP BOUCHER SOURCE HEADER96// =============================================================================9798import AstraCore99import AstraLocal100import DocAI101import Foundation102103public enum OnDeviceProviders {104    /// The Apple Intelligence adapter. `availability` is injectable for tests and previews.105    public static func appleIntelligence(availability: @escaping @Sendable () -> AppleFoundationAvailability = { .current() }) -> AppleFoundationProvider {106        AppleFoundationProvider(availability: availability)107    }108109    /// Why Apple Intelligence can or cannot be used on this Mac right now (device not eligible, turned off, model not ready, OS too old).110    public static var appleIntelligenceAvailability: AppleFoundationAvailability { .current() }111112    /// What the app may claim about the system model. Deliberately narrow: text in, text out, a small context window.113    /// Tool calling and image input exist in the framework but are not wired or verified in this adapter, so they are not claimed.114    public static func appleIntelligenceCapabilities() async -> ModelCapabilities? {115        (try? await appleIntelligence().listModels())?.first.map(ModelCapabilities.init)116    }117118    /// Registers Apple Intelligence and, when a library is given, the MLX provider in the hub, then records their state119    /// (`verified` or `unavailable` with the reason) and their model lists.120    public static func register(in hub: ProviderHub, library: LocalModelLibrary?,121                                appleAvailability: @escaping @Sendable () -> AppleFoundationAvailability = { .current() }) async {122        await hub.registerOnDeviceProvider(appleIntelligence(availability: appleAvailability))123        if let library { await hub.registerOnDeviceProvider(library.chatProvider) }124        for kind in [ProviderKind.appleFoundation, .mlx] {125            let id = ProviderID(kind)126            guard (try? await hub.verify(id)) != nil else { continue }127            _ = try? await hub.models(for: id, refresh: true)128        }129    }130131    /// Apple Intelligence as a router candidate; unavailable (with the system's reason) when it cannot be used.132    /// Size class `small`: it is offered for short editing tasks, not for complex multi-step work.133    public static func appleRouteCandidate(availability: AppleFoundationAvailability = .current(), contextLength: Int? = nil) async -> RouteCandidate {134        let listed = availability.isAvailable ? (try? await appleIntelligence(availability: { availability }).listModels())?.first : nil135        let info = listed ?? ModelInfo(ref: AppleFoundationProvider.modelRef, displayName: "Apple Intelligence", contextLength: contextLength,136                                       capabilities: [.text], source: .runtime, vendor: "Apple")137        return RouteCandidate(model: info, providerName: ProviderKind.appleFoundation.displayName, unavailableReason: availability.reason, tier: .small)138    }139140    /// Every on-device candidate for `ModelRouter`: installed MLX models and Apple Intelligence.141    public static func routeCandidates(library: LocalModelLibrary?) async -> [RouteCandidate] {142        var out = await library?.routeCandidates() ?? []143        out.append(await appleRouteCandidate())144        return out145    }146}147
Files main
Menu

Theme