SPB Git

Repository Public

Provider.swift 16.7 KB 317 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Astra9// File             : Packages/AstraCore/Sources/Provider.swift10// Module           : Packages11// Repository       : https://git.spboucher.ai/orix-astra12// Created          : 2026-11-2113// 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 Foundation8990/// Result of a provider connection check: proves the key works without generating anything.91public struct ConnectionStatus: Sendable, Hashable, Codable {92    public var ok: Bool93    public var detail: String94    public var modelCount: Int?95    /// Remaining credit in US dollars when the provider reports it (OpenRouter).96    public var remainingCreditUSD: Double?97    public var checkedAt: Date98    public init(ok: Bool, detail: String, modelCount: Int? = nil, remainingCreditUSD: Double? = nil, checkedAt: Date = Date()) {99        self.ok = ok; self.detail = detail; self.modelCount = modelCount; self.remainingCreditUSD = remainingCreditUSD; self.checkedAt = checkedAt100    }101}102103/// One inference backend, cloud or local. Adapters translate to and from their transport; nothing else knows the wire format.104public protocol ChatProvider: Sendable {105    var kind: ProviderKind { get }106    /// Models this provider offers right now, with metadata that states its own source.107    func listModels() async throws -> [ModelInfo]108    /// Verifies credentials and reachability with the cheapest call the provider has.109    func verify() async throws -> ConnectionStatus110    /// Streams one answer. Cancelling the consuming task cancels the request.111    func stream(_ request: GenerationRequest) -> AsyncThrowingStream<StreamEvent, Error>112}113114/// One sanitized record per provider request, for Lab diagnostics. Never contains headers, keys, prompts or answers.115public struct RequestDiagnostic: Sendable, Hashable, Codable, Identifiable {116    public var id: UUID117    public var provider: ProviderKind118    public var modelID: String119    public var startedAt: Date120    public var httpStatus: Int?121    public var requestID: String?122    public var timeToHeaders: TimeInterval?123    public var timeToFirstToken: TimeInterval?124    public var totalTime: TimeInterval?125    public var retryCount: Int126    public var usage: TokenUsage?127    public var stopReason: StopReason?128    public var errorTitle: String?129    public init(id: UUID = UUID(), provider: ProviderKind, modelID: String, startedAt: Date = Date(), httpStatus: Int? = nil, requestID: String? = nil,130                timeToHeaders: TimeInterval? = nil, timeToFirstToken: TimeInterval? = nil, totalTime: TimeInterval? = nil, retryCount: Int = 0,131                usage: TokenUsage? = nil, stopReason: StopReason? = nil, errorTitle: String? = nil) {132        self.id = id; self.provider = provider; self.modelID = modelID; self.startedAt = startedAt; self.httpStatus = httpStatus133        self.requestID = requestID; self.timeToHeaders = timeToHeaders; self.timeToFirstToken = timeToFirstToken; self.totalTime = totalTime134        self.retryCount = retryCount; self.usage = usage; self.stopReason = stopReason; self.errorTitle = errorTitle135    }136}137138/// Receives transport-level facts from adapters (status, request id, header latency). Implemented by the app's diagnostics store.139public protocol DiagnosticsSink: Sendable {140    func httpResponse(provider: ProviderKind, modelID: String, status: Int, requestID: String?, timeToHeaders: TimeInterval, retryCount: Int) async141}142143// MARK: - Stream validation and measurement144145/// Checks the order of events coming out of an adapter and turns a malformed stream into one clean terminal error.146/// Rules: one `messageStarted` first; tool deltas only for started calls; nothing after a terminal event; exactly one terminal event.147public struct StreamValidator: Sendable {148    public private(set) var started = false149    public private(set) var finished = false150    private var openCalls: Set<String> = []151    private var completedCalls: Set<String> = []152    public init() {}153154    /// Returns the events to forward for `event` (possibly a synthesized `messageStarted` before it), or throws on a violation.155    public mutating func accept(_ event: StreamEvent) throws -> [StreamEvent] {156        guard !finished else { throw AstraError.protocolViolation("event after the end of the message") }157        var out: [StreamEvent] = []158        if case .messageStarted = event {159            guard !started else { return [] }   // a duplicated start is harmless: keep the first identity160            started = true161            return [event]162        }163        if !started { started = true; out.append(.messageStarted(MessageStart())) }164        switch event {165        case .toolCallStarted(let id, _):166            guard !openCalls.contains(id), !completedCalls.contains(id) else { throw AstraError.protocolViolation("tool call \(id) started twice") }167            openCalls.insert(id)168        case .toolCallDelta(let id, _):169            guard openCalls.contains(id) else { throw AstraError.protocolViolation("arguments for a tool call that was never started") }170        case .toolCallCompleted(let call):171            guard !completedCalls.contains(call.id) else { throw AstraError.protocolViolation("tool call \(call.id) completed twice") }172            openCalls.remove(call.id); completedCalls.insert(call.id)173        case .messageCompleted(let reason):174            // A turn that says "call these tools" while a call is still open would lose that call silently. A turn cut by the175            // output limit or a filter may legitimately end mid-call: the unfinished call is simply not delivered.176            if reason == .toolCalls, !openCalls.isEmpty { throw AstraError.protocolViolation("the message ended with an unfinished tool call") }177            finished = true178        case .error:179            finished = true180        default: break181        }182        out.append(event)183        return out184    }185}186187/// Wall-clock measurements of one generation, taken by the orchestrator, never by the model.188public struct GenerationTiming: Sendable, Hashable, Codable {189    public var startedAt: Date190    public var timeToFirstToken: TimeInterval?191    public var totalTime: TimeInterval?192    public init(startedAt: Date = Date(), timeToFirstToken: TimeInterval? = nil, totalTime: TimeInterval? = nil) {193        self.startedAt = startedAt; self.timeToFirstToken = timeToFirstToken; self.totalTime = totalTime194    }195    /// Visible output tokens per second over the streaming phase (first visible token to the end).196    /// Nil unless it is a meaningful measurement: the token count was reported, hidden reasoning tokens are known and197    /// excluded (they are produced before the first visible token), and text actually streamed for at least half a second.198    /// A provider that delivers its whole answer in one burst therefore shows no speed rather than an absurd one.199    public func tokensPerSecond(outputTokens: Int?, reasoningTokens: Int? = nil) -> Double? {200        guard let outputTokens, let total = totalTime, let first = timeToFirstToken else { return nil }201        let visible = outputTokens - (reasoningTokens ?? 0)202        let phase = total - first203        guard visible > 1, phase >= 0.5 else { return nil }204        return Double(visible) / phase205    }206}207208/// The complete, provider-independent result of one generation.209public struct GenerationOutcome: Sendable, Hashable {210    public var start = MessageStart()211    public var text = ""212    public var reasoningSummary = ""213    public var toolCalls: [ToolCall] = []214    public var usage: TokenUsage?215    public var stopReason: StopReason = .unknown216    public var error: AstraError?217    public var timing = GenerationTiming()218    public init() {}219220    /// Folds one validated event into the outcome.221    public mutating func apply(_ event: StreamEvent, now: Date = Date()) {222        switch event {223        case .messageStarted(let s): start = s224        case .textDelta(let t):225            if timing.timeToFirstToken == nil { timing.timeToFirstToken = now.timeIntervalSince(timing.startedAt) }226            text += t227        case .reasoningSummaryDelta(let t):228            if timing.timeToFirstToken == nil { timing.timeToFirstToken = now.timeIntervalSince(timing.startedAt) }229            reasoningSummary += t230        case .toolCallStarted, .toolCallDelta: break231        case .toolCallCompleted(let call): toolCalls.append(call)232        case .usage(let u): usage = usage?.merged(with: u) ?? u233        case .messageCompleted(let reason): stopReason = reason; timing.totalTime = now.timeIntervalSince(timing.startedAt)234        case .error(let e): error = e; stopReason = e == .cancelled ? .cancelled : .error; timing.totalTime = now.timeIntervalSince(timing.startedAt)235        }236    }237}238239public extension GenerationOutcome {240    /// Closes an outcome whose stream ended without a terminal event. That happens when the consumer itself was cancelled241    /// (the stream is torn down before the orchestrator can deliver `.error(.cancelled)`) or stopped reading early.242    /// Every consumer calls this once after its loop, so no answer is ever stored with an unknown stop reason.243    mutating func closeIfUnterminated(cancelled: Bool, now: Date = Date()) {244        guard error == nil, stopReason == .unknown else { return }245        apply(.error(cancelled ? .cancelled : .protocolViolation("the stream ended without completing the message")), now: now)246    }247}248249/// Routes requests to providers and guarantees a well-formed event stream: validated order, exactly one terminal event,250/// a safe retry only when nothing has been received yet. When the consumer is cancelled the stream simply ends (an251/// `AsyncStream` cannot deliver to a cancelled reader): consumers close their outcome with `closeIfUnterminated`.252public struct InferenceOrchestrator: Sendable {253    public typealias Resolver = @Sendable (ModelRef) async throws -> any ChatProvider254    private let resolve: Resolver255    public var maxRetries: Int256    public var sleep: @Sendable (TimeInterval) async throws -> Void257258    public init(maxRetries: Int = 1, sleep: @escaping @Sendable (TimeInterval) async throws -> Void = { try await Task.sleep(nanoseconds: UInt64((RetryDelay.sane($0) ?? 0) * 1_000_000_000)) },259                resolve: @escaping Resolver) {260        self.resolve = resolve; self.maxRetries = maxRetries; self.sleep = sleep261    }262263    /// Never throws: failures arrive as a terminal `.error` event, so partial text already delivered stays valid.264    public func stream(_ request: GenerationRequest) -> AsyncStream<StreamEvent> {265        // Unbounded on purpose: no event may be dropped. Memory is bounded by the size of one response.266        AsyncStream(bufferingPolicy: .unbounded) { continuation in267            let task = Task {268                var attempt = 0269                while true {270                    var validator = StreamValidator()271                    var receivedContent = false272                    // The start of an attempt is held back until the attempt delivers something: a retried attempt then273                    // leaves no trace, and the consumer sees exactly one start.274                    var pendingStart: StreamEvent?275                    do {276                        try Task.checkCancellation()277                        let provider = try await resolve(request.model)278                        for try await event in provider.stream(request) {279                            try Task.checkCancellation()280                            for out in try validator.accept(event) {281                                if case .messageStarted = out { pendingStart = out; continue }282                                if let start = pendingStart { continuation.yield(start); pendingStart = nil }283                                receivedContent = true284                                continuation.yield(out)285                            }286                            if validator.finished { break }287                        }288                        if !validator.finished {289                            if let start = pendingStart { continuation.yield(start); pendingStart = nil }290                            if Task.isCancelled { continuation.yield(.error(.cancelled)) }291                            else { continuation.yield(.error(.protocolViolation("the stream ended without completing the message"))) }292                        }293                        continuation.finish(); return294                    } catch {295                        let mapped = Task.isCancelled ? AstraError.cancelled : AstraError.wrap(error)296                        // Retrying is only safe when the provider has produced nothing: no partial answer, no tool call, no billed output shown.297                        if mapped.isSafeToRetryAutomatically, !receivedContent, attempt < maxRetries, !Task.isCancelled {298                            attempt += 1299                            var delay = min(8, pow(2, Double(attempt - 1)))300                            // A server-supplied delay is clamped; one that is not a number is treated as "too long to wait".301                            if case .rateLimited(let after, _) = mapped, let after { delay = RetryDelay.sane(after) ?? .infinity }302                            if delay.isInfinite { attempt = maxRetries }303                            else if delay <= 20, (try? await sleep(delay)) != nil { continue }304                        }305                        if !validator.finished {306                            if let start = pendingStart { continuation.yield(start); pendingStart = nil }307                            continuation.yield(.error(mapped))308                        }309                        continuation.finish(); return310                    }311                }312            }313            continuation.onTermination = { _ in task.cancel() }314        }315    }316}317
Files main
Menu

Theme