Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Keyboard9// File : Shared/Sources/AIEngine/AIModels.swift10// Description : Typed wire models of the Anthropic Messages and Models11// APIs, the SP AI error taxonomy and the user-facing AI12// settings (model, budget, language, tone, favourite13// prompts, local counters).14// Module : AIEngine15// Repository : https://git.spboucher.ai/sp-keyboard16// Created : 2026-12-0117// Last Modified : 2026-12-0118//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author : Simon-Pierre Boucher24// Position : Professor of Finance25// Institution : Université du Québec en Outaouais (UQO)26// Department : Département des sciences administratives27// Organization : SP Boucher28//29// Website : https://spboucher.ai30// Git : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General : info@spboucher.ai37// Professional : contact@spboucher.ai38// Direct : simon@spboucher.ai39// Research : research@spboucher.ai40// Development : dev@spboucher.ai41// Support : support@spboucher.ai42// Security/Admin : admin@spboucher.ai43// Notifications : notifications@spboucher.ai44//45// Preferred Contact: support@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification : Public70// Distribution : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License : None specified (no license file in this repository)84// Maintainer : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import Foundation92import SecureStorage9394// MARK: - Wire: request9596struct MessagesRequestBody: Encodable {97 struct Message: Encodable {98 var role: String99 var content: String100 }101102 struct OutputConfig: Encodable {103 var effort: String104 }105106 var model: String107 var max_tokens: Int108 var system: String109 var messages: [Message]110 var output_config: OutputConfig?111 var fallbacks: String?112}113114// MARK: - Wire: response115116struct MessagesResponseBody: Decodable {117 struct Block: Decodable {118 var type: String119 var text: String?120 }121122 struct Usage: Decodable {123 var input_tokens: Int?124 var output_tokens: Int?125 }126127 struct StopDetails: Decodable {128 var category: String?129 }130131 var id: String?132 var type: String133 var model: String?134 var content: [Block]135 var stop_reason: String?136 var stop_details: StopDetails?137 var usage: Usage?138}139140struct ErrorResponseBody: Decodable {141 struct Detail: Decodable {142 var type: String?143 var message: String?144 }145146 var error: Detail?147}148149struct ModelsResponseBody: Decodable {150 struct Flag: Decodable {151 var supported: Bool?152 }153154 struct Effort: Decodable {155 var supported: Bool?156 var low: Flag?157 }158159 struct Capabilities: Decodable {160 var effort: Effort?161 }162163 struct Model: Decodable {164 var id: String165 var display_name: String?166 var max_tokens: Int?167 var capabilities: Capabilities?168 }169170 var data: [Model]171 var has_more: Bool?172}173174// MARK: - Public models175176/// A model the configured key can call, as reported by `GET /v1/models`. Nothing here is invented locally.177public struct AIModelInfo: Codable, Hashable, Sendable, Identifiable {178 public var id: String179 public var displayName: String180 public var maxOutputTokens: Int?181 public var supportsLowEffort: Bool182183 public init(id: String, displayName: String, maxOutputTokens: Int? = nil, supportsLowEffort: Bool = false) {184 self.id = id185 self.displayName = displayName186 self.maxOutputTokens = maxOutputTokens187 self.supportsLowEffort = supportsLowEffort188 }189}190191public struct AIUsage: Codable, Hashable, Sendable {192 public var inputTokens: Int193 public var outputTokens: Int194195 public init(inputTokens: Int = 0, outputTokens: Int = 0) {196 self.inputTokens = inputTokens197 self.outputTokens = outputTokens198 }199}200201public struct AIResult: Hashable, Sendable {202 /// Plain text, already trimmed and bounded. Never interpreted as markup or instructions.203 public var text: String204 public var usage: AIUsage205 /// Model that actually answered (may differ from the requested one after a server-side fallback).206 public var model: String207208 public init(text: String, usage: AIUsage, model: String) {209 self.text = text210 self.usage = usage211 self.model = model212 }213}214215/// Everything that can go wrong. No case ever carries the key or the user's text.216public enum AIError: Error, Equatable, Sendable {217 case missingKey218 case keychain(SecretStoreError)219 case noModelSelected220 case emptySource221 case sourceTooLong(limit: Int)222 case invalidKey // 401223 case forbidden // 403224 case modelUnavailable // 404225 case badRequest(String) // 400, server message redacted226 case rateLimited(retryAfter: Int?)227 case overloaded // 529228 case server(status: Int)229 case offline230 case timeout231 /// The request left the device but no answer came back: it may have been processed and billed.232 case outcomeUnknown233 case blockedRedirect234 case malformedResponse235 case refused(category: String?)236 case truncated237 case emptyOutput238 case cancelled239 case busy240241 /// True when sending the same request again cannot double a charge and may succeed.242 public var isTransient: Bool {243 switch self {244 case .rateLimited, .overloaded, .server, .offline: true245 default: false246 }247 }248}249250public enum AIOutputLanguage: String, Codable, Sendable, CaseIterable {251 case sameAsSource = "auto", french = "fr", english = "en", spanish = "es"252253 var englishName: String? {254 switch self {255 case .sameAsSource: nil256 case .french: "Canadian French"257 case .english: "English"258 case .spanish: "Spanish"259 }260 }261}262263public enum AITone: String, Codable, Sendable, CaseIterable {264 case professional, friendly, direct, warm, academic, humorous265}266267public struct AIFavoritePrompt: Codable, Hashable, Sendable, Identifiable {268 public var id: String269 public var title: String270 public var prompt: String271272 public init(id: String = UUID().uuidString, title: String, prompt: String) {273 self.id = id274 self.title = title275 self.prompt = prompt276 }277}278279/// Local counters: numbers only, never any content.280public struct AICounters: Codable, Hashable, Sendable {281 public var calls = 0282 public var failures = 0283 public var inputTokens = 0284 public var outputTokens = 0285 public var since: Date = Date()286287 public init() {}288289 public mutating func record(_ usage: AIUsage) {290 calls += 1291 inputTokens += usage.inputTokens292 outputTokens += usage.outputTokens293 }294}295296public struct AISettings: VersionedSettings, Hashable {297 public static let currentSchemaVersion = 1298 public static let storageKey = "ai.settings"299 public static var fallback: AISettings { AISettings() }300301 public static let outputTokenRange = 256...4096302 public static let maxSourceCharacters = 6000303 public static let maxFavorites = 24304305 public var schemaVersion = AISettings.currentSchemaVersion306 /// Empty until the user picks one of the models returned for their key.307 public var modelID = ""308 /// Models last returned by the API for this key (identifiers and names only).309 public var knownModels: [AIModelInfo] = []310 public var outputLanguage: AIOutputLanguage = .sameAsSource311 public var maxOutputTokens = 1024312 public var defaultTone: AITone = .professional313 public var favorites: [AIFavoritePrompt] = AISettings.defaultFavorites314 public var countersEnabled = true315 public var counters = AICounters()316317 public init() {}318319 public func migrated() -> AISettings {320 var copy = self321 copy.maxOutputTokens = min(max(copy.maxOutputTokens, Self.outputTokenRange.lowerBound), Self.outputTokenRange.upperBound)322 copy.favorites = copy.favorites.prefix(Self.maxFavorites).map {323 AIFavoritePrompt(id: $0.id, title: String($0.title.prefix(40)), prompt: String($0.prompt.prefix(600)))324 }325 copy.knownModels = Array(copy.knownModels.prefix(60))326 copy.modelID = String(copy.modelID.prefix(120))327 return copy328 }329330 public var selectedModel: AIModelInfo? { knownModels.first { $0.id == modelID } }331332 public static let defaultFavorites: [AIFavoritePrompt] = [333 AIFavoritePrompt(id: "fav-email", title: "Courriel poli", prompt: "Transforme ces notes en courriel poli et concis, avec une salutation et une formule de fin."),334 AIFavoritePrompt(id: "fav-sms", title: "Texto court", prompt: "Réécris ce message comme un texto court et naturel."),335 AIFavoritePrompt(id: "fav-points", title: "Liste à puces", prompt: "Réorganise ce texte en liste à puces claire."),336 ]337}338