SPB Git

Repository Public

ProviderModels.swift 16.3 KB 280 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Core/Models/ProviderModels.swift3// Description: Providers and key management, Live Model Intelligence (model detail) and advisory route suggestion DTOs, with their endpoints.4import Foundation56// MARK: - Providers78public struct ProviderInfo: Sendable, Hashable, Identifiable, Codable {9    public struct Counts: Sendable, Hashable, Codable {10        public var total: Int; public var chat: Int11        enum CodingKeys: String, CodingKey { case total, chat }12        public init(from decoder: Decoder) throws { let c = try decoder.container(keyedBy: CodingKeys.self); total = c.flexInt(.total) ?? 0; chat = c.flexInt(.chat) ?? 0 }13    }14    public struct Health: Sendable, Hashable, Codable {15        public var state: String; public var recentFailures: Int; public var retryInSec: Int; public var active: Int16        enum CodingKeys: String, CodingKey { case state, recentFailures, retryInSec, active }17        public init(from decoder: Decoder) throws {18            let c = try decoder.container(keyedBy: CodingKeys.self)19            state = c.optional(String.self, .state) ?? "unknown"; recentFailures = c.flexInt(.recentFailures) ?? 0; retryInSec = c.flexInt(.retryInSec) ?? 0; active = c.flexInt(.active) ?? 020        }21    }22    public var id: String23    public var name: String24    /// `models` (an API that runs models) or `tool` (Tavily web search).25    public var kind: String26    public var route: String?27    public var logo: String?28    public var configured: Bool29    /// `stored` (set from an app, encrypted on the server) · `env` (server environment) · `none`.30    public var keySource: String31    /// Last characters of the key (« …a299 ») — the only part of a key ever sent to a client.32    public var keyHint: String?33    /// The key can be set / rotated / revoked from the apps (OpenRouter, Tavily).34    public var manageable: Bool35    public var validatedAt: Date?36    public var info: JSONValue?37    public var models: Counts?38    public var catalog: JSONValue?39    public var health: Health?4041    enum CodingKeys: String, CodingKey { case id, name, kind, route, logo, configured, keySource, keyHint, manageable, validatedAt, info, models, catalog, health }42    public init(from decoder: Decoder) throws {43        let c = try decoder.container(keyedBy: CodingKeys.self)44        id = try c.decode(String.self, forKey: .id); name = c.optional(String.self, .name) ?? id; kind = c.optional(String.self, .kind) ?? "models"45        route = c.optional(String.self, .route); logo = c.optional(String.self, .logo); configured = c.optional(Bool.self, .configured) ?? false46        keySource = c.optional(String.self, .keySource) ?? "none"; keyHint = c.optional(String.self, .keyHint); manageable = c.optional(Bool.self, .manageable) ?? false47        validatedAt = c.optional(Date.self, .validatedAt); info = c.optional(JSONValue.self, .info); models = c.optional(Counts.self, .models)48        catalog = c.optional(JSONValue.self, .catalog); health = c.optional(Health.self, .health)49    }50    public var keySourceLabel: String {51        switch keySource { case "stored": "Clé enregistrée sur le serveur (chiffrée)"; case "env": "Clé de l'environnement du serveur"; case "none": "Aucune clé"; default: keySource }52    }53}5455public struct LogoRegistryInfo: Sendable, Hashable, Codable {56    public struct MakerEntry: Sendable, Hashable, Codable, Identifiable { public var slug: String; public var name: String; public var color: Bool; public var id: String { slug } }57    public var source: String?58    public var license: String?59    public var makers: [MakerEntry]60    public var aliases: [String: String]61    enum CodingKeys: String, CodingKey { case source, license, makers, aliases }62    public init(from decoder: Decoder) throws {63        let c = try decoder.container(keyedBy: CodingKeys.self)64        source = c.optional(String.self, .source); license = c.optional(String.self, .license)65        makers = (c.optional([Lossy<MakerEntry>].self, .makers) ?? []).compactMap(\.value); aliases = c.optional([String: String].self, .aliases) ?? [:]66    }67}6869public struct ProvidersOverview: Sendable, Hashable, Codable {70    public var providers: [ProviderInfo]71    public var logos: LogoRegistryInfo?72    /// The rule behind each model category, in French, as written by the server.73    public var categoryRules: [String: String]74    enum CodingKeys: String, CodingKey { case providers, logos, categoryRules }75    public init(from decoder: Decoder) throws {76        let c = try decoder.container(keyedBy: CodingKeys.self)77        providers = (c.optional([Lossy<ProviderInfo>].self, .providers) ?? []).compactMap(\.value)78        logos = c.optional(LogoRegistryInfo.self, .logos); categoryRules = c.optional([String: String].self, .categoryRules) ?? [:]79    }80    public func provider(_ id: String) -> ProviderInfo? { providers.first { $0.id == id } }81}8283public struct ProviderTestResult: Sendable, Hashable {84    public var ok: Bool85    public var message: String86    public var info: JSONValue?87}8889public struct ProviderKeyRemoval: Sendable, Hashable {90    public var removed: Bool91    /// An environment key takes over after the stored key is revoked.92    public var fallback: Bool93}9495// MARK: - Live Model Intelligence9697public struct ModelDetail: Sendable, Hashable, Codable {98    public struct Params: Sendable, Hashable, Codable {99        public var effort: [String]100        public var effortAlias: [String: String]101        public var temperature: Bool?102        public var reasoningSummary: Bool?103        public var notes: [String: String]104        enum CodingKeys: String, CodingKey { case effort, effortAlias, temperature, reasoningSummary, notes }105        public init(from decoder: Decoder) throws {106            let c = try decoder.container(keyedBy: CodingKeys.self)107            effort = c.optional([String].self, .effort) ?? []; effortAlias = c.optional([String: String].self, .effortAlias) ?? [:]108            temperature = c.optional(Bool.self, .temperature); reasoningSummary = c.optional(Bool.self, .reasoningSummary); notes = c.optional([String: String].self, .notes) ?? [:]109        }110    }111    /// Figures measured on this account (usage log of SP Chat) — shown with `source`.112    public struct Measured: Sendable, Hashable, Codable {113        public var source: String114        public var requests: Int115        public var errors: Int116        public var p50LatencyMs: Double?117        public var p50TtftMs: Double?118        public var tokensPerSec: Double?119        public var costUsd: Double?120        public var inputTokens: Int?121        public var outputTokens: Int?122        public var firstUsed: Date?123        public var lastUsed: Date?124        enum CodingKeys: String, CodingKey { case source, requests, errors; case p50LatencyMs = "p50_latency_ms", p50TtftMs = "p50_ttft_ms", tokensPerSec = "tokens_per_sec", costUsd = "cost_usd", inputTokens = "input_tokens", outputTokens = "output_tokens", firstUsed = "first_used", lastUsed = "last_used" }125        public init(from decoder: Decoder) throws {126            let c = try decoder.container(keyedBy: CodingKeys.self)127            source = c.optional(String.self, .source) ?? ""; requests = c.flexInt(.requests) ?? 0; errors = c.flexInt(.errors) ?? 0128            p50LatencyMs = c.flexDouble(.p50LatencyMs); p50TtftMs = c.flexDouble(.p50TtftMs); tokensPerSec = c.flexDouble(.tokensPerSec); costUsd = c.flexDouble(.costUsd)129            inputTokens = c.flexInt(.inputTokens); outputTokens = c.flexInt(.outputTokens); firstUsed = c.optional(Date.self, .firstUsed); lastUsed = c.optional(Date.self, .lastUsed)130        }131    }132    public struct Endpoint: Sendable, Hashable, Codable, Identifiable {133        public var provider: String134        public var tag: String?135        public var contextLength: Int?136        public var maxCompletionTokens: Int?137        public var quantization: String?138        public var uptimeLast30m: Double?139        public var status: Int?140        public var inputPerM: Double?141        public var outputPerM: Double?142        public var supportsTools: Bool?143        public var id: String { tag ?? provider }144        enum CodingKeys: String, CodingKey { case provider, tag, contextLength, maxCompletionTokens, quantization, uptimeLast30m, status, inputPerM, outputPerM, supportsTools }145        public init(from decoder: Decoder) throws {146            let c = try decoder.container(keyedBy: CodingKeys.self)147            provider = c.optional(String.self, .provider) ?? "?"; tag = c.optional(String.self, .tag); contextLength = c.flexInt(.contextLength); maxCompletionTokens = c.flexInt(.maxCompletionTokens)148            quantization = c.optional(String.self, .quantization); uptimeLast30m = c.flexDouble(.uptimeLast30m); status = c.flexInt(.status)149            inputPerM = c.flexDouble(.inputPerM); outputPerM = c.flexDouble(.outputPerM); supportsTools = c.optional(Bool.self, .supportsTools)150        }151    }152    public struct Endpoints: Sendable, Hashable, Codable {153        public var source: String154        public var list: [Endpoint]155        enum CodingKeys: String, CodingKey { case source, list }156        public init(from decoder: Decoder) throws {157            let c = try decoder.container(keyedBy: CodingKeys.self)158            source = c.optional(String.self, .source) ?? ""; list = (c.optional([Lossy<Endpoint>].self, .list) ?? []).compactMap(\.value)159        }160    }161    /// The same model reachable by the other route.162    public struct Twin: Sendable, Hashable, Codable, Identifiable {163        public var id: String164        public var route: String165        public var provider: String?166        public var displayName: String167        public var pricing: [String: JSONValue]?168        public var status: String?169        enum CodingKeys: String, CodingKey { case id, route, provider, pricing, status; case displayName = "display_name" }170        public init(from decoder: Decoder) throws {171            let c = try decoder.container(keyedBy: CodingKeys.self)172            id = try c.decode(String.self, forKey: .id); route = c.optional(String.self, .route) ?? (id.hasPrefix("or:") ? "openrouter" : "direct"); provider = c.optional(String.self, .provider)173            displayName = c.optional(String.self, .displayName) ?? id; pricing = c.optional([String: JSONValue].self, .pricing); status = c.optional(String.self, .status)174        }175        public var inputPrice: Double? { pricing?["input"]?.doubleValue }176        public var outputPrice: Double? { pricing?["output"]?.doubleValue }177    }178    /// One third-party benchmark source with its figures, exactly as passed through by the server.179    public struct BenchmarkSource: Sendable, Hashable, Identifiable {180        public var source: String181        public var figures: [(name: String, value: Double)] { values.sorted { $0.key < $1.key }.map { ($0.key, $0.value) } }182        public var values: [String: Double]183        public var id: String { source }184        /// `artificial_analysis` → « Artificial Analysis ».185        public var sourceLabel: String { source.split(separator: "_").map { $0.prefix(1).uppercased() + $0.dropFirst() }.joined(separator: " ") }186        public static func figureLabel(_ key: String) -> String {187            var k = key; if k.hasSuffix("_index") { k.removeLast(6) }188            let s = k.replacingOccurrences(of: "_", with: " ")189            return s.prefix(1).uppercased() + s.dropFirst()190        }191    }192193    public var model: AIModel194    public var params: Params?195    public var measured: Measured?196    public var endpoints: Endpoints?197    public var twins: [Twin]198    enum CodingKeys: String, CodingKey { case model, params, measured, endpoints, twins }199    public init(from decoder: Decoder) throws {200        let c = try decoder.container(keyedBy: CodingKeys.self)201        model = try c.decode(AIModel.self, forKey: .model)202        params = c.optional(Params.self, .params); measured = c.optional(Measured.self, .measured); endpoints = c.optional(Endpoints.self, .endpoints)203        twins = (c.optional([Lossy<Twin>].self, .twins) ?? []).compactMap(\.value)204    }205    public var thirdPartyBenchmarks: [BenchmarkSource] {206        guard let o = model.catalog?.benchmarks?.objectValue else { return [] }207        return o.compactMap { key, value -> BenchmarkSource? in208            guard let figures = value.objectValue else { return nil }209            let numbers = figures.compactMapValues(\.doubleValue)210            return numbers.isEmpty ? nil : BenchmarkSource(source: key, values: numbers)211        }.sorted { $0.source < $1.source }212    }213}214215// MARK: - Smart Model Router (advisory)216217public struct RouteSuggestion: Sendable, Hashable, Codable {218    public struct Decision: Sendable, Hashable, Codable {219        public var mode: String?220        public var selected: String?221        public var reason: String?222        public var task: String?223        public var candidates: [String]?224    }225    public struct Candidate: Sendable, Hashable, Codable, Identifiable {226        public var id: String227        public var displayName: String?228        public var provider: String?229        public var logo: String?230        public var qualityScore: Double?231        public var p50LatencyMs: Double?232        public var blendedPricePerM: Double?233        enum CodingKeys: String, CodingKey { case id, displayName, provider, logo, qualityScore, p50LatencyMs, blendedPricePerM }234        public init(from decoder: Decoder) throws {235            let c = try decoder.container(keyedBy: CodingKeys.self)236            id = try c.decode(String.self, forKey: .id); displayName = c.optional(String.self, .displayName); provider = c.optional(String.self, .provider); logo = c.optional(String.self, .logo)237            qualityScore = c.flexDouble(.qualityScore); p50LatencyMs = c.flexDouble(.p50LatencyMs); blendedPricePerM = c.flexDouble(.blendedPricePerM)238        }239    }240    public var decision: Decision?241    public var candidates: [Candidate]242    /// What the suggestion is based on, as written by the server.243    public var basis: String?244    enum CodingKeys: String, CodingKey { case decision, candidates, basis }245    public init(from decoder: Decoder) throws {246        let c = try decoder.container(keyedBy: CodingKeys.self)247        decision = c.optional(Decision.self, .decision); candidates = (c.optional([Lossy<Candidate>].self, .candidates) ?? []).compactMap(\.value); basis = c.optional(String.self, .basis)248    }249}250251// MARK: - Endpoints252253public extension APIClient {254    func providers() async throws -> ProvidersOverview { try await decode(ProvidersOverview.self, .get, "/api/providers") }255256    /// Validates the key with the provider, stores it encrypted on the server and refreshes the catalogue. Needs a recent257    /// passkey verification: `403 reauth_required` runs the re-authentication once, then the request is replayed.258    /// The key is sent once and never kept by the app. `422` (key refused by the provider) is thrown with the server's message.259    func setProviderKey(_ providerId: String, key: String) async throws {260        do { _ = try await raw(.put, "/api/providers/\(providerId)/key", json: ["key": .string(key)], timeout: 125) }261        catch let e as APIError where e.status == 422 { throw APIError(.server(status: 422), message: e.message == "HTTP 422" ? "Le fournisseur a refusé cette clé." : e.message, code: e.code ?? "key_refused", requestId: e.requestId) }262    }263    func removeProviderKey(_ providerId: String) async throws -> ProviderKeyRemoval {264        let j = try await json(.delete, "/api/providers/\(providerId)/key")265        return ProviderKeyRemoval(removed: j["removed"]?.boolValue ?? true, fallback: j["fallback"]?.boolValue ?? false)266    }267    func testProvider(_ providerId: String) async throws -> ProviderTestResult {268        let j = try await json(.post, "/api/providers/\(providerId)/test", timeout: 60)269        return ProviderTestResult(ok: j["ok"]?.boolValue ?? false, message: j["message"]?.stringValue ?? "", info: j["info"])270    }271272    func modelDetail(_ id: String) async throws -> ModelDetail { try await decode(ModelDetail.self, .get, "/api/models/detail", query: ["id": id], timeout: 45) }273274    /// Smart Model Router in advisory mode: returns a suggestion, never sends or switches anything.275    func suggestRoute(text: String, mode: RoutingMode = .auto, hasImages: Bool = false, wantsTools: Bool = false) async throws -> RouteSuggestion {276        try await decode(RouteSuggestion.self, .post, "/api/models/route-suggest",277                         body: ["text": .string(String(text.prefix(8000))), "mode": .string(mode == .manual ? "auto" : mode.rawValue), "hasImages": .bool(hasImages), "wantsTools": .bool(wantsTools)])278    }279}280
Files main
Menu

Theme