Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Astra9// File : Packages/AstraProviders/Sources/KeyedChatCompletions.swift10// Module : Packages11// Repository : https://git.spboucher.ai/orix-astra12// Created : 2026-11-2213// Last Modified : 2026-11-2214//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author : Simon-Pierre Boucher20// Position : Professor of Finance21// Institution : Université du Québec en Outaouais (UQO)22// Department : Département des sciences administratives23// Organization : SP Boucher24//25// Website : https://spboucher.ai26// Git : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General : info@spboucher.ai33// Professional : contact@spboucher.ai34// Direct : simon@spboucher.ai35// Research : research@spboucher.ai36// Development : dev@spboucher.ai37// Support : support@spboucher.ai38// Security/Admin : admin@spboucher.ai39// Notifications : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification : Public66// Distribution : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License : Proprietary, all rights reserved (see license file)80// License File : LICENSE81// Maintainer : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import AstraCore89import Foundation9091/// What the keyed Chat Completions providers (Mistral, DeepSeek, Moonshot, Cerebras, DeepInfra) have in common:92/// a base URL, a bearer key read at request time, `GET {base}/models` and `POST {base}/chat/completions` in the provider's dialect.93struct KeyedChatCompletions: Sendable {94 let kind: ProviderKind95 let http: ProviderHTTP96 let apiKey: KeyProvider97 let baseURL: URL98 let dialect: ChatCompletionsDialect99100 init(kind: ProviderKind, transport: any HTTPTransport, apiKey: @escaping KeyProvider, diagnostics: (any DiagnosticsSink)?, baseURL: URL, dialect: ChatCompletionsDialect) {101 self.kind = kind102 self.http = ProviderHTTP(kind: kind, transport: transport, diagnostics: diagnostics)103 self.apiKey = apiKey104 self.baseURL = baseURL105 self.dialect = dialect106 }107108 /// The key, or `missingCredential` when `required` and none is stored.109 func key(required: Bool = true) throws -> String? { try resolveKey(apiKey, kind: kind, required: required) }110111 /// `GET` of a JSON document. The key travels only in the `Authorization` header; with `key == nil` the request is anonymous.112 func get(_ url: URL, key: String?) async throws -> JSONValue {113 var headers = ["Accept": "application/json"]114 if let key { headers["Authorization"] = "Bearer \(key)" }115 let (json, _) = try await http.json(ProviderHTTP.request(url, headers: headers), secrets: [key].compactMap { $0 }, normalize: dialect.normalize)116 return json117 }118119 /// The `data` array of `GET {base}/models`.120 func modelEntries(key: String?) async throws -> [JSONValue] {121 let json = try await get(baseURL.appendingPathComponent("models"), key: key)122 guard let data = json["data"]?.arrayValue ?? json.arrayValue else { throw AstraError.decoding("the model list has no data array") }123 return data124 }125126 func stream(_ request: GenerationRequest) -> AsyncThrowingStream<StreamEvent, Error> {127 let http = http, apiKey = apiKey, kind = kind, dialect = dialect, url = baseURL.appendingPathComponent("chat/completions")128 let secretBox = SecretBox()129 return makeEventStream(secrets: { secretBox.values }) { continuation in130 let key = try resolveKey(apiKey, kind: kind, required: true) ?? ""131 secretBox.add(key)132 let headers = ["Authorization": "Bearer \(key)", "Accept": "text/event-stream"]133 try await runChatCompletionsStream(http: http, request: request, dialect: dialect, secrets: [key], makeRequest: { body in134 ProviderHTTP.request(url, method: "POST", headers: headers, body: body)135 }, continuation: continuation)136 }137 }138}139140/// Picks another reasoning effort when a provider rejects the one that was sent and names the ones the model accepts.141enum EffortFallback {142 static let scale = ["none", "minimal", "low", "medium", "high", "xhigh", "max"]143144 /// The efforts a rejection lists after "one of" / "supported values" (Mistral: `Must be one of (<ReasoningEffort.none: 'none'>, …)`;145 /// Cerebras: `Supported values are 'low', 'medium', and 'high'`). Empty when the message lists none.146 static func allowed(in message: String) -> [String] {147 let lowered = message.lowercased()148 guard let marker = ["must be one of", "supported values", "expected one of", "valid values"].compactMap({ lowered.range(of: $0) }).map(\.upperBound).min() else { return [] }149 let tail = String(lowered[marker...])150 return scale.filter { tail.range(of: #"(^|[^a-z])"# + $0 + #"([^a-z]|$)"#, options: .regularExpression) != nil }151 }152153 /// The accepted effort closest to `current`; between two equally close ones, the deeper. Nil when nothing usable is listed.154 static func nearest(to current: String, allowed: [String]) -> String? {155 guard let position = scale.firstIndex(of: current.lowercased()) else { return nil }156 return allowed.filter { $0 != current.lowercased() }.compactMap { name in scale.firstIndex(of: name).map { (name, $0) } }157 .min { a, b in abs(a.1 - position) != abs(b.1 - position) ? abs(a.1 - position) < abs(b.1 - position) : a.1 > b.1 }?.0158 }159160 /// Parameter fallback for `reasoning_effort`: swaps in the nearest accepted value, or drops the field when the model takes none.161 static func adjust(_ failure: ProviderHTTP.Failure, _ body: inout [String: JSONValue]) -> Bool {162 guard failure.status == 400 || failure.status == 422, let current = body["reasoning_effort"]?.stringValue else { return false }163 let message = (failure.body.message ?? "").lowercased()164 guard message.contains("reasoning_effort") || message.contains("reasoning effort") else { return false }165 if let replacement = nearest(to: current, allowed: allowed(in: message)) { body["reasoning_effort"] = .string(replacement) }166 else { body.removeValue(forKey: "reasoning_effort") }167 return true168 }169}170171extension ModelInfo {172 /// Publisher of a hosted model, from the owner segment of a `owner/name` id ("meta-llama/Llama-…" → "meta-llama").173 static func owner(of modelID: String) -> String? {174 let parts = modelID.split(separator: "/", omittingEmptySubsequences: true)175 return parts.count > 1 ? String(parts[0]) : nil176 }177}178179/// USD per million tokens without binary floating-point noise (2.9999999999999996 → 3).180func roundedPrice(_ value: Double) -> Double { (value * 1_000_000).rounded() / 1_000_000 }181