Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Core/Models/ModelQuery.swift3// Description: Filtering, searching and sorting of the model catalogue (direct models + OpenRouter), used by the picker and the Explorer.4import Foundation56public enum ModelSort: String, Sendable, CaseIterable, Hashable, Codable {7 case relevance, name, priceAscending, priceDescending, context, newest, recentlyUsed8 public var label: String {9 switch self {10 case .relevance: "Pertinence"; case .name: "Nom"; case .priceAscending: "Prix croissant"; case .priceDescending: "Prix décroissant"11 case .context: "Contexte"; case .newest: "Plus récents"; case .recentlyUsed: "Utilisés récemment"12 }13 }14}1516/// Criteria applied to the catalogue. Every criterion maps to a fact sent by the server (nothing is inferred).17public struct ModelQuery: Sendable, Equatable {18 public var text = ""19 public var makers: Set<String> = []20 /// `direct`, `local`, `openrouter`.21 public var routes: Set<String> = []22 /// Capability flags that must be `true` (`vision`, `tools`, `reasoning`, `audioInput`, `imageGeneration`, `structuredOutput`…).23 public var capabilities: Set<String> = []24 /// Server categories that must all be present (`coding`, `research`, `fast`, `long-context`…).25 public var categories: Set<String> = []26 /// Maximum input price, USD per million tokens.27 public var maxInputPrice: Double?28 public var minContext: Int?29 public var freeOnly = false30 public var openWeightOnly = false31 public var favoritesOnly = false32 /// Include models that cannot be picked for a conversation (image, speech, embedding…, unavailable or hidden ones).33 public var includeNonChat = false34 public var sort: ModelSort = .relevance35 public init() {}3637 public var hasFilters: Bool {38 !makers.isEmpty || !routes.isEmpty || !capabilities.isEmpty || !categories.isEmpty || maxInputPrice != nil || minContext != nil || freeOnly || openWeightOnly || favoritesOnly39 }40 public var activeFilterCount: Int {41 makers.count + routes.count + capabilities.count + categories.count + [maxInputPrice != nil, minContext != nil, freeOnly, openWeightOnly, favoritesOnly].filter { $0 }.count42 }43 public mutating func clearFilters() { let t = text, s = sort, n = includeNonChat; self = ModelQuery(); text = t; sort = s; includeNonChat = n }4445 public func matches(_ m: AIModel) -> Bool {46 if !includeNonChat, !m.isSelectableForChat || m.hidden { return false }47 if !makers.isEmpty, !makers.contains(m.creator) { return false }48 if !routes.isEmpty, !routes.contains(m.route) { return false }49 for c in capabilities where !m.has(c) { return false }50 for c in categories where !m.categories.contains(c) { return false }51 if let max = maxInputPrice { guard let p = m.inputPrice, p <= max else { return false } }52 if let min = minContext { guard let c = m.contextWindow, c >= min else { return false } }53 if freeOnly, !m.isFree { return false }54 if openWeightOnly, !m.isOpenWeight { return false }55 if favoritesOnly, !m.favorite { return false }56 return true57 }58}5960/// Pre-folded search keys for instant search over the whole catalogue (≈ 500 models): built once per catalogue load.61public struct ModelSearchIndex: Sendable {62 struct Entry: Sendable { let model: AIModel; let name: String; let haystack: String }63 private let entries: [Entry]64 public let count: Int6566 public init(_ models: [AIModel]) {67 entries = models.map { m in68 let name = Self.fold(m.displayName)69 return Entry(model: m, name: name, haystack: [name, Self.fold(m.id), Self.fold(m.creatorName), Self.fold(m.creator), Self.fold(m.catalog?.slug ?? "")].joined(separator: " "))70 }71 count = entries.count72 }7374 static func fold(_ s: String) -> String { s.folding(options: [.diacriticInsensitive, .caseInsensitive], locale: nil) }7576 /// Relevance of a model for the query words: nil = no match. Every word must appear; a prefix of the name ranks first.77 static func score(_ words: [String], _ e: Entry) -> Int? {78 var total = 079 for w in words {80 if e.name.hasPrefix(w) { total += 40 }81 else if e.name.range(of: " " + w) != nil || e.name.range(of: "-" + w) != nil { total += 25 }82 else if e.name.contains(w) { total += 15 }83 else if e.haystack.contains(w) { total += 6 }84 else { return nil }85 }86 return total87 }8889 public func search(_ query: ModelQuery) -> [AIModel] {90 let words = Self.fold(query.text).split(whereSeparator: { $0 == " " || $0 == "\t" }).map(String.init)91 var scored: [(model: AIModel, score: Int)] = []92 scored.reserveCapacity(entries.count)93 for e in entries where query.matches(e.model) {94 if words.isEmpty { scored.append((e.model, 0)) } else if let s = Self.score(words, e) { scored.append((e.model, s)) }95 }96 return Self.sorted(scored, by: query.sort, hasText: !words.isEmpty).map(\.model)97 }9899 /// Default order when nothing else decides: favourites, verified direct models, then by maker and name.100 static func baseline(_ a: AIModel, _ b: AIModel) -> Bool {101 // favourites, then verified direct models, then the local route, then the catalogue102 func rank(_ m: AIModel) -> Int { (m.favorite ? 0 : 4) + (m.isVerified ? 0 : (m.isLocal ? 1 : 2)) }103 let ra = rank(a), rb = rank(b)104 if ra != rb { return ra < rb }105 if a.creatorName != b.creatorName { return a.creatorName.localizedCaseInsensitiveCompare(b.creatorName) == .orderedAscending }106 let c = a.displayName.localizedStandardCompare(b.displayName)107 if c != .orderedSame { return c == .orderedAscending }108 return a.id < b.id109 }110111 static func sorted(_ items: [(model: AIModel, score: Int)], by sort: ModelSort, hasText: Bool) -> [(model: AIModel, score: Int)] {112 // unknown values (no price, no context, never used) always go last, whatever the direction113 func missingLast<T: Comparable>(_ a: T?, _ b: T?, ascending: Bool) -> Bool? {114 switch (a, b) {115 case (nil, nil): return nil116 case (nil, _): return false117 case (_, nil): return true118 case (let x?, let y?): return x == y ? nil : (ascending ? x < y : x > y)119 }120 }121 return items.sorted { l, r in122 let a = l.model, b = r.model123 switch sort {124 case .relevance: if hasText, l.score != r.score { return l.score > r.score }125 case .name:126 let c = a.displayName.localizedStandardCompare(b.displayName)127 if c != .orderedSame { return c == .orderedAscending }128 return a.id < b.id129 case .priceAscending: if let d = missingLast(a.blendedPrice, b.blendedPrice, ascending: true) { return d }130 case .priceDescending: if let d = missingLast(a.blendedPrice, b.blendedPrice, ascending: false) { return d }131 case .context: if let d = missingLast(a.contextWindow, b.contextWindow, ascending: false) { return d }132 case .newest: if let d = missingLast(a.publishedAt ?? a.lastVerifiedAt, b.publishedAt ?? b.lastVerifiedAt, ascending: false) { return d }133 case .recentlyUsed: if let d = missingLast(a.lastUsedAt, b.lastUsedAt, ascending: false) { return d }134 }135 return baseline(a, b)136 }137 }138}139140public extension Array where Element == AIModel {141 func applying(_ query: ModelQuery) -> [AIModel] { ModelSearchIndex(self).search(query) }142 /// Makers present in the list, most models first — the « maker » filter of the Explorer.143 var makers: [(slug: String, name: String, logo: String?, count: Int)] {144 var counts: [String: (name: String, logo: String?, count: Int)] = [:]145 for m in self { var e = counts[m.creator] ?? (m.creatorName, m.logo, 0); e.count += 1; if e.logo == nil { e.logo = m.logo }; counts[m.creator] = e }146 return counts.map { ($0.key, $0.value.name, $0.value.logo, $0.value.count) }.sorted { $0.count != $1.count ? $0.count > $1.count : $0.name < $1.name }147 }148 /// Models used most recently first (`lastUsedAt`), for the « récents » section.149 func recents(limit: Int = 6) -> [AIModel] {150 Array(filter { $0.lastUsedAt != nil && $0.isSelectableForChat && !$0.hidden }.sorted { ($0.lastUsedAt ?? .distantPast) > ($1.lastUsedAt ?? .distantPast) }.prefix(limit))151 }152}153154/// Category and capability labels shown in French (the rule behind each category comes from `GET /api/providers`).155public enum ModelFacet {156 public static let categories = ["reasoning", "vision", "multimodal", "long-context", "tools", "coding", "research", "creative-writing", "fast", "local", "open-weight", "free", "image-generation"]157 public static func label(_ category: String) -> String {158 switch category {159 case "reasoning": "Raisonnement"; case "vision": "Vision"; case "multimodal": "Multimodal"; case "long-context": "Long contexte"; case "open-weight": "Poids ouverts"; case "free": "Gratuit"160 case "image-generation": "Génération d'images"; case "tools": "Outils"; case "coding": "Code"; case "creative-writing": "Écriture créative"; case "research": "Recherche"; case "fast": "Rapide"; case "local": "Local"161 default: category.capitalized162 }163 }164 public static func symbol(_ category: String) -> String {165 switch category {166 case "reasoning": "brain"; case "vision": "eye"; case "multimodal": "waveform"; case "long-context": "text.justify.leading"; case "open-weight": "lock.open"; case "free": "gift"167 case "image-generation": "photo"; case "tools": "wrench.and.screwdriver"; case "coding": "chevron.left.forwardslash.chevron.right"; case "creative-writing": "pencil.and.outline"; case "research": "books.vertical"; case "fast": "bolt"; case "local": "desktopcomputer"168 default: "tag"169 }170 }171 public static let capabilities = ["vision", "tools", "reasoning", "audioInput", "imageGeneration", "structuredOutput", "longContext"]172 public static func capabilityLabel(_ c: String) -> String {173 switch c {174 case "text": "Texte"; case "vision": "Vision"; case "tools": "Outils"; case "reasoning": "Raisonnement"; case "audioInput": "Entrée audio"; case "audioOutput": "Sortie audio"175 case "imageGeneration": "Génération d'images"; case "structuredOutput": "Sortie structurée"; case "streaming": "Streaming"; case "longContext": "Long contexte"176 default: c177 }178 }179 public static func capabilitySymbol(_ c: String) -> String {180 switch c {181 case "vision": "eye"; case "tools": "wrench.and.screwdriver"; case "reasoning": "brain"; case "audioInput": "mic"; case "audioOutput": "speaker.wave.2"; case "imageGeneration": "photo"182 case "structuredOutput": "curlybraces"; case "streaming": "dot.radiowaves.left.and.right"; case "longContext": "text.justify.leading"; default: "circle"183 }184 }185}186