Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Docs9// File : Packages/ORIXDocsAI/Sources/DocAI/ModelRouter.swift10// Description : Chooses the model for one task. A pure function of its11// inputs (mode, task, candidates, available memory, user12// restrictions): no clock, no I/O, no randomness, so the13// same inputs always give the same choice, the same reason14// and the same list of rejected candidates. Local Only and15// Privacy First draw their choice from on-device candidates16// only; a cloud model cannot come out of them by17// construction.18// Module : DocAI19// Repository : https://git.spboucher.ai/orix-docs20// Created : 2026-11-2221// Last Modified : 2026-11-2222//23// =============================================================================24// AUTHOR & PROFESSIONAL AFFILIATION25// =============================================================================26//27// Author : Simon-Pierre Boucher28// Position : Professor of Finance29// Institution : Université du Québec en Outaouais (UQO)30// Department : Département des sciences administratives31// Organization : SP Boucher32//33// Website : https://spboucher.ai34// Git : https://git.spboucher.ai35//36// =============================================================================37// OFFICIAL CONTACT DIRECTORY38// =============================================================================39//40// General : info@spboucher.ai41// Professional : contact@spboucher.ai42// Direct : simon@spboucher.ai43// Research : research@spboucher.ai44// Development : dev@spboucher.ai45// Support : support@spboucher.ai46// Security/Admin : admin@spboucher.ai47// Notifications : notifications@spboucher.ai48//49// Preferred Contact: support@spboucher.ai50//51// =============================================================================52// COPYRIGHT & INTELLECTUAL PROPERTY53// =============================================================================54//55// Copyright (c) 202656// Simon-Pierre Boucher57//58// All rights reserved where applicable.59//60// This file is governed by the applicable project license,61// copyright notices, institutional agreements and relevant law.62//63// Unless expressly authorized by the applicable license or64// rights holder, copying, redistribution, sublicensing,65// publication and commercial exploitation are not permitted.66//67// Existing third-party rights and notices remain unaffected.68//69// =============================================================================70// CONFIDENTIALITY & SECURITY71// =============================================================================72//73// Classification : Public74// Distribution : Public repository; use is governed by the project license75// Security Contact : admin@spboucher.ai76//77// Access to this source does not independently grant permission78// to redistribute or disclose confidential materials.79//80// Do not embed credentials, private keys, access tokens,81// certificates or confidential personal information.82//83// =============================================================================84// LICENSE & MAINTENANCE85// =============================================================================86//87// License : None specified (no license file in this repository)88// Maintainer : Simon-Pierre Boucher89// Technical Contact: dev@spboucher.ai90//91// =============================================================================92// END OF SP BOUCHER SOURCE HEADER93// =============================================================================9495import AstraCore96import Foundation9798public enum RoutingMode: String, Sendable, Hashable, Codable, CaseIterable, Identifiable {99 /// The model the user picked, or nothing: never a substitute.100 case manual101 /// On-device models only, the most capable one that fits.102 case localOnly103 /// On-device models only, preferring what is already in memory, then the system model: nothing new is loaded if avoidable.104 case privacyFirst105 /// The fastest model (measured tokens per second) among those that can do the task.106 case fastestCompatible107 /// The cheapest model for this task at published prices; on-device models cost nothing.108 case lowestEstimatedCost109 /// The most capable model that can do the task, wherever it runs.110 case bestAvailableCapability111 /// A cloud model when one can do the task and the restrictions allow it; an on-device model otherwise.112 case cloudPreferred113114 public var id: String { rawValue }115 public var title: String {116 switch self {117 case .manual: "Manual"118 case .localOnly: "Local Only"119 case .privacyFirst: "Privacy First"120 case .fastestCompatible: "Fastest Compatible"121 case .lowestEstimatedCost: "Lowest Estimated Cost"122 case .bestAvailableCapability: "Best Available Capability"123 case .cloudPreferred: "Cloud Preferred"124 }125 }126 /// True for the modes that never leave this Mac, whatever the candidates and the restrictions are.127 public var isOnDeviceOnly: Bool { self == .localOnly || self == .privacyFirst }128}129130/// Rough size class of a model, used to keep small models away from hard tasks. nil on a candidate = unknown (never a reason to reject).131public enum ModelTier: Int, Sendable, Hashable, Codable, Comparable, CaseIterable {132 case small = 0, medium = 1, large = 2133 public static func < (a: ModelTier, b: ModelTier) -> Bool { a.rawValue < b.rawValue }134 /// On-device models by parameter count: under 2 billion small, under 8 billion medium, larger large.135 public static func forParameters(_ count: Int64?) -> ModelTier? {136 guard let count, count > 0 else { return nil }137 return count < 2_000_000_000 ? .small : count < 8_000_000_000 ? .medium : .large138 }139}140141public enum TaskComplexity: String, Sendable, Hashable, Codable, CaseIterable {142 /// Rephrase a sentence, fix spelling, give a title.143 case simple144 /// Summarise a section, rewrite in another register, translate.145 case moderate146 /// Restructure a long document, multi-step agent work, careful reasoning.147 case complex148 var minimumTier: ModelTier {149 switch self { case .simple: .small; case .moderate: .small; case .complex: .medium }150 }151}152153/// What the task needs. Token figures are estimates made by the caller (ORIX Astra's `TokenEstimator`).154public struct TaskDescriptor: Sendable, Hashable, Codable {155 public var needsTools: Bool156 public var needsStructuredOutput: Bool157 public var needsVision: Bool158 /// Prompt size: instructions, document excerpt, conversation.159 public var estimatedInputTokens: Int160 /// Room the answer needs.161 public var expectedOutputTokens: Int162 /// BCP 47 language of the text ("fr-CA", "en"); nil = unknown.163 public var language: String?164 public var complexity: TaskComplexity165 /// True when the prompt carries text of the user's document.166 public var containsDocumentContent: Bool167 public init(needsTools: Bool = false, needsStructuredOutput: Bool = false, needsVision: Bool = false, estimatedInputTokens: Int = 0,168 expectedOutputTokens: Int = 512, language: String? = nil, complexity: TaskComplexity = .moderate, containsDocumentContent: Bool = true) {169 self.needsTools = needsTools; self.needsStructuredOutput = needsStructuredOutput; self.needsVision = needsVision170 self.estimatedInputTokens = max(0, estimatedInputTokens); self.expectedOutputTokens = max(0, expectedOutputTokens)171 self.language = language; self.complexity = complexity; self.containsDocumentContent = containsDocumentContent172 }173 public var totalTokens: Int {174 let (sum, overflow) = estimatedInputTokens.addingReportingOverflow(expectedOutputTokens)175 return overflow ? Int.max : sum176 }177}178179/// One model the router may choose, with what is known about it.180public struct RouteCandidate: Sendable, Hashable, Identifiable {181 public var model: ModelInfo182 /// Name shown for the provider ("Mistral", "My server", "On-device (MLX)").183 public var providerName: String184 /// Non-nil when the model cannot be used right now (no key, not installed, system model off); the sentence says why.185 public var unavailableReason: String?186 /// Measured on this Mac (on-device) or over past requests (cloud); nil = never measured.187 public var tokensPerSecond: Double?188 public var timeToFirstToken: TimeInterval?189 /// On-device models: memory the model needs to load (weights + context cache + runtime), as estimated by the memory governor.190 public var requiredMemoryBytes: Int64?191 /// On-device models already in memory: they need no further memory and answer without a load.192 public var isLoaded: Bool193 public var tier: ModelTier?194 /// Primary language subtags the model handles ("en", "fr"); nil = not restricted (multilingual or unknown).195 public var languages: Set<String>?196197 public init(model: ModelInfo, providerName: String? = nil, unavailableReason: String? = nil, tokensPerSecond: Double? = nil,198 timeToFirstToken: TimeInterval? = nil, requiredMemoryBytes: Int64? = nil, isLoaded: Bool = false, tier: ModelTier? = nil,199 languages: Set<String>? = nil) {200 self.model = model; self.providerName = providerName ?? model.ref.provider.displayName; self.unavailableReason = unavailableReason201 self.tokensPerSecond = tokensPerSecond; self.timeToFirstToken = timeToFirstToken; self.requiredMemoryBytes = requiredMemoryBytes202 self.isLoaded = isLoaded; self.tier = tier; self.languages = languages203 }204 public var id: String { model.ref.id }205 public var ref: ModelRef { model.ref }206 /// On this Mac, in the strict sense: MLX or the Apple system model. A custom endpoint is never on-device for the router, even on207 /// localhost: the router cannot know what a local server forwards to.208 public var isOnDevice: Bool { model.ref.provider.isLocal }209}210211/// Limits set by the user. They apply in every mode, Manual included.212public struct RoutingRestrictions: Sendable, Hashable, Codable {213 /// False = on-device models only, in every mode.214 public var allowCloud: Bool215 /// True = a task that carries document content is never given to a cloud model.216 public var neverSendDocumentContentToCloud: Bool217 public var blockedProviders: Set<ProviderID>218 /// Highest estimated cost accepted for one request, in US dollars; nil = no limit. A cloud model without a published price219 /// cannot be shown to respect the limit and is rejected when one is set.220 public var maxEstimatedCostUSD: Double?221 public init(allowCloud: Bool = true, neverSendDocumentContentToCloud: Bool = false, blockedProviders: Set<ProviderID> = [],222 maxEstimatedCostUSD: Double? = nil) {223 self.allowCloud = allowCloud; self.neverSendDocumentContentToCloud = neverSendDocumentContentToCloud224 self.blockedProviders = blockedProviders; self.maxEstimatedCostUSD = maxEstimatedCostUSD225 }226 public static let none = RoutingRestrictions()227 /// The restrictions equivalent to a hub data policy.228 public init(_ policy: DataPolicy) {229 self.init(allowCloud: policy.allowCloud, neverSendDocumentContentToCloud: !policy.allowDocumentContentInCloud)230 }231}232233public struct RoutingRequest: Sendable, Hashable {234 public var mode: RoutingMode235 public var task: TaskDescriptor236 public var candidates: [RouteCandidate]237 /// Memory a newly loaded on-device model may use right now (the memory governor's budget); nil = unknown, not checked.238 public var availableMemoryBytes: Int64?239 public var restrictions: RoutingRestrictions240 /// Manual mode: the model the user picked.241 public var manualSelection: ModelRef?242 public init(mode: RoutingMode, task: TaskDescriptor, candidates: [RouteCandidate], availableMemoryBytes: Int64? = nil,243 restrictions: RoutingRestrictions = .none, manualSelection: ModelRef? = nil) {244 self.mode = mode; self.task = task; self.candidates = candidates; self.availableMemoryBytes = availableMemoryBytes245 self.restrictions = restrictions; self.manualSelection = manualSelection246 }247}248249public enum ExecutionLocation: Sendable, Hashable, Codable {250 case onDevice251 /// The provider that receives the request ("Mistral", "OpenRouter", the name of a custom endpoint).252 case cloud(provider: String)253 public var isOnDevice: Bool { self == .onDevice }254 public var label: String {255 switch self { case .onDevice: "On this Mac"; case .cloud(let provider): provider }256 }257}258259public struct RoutingDecision: Sendable, Hashable {260 public enum RejectionCode: String, Sendable, Hashable, Codable, CaseIterable {261 case unavailable, modeIsOnDeviceOnly, cloudDisabled, documentContentRestricted, providerBlocked, noToolCalling, noStructuredOutput,262 noVision, contextTooSmall, contextUnknown, notEnoughMemory, languageNotSupported, tooSmallForTask, overCostLimit, costUnknown,263 notTheManualSelection264 }265 public struct Rejection: Sendable, Hashable, Identifiable {266 public var model: ModelRef267 public var code: RejectionCode268 public var reason: String269 public var id: String { model.id }270 }271 public var mode: RoutingMode272 /// nil when no candidate can do the task under the mode and the restrictions. The router never substitutes outside them.273 public var chosen: RouteCandidate?274 public var location: ExecutionLocation?275 /// One or two sentences for the user: why this model, or why none.276 public var reason: String277 /// Estimated cost of the task on the chosen model at published prices; nil when unknown. 0 on-device.278 public var estimatedCostUSD: Double?279 /// The other candidates that could have done the task, best first.280 public var alternatives: [ModelRef]281 /// Every candidate that was set aside, in the order of the input, each with the first reason that excluded it.282 public var rejected: [Rejection]283}284285public enum ModelRouter {286 /// Largest task accepted on a model whose context length is unknown.287 public static let unknownContextAllowance = 4_096288289 /// Cost of `task` on `candidate` at its published price. 0 on-device; nil when no price is known.290 public static func estimatedCost(of task: TaskDescriptor, on candidate: RouteCandidate) -> Double? {291 if candidate.isOnDevice { return 0 }292 guard let p = candidate.model.pricing else { return nil }293 return (Double(task.estimatedInputTokens) * p.inputPerMTok + Double(task.expectedOutputTokens) * p.outputPerMTok) / 1_000_000294 }295296 /// Capability score used to compare candidates that can all do the task. Built only from declared facts.297 static func capabilityScore(_ c: RouteCandidate, task: TaskDescriptor) -> Double {298 var score = Double((c.tier ?? .medium).rawValue) * 100299 if c.model.capabilities.contains(.reasoning) { score += task.complexity == .complex ? 40 : 15 }300 if c.model.capabilities.contains(.tools) { score += 10 }301 if c.model.capabilities.contains(.structuredOutput) { score += 5 }302 if c.model.capabilities.contains(.vision) { score += 5 }303 if let context = c.model.contextLength, context > 0 { score += min(30, log2(Double(context) / 1_024) * 3) }304 return score305 }306307 static func primaryLanguage(_ tag: String) -> String {308 String(tag.lowercased().split(whereSeparator: { $0 == "-" || $0 == "_" }).first ?? "")309 }310311 /// The first reason `c` cannot do the task under the restrictions, independent of the mode; nil when it can.312 static func hardRejection(_ c: RouteCandidate, _ r: RoutingRequest, enforceTier: Bool) -> (RoutingDecision.RejectionCode, String)? {313 let task = r.task, name = c.model.displayName314 if let why = c.unavailableReason { return (.unavailable, why) }315 if !c.isOnDevice {316 if !r.restrictions.allowCloud { return (.cloudDisabled, "Cloud models are turned off.") }317 if task.containsDocumentContent, r.restrictions.neverSendDocumentContentToCloud {318 return (.documentContentRestricted, "Document content may not be sent to a cloud model.")319 }320 }321 if r.restrictions.blockedProviders.contains(ProviderID(model: c.ref)) { return (.providerBlocked, "\(c.providerName) is blocked in the settings.") }322 if task.needsTools, !c.model.capabilities.contains(.tools) { return (.noToolCalling, "\(name) is not known to support tool calling.") }323 if task.needsStructuredOutput, !c.model.capabilities.contains(.structuredOutput) {324 return (.noStructuredOutput, "\(name) is not known to support structured output.")325 }326 if task.needsVision, !c.model.capabilities.contains(.vision) { return (.noVision, "\(name) does not read images.") }327 if let context = c.model.contextLength {328 if task.totalTokens > context {329 return (.contextTooSmall, "The task needs about \(task.totalTokens) tokens; \(name) has a context of \(context).")330 }331 } else if task.totalTokens > unknownContextAllowance {332 return (.contextUnknown, "The context length of \(name) is unknown and the task needs about \(task.totalTokens) tokens.")333 }334 if c.isOnDevice, !c.isLoaded, let need = c.requiredMemoryBytes, let available = r.availableMemoryBytes, need > available {335 return (.notEnoughMemory, "\(name) needs about \(formatBytes(need)); \(formatBytes(available)) can be used right now.")336 }337 if let language = task.language, let supported = c.languages, !supported.contains(primaryLanguage(language)) {338 return (.languageNotSupported, "\(name) is not meant for this language (\(language)).")339 }340 if enforceTier, let tier = c.tier, tier < task.complexity.minimumTier {341 return (.tooSmallForTask, "\(name) is too small for a complex task.")342 }343 if let limit = r.restrictions.maxEstimatedCostUSD, !c.isOnDevice {344 guard let cost = estimatedCost(of: task, on: c) else { return (.costUnknown, "\(name) has no published price, so the cost limit cannot be checked.") }345 if cost > limit { return (.overCostLimit, "Estimated cost \(CostEstimate.format(cost)) exceeds the limit of \(CostEstimate.format(limit)).") }346 }347 return nil348 }349350 static func formatBytes(_ bytes: Int64) -> String {351 let gb = Double(bytes) / 1_073_741_824352 return gb >= 1 ? String(format: "%.1f GB", gb) : String(format: "%.0f MB", Double(bytes) / 1_048_576)353 }354355 public static func route(_ request: RoutingRequest) -> RoutingDecision {356 let task = request.task, mode = request.mode357 var rejected: [RoutingDecision.Rejection] = []358 var eligible: [RouteCandidate] = []359 var seen = Set<String>()360361 for c in request.candidates {362 guard seen.insert(c.id).inserted else { continue } // the same model listed twice is considered once363 if mode == .manual {364 guard c.ref == request.manualSelection else {365 rejected.append(.init(model: c.ref, code: .notTheManualSelection, reason: "Manual mode uses only the model you picked.")); continue366 }367 }368 if mode.isOnDeviceOnly, !c.isOnDevice {369 rejected.append(.init(model: c.ref, code: .modeIsOnDeviceOnly, reason: "\(mode.title) uses on-device models only.")); continue370 }371 // A model the user picked by hand is not second-guessed on size; every other requirement still applies.372 if let (code, reason) = hardRejection(c, request, enforceTier: mode != .manual) {373 rejected.append(.init(model: c.ref, code: code, reason: reason)); continue374 }375 eligible.append(c)376 }377 // The guarantee of the on-device modes does not rest on the loop above alone.378 if mode.isOnDeviceOnly { eligible.removeAll { !$0.isOnDevice } }379380 let cost: (RouteCandidate) -> Double? = { estimatedCost(of: task, on: $0) }381 let capability: (RouteCandidate) -> Double = { capabilityScore($0, task: task) }382 /// Sort keys, compared in order; smaller is better. The model id closes every tie, so the order never depends on the input order.383 func keys(_ c: RouteCandidate) -> [Double] {384 let speed = -(c.tokensPerSecond ?? -1) // measured and fast first; unmeasured last385 let latency = c.timeToFirstToken ?? .greatestFiniteMagnitude386 let cap = -capability(c)387 let price = cost(c) ?? .greatestFiniteMagnitude // unknown price after every known one388 let loaded: Double = c.isLoaded ? 0 : 1389 let cloudFirst: Double = c.isOnDevice ? 1 : 0390 switch mode {391 case .manual: return [0]392 case .localOnly: return [cap, loaded, speed]393 case .privacyFirst:394 // Already in memory, then the system model (nothing to load or download), then the rest by capability.395 let system: Double = c.ref.provider == .appleFoundation ? 0 : 1396 return [loaded, system, cap, speed]397 case .fastestCompatible: return [speed, latency, cap]398 case .lowestEstimatedCost: return [price, cap, speed]399 case .bestAvailableCapability: return [cap, price, speed]400 case .cloudPreferred: return [cloudFirst, cap, price, speed]401 }402 }403 let ranked = eligible.map { ($0, keys($0)) }.sorted { a, b in404 for (x, y) in zip(a.1, b.1) where x != y { return x < y }405 return a.0.id < b.0.id406 }.map(\.0)407408 guard let chosen = ranked.first, !(mode.isOnDeviceOnly && !chosen.isOnDevice) else {409 return RoutingDecision(mode: mode, chosen: nil, location: nil, reason: noChoiceReason(request, rejected), estimatedCostUSD: nil,410 alternatives: [], rejected: rejected)411 }412 let location: ExecutionLocation = chosen.isOnDevice ? .onDevice : .cloud(provider: chosen.providerName)413 return RoutingDecision(mode: mode, chosen: chosen, location: location, reason: choiceReason(chosen, request, cost: cost(chosen), others: ranked.count - 1),414 estimatedCostUSD: cost(chosen), alternatives: ranked.dropFirst().map(\.ref), rejected: rejected)415 }416417 static func choiceReason(_ c: RouteCandidate, _ r: RoutingRequest, cost: Double?, others: Int) -> String {418 let name = c.model.displayName419 let place = c.isOnDevice ? "on this Mac" : "at \(c.providerName)"420 let price: String = c.isOnDevice ? "at no cost" : cost.map { "for an estimated \(CostEstimate.format($0))" } ?? "at a price that is not published"421 let speed = c.tokensPerSecond.map { String(format: "%.0f tokens per second measured", $0) }422 let among = others > 0 ? " among \(others + 1) models that can do this task" : ", the only model that can do this task"423 switch r.mode {424 case .manual: return "\(name) runs \(place): it is the model you picked."425 case .localOnly: return "\(name) runs on this Mac. Local Only never uses a cloud model; it is the most capable on-device model\(among)."426 case .privacyFirst:427 let why = c.isLoaded ? "it is already in memory" : c.ref.provider == .appleFoundation ? "it is the system model, with nothing to load" : "it is the most capable on-device model available"428 return "\(name) runs on this Mac. Privacy First never uses a cloud model; \(why)."429 case .fastestCompatible:430 return "\(name) runs \(place): " + (speed.map { "the fastest\(among) (\($0))." } ?? "no speed has been measured yet, so the most capable model was taken\(among).")431 case .lowestEstimatedCost: return "\(name) runs \(place) \(price): the cheapest\(among)."432 case .bestAvailableCapability: return "\(name) runs \(place) \(price): the most capable\(among)."433 case .cloudPreferred:434 return c.isOnDevice ? "\(name) runs on this Mac: no cloud model can do this task under the current restrictions."435 : "\(name) runs \(place) \(price): the most capable cloud model\(among)."436 }437 }438439 static func noChoiceReason(_ r: RoutingRequest, _ unordered: [RoutingDecision.Rejection]) -> String {440 // The example quoted in the sentence must not depend on the order the candidates were listed in.441 let rejected = unordered.sorted { $0.model.id < $1.model.id }442 if r.mode == .manual {443 guard let pick = r.manualSelection else { return "No model is selected. Pick a model, or choose another routing mode." }444 if let why = rejected.first(where: { $0.model == pick && $0.code != .notTheManualSelection }) { return "The model you picked cannot do this task: \(why.reason)" }445 return "The model you picked is not available any more. Pick another model."446 }447 if r.candidates.isEmpty { return "No model is set up yet. Add a provider key or download an on-device model." }448 if r.mode.isOnDeviceOnly {449 let local = rejected.filter { $0.model.provider.isLocal }450 if local.isEmpty { return "\(r.mode.title) uses on-device models only, and none is installed. Nothing was sent to the cloud." }451 return "No on-device model can do this task (\(local[0].reason)). \(r.mode.title) never falls back to the cloud."452 }453 // The most frequent reason tells the user what to change.454 let counts = Dictionary(grouping: rejected, by: \.code).mapValues(\.count)455 let top = counts.sorted { ($1.value, $0.key.rawValue) < ($0.value, $1.key.rawValue) }.first?.key456 let example = rejected.first { $0.code == top }?.reason ?? ""457 return "No model can do this task under the current settings. \(example)"458 }459}460