SPB Git

Repository Public MIT

OpenAIProvider.swift 7.8 KB 162 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Astra9// File             : Packages/AstraProviders/Sources/OpenAIProvider.swift10// Module           : Packages11// Repository       : https://git.spboucher.ai/orix-astra12// Created          : 2026-11-2113// Last Modified    : 2026-11-2114//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/// OpenAI through the Responses API (`POST /v1/responses`), the API OpenAI recommends for new text applications.92public struct OpenAIProvider: ChatProvider {93    public let kind: ProviderKind = .openAI94    public static let defaultBaseURL = URL(string: "https://api.openai.com/v1")!9596    private let http: ProviderHTTP97    private let apiKey: KeyProvider98    private let baseURL: URL99100    public init(transport: any HTTPTransport, apiKey: @escaping KeyProvider, diagnostics: (any DiagnosticsSink)? = nil, baseURL: URL = OpenAIProvider.defaultBaseURL) {101        self.http = ProviderHTTP(kind: .openAI, transport: transport, diagnostics: diagnostics)102        self.apiKey = apiKey103        self.baseURL = baseURL104    }105106    private func key() throws -> String { try resolveKey(apiKey, kind: kind, required: true) ?? "" }107    private func headers(_ key: String) -> [String: String] { ["Authorization": "Bearer \(key)", "Accept": "application/json"] }108109    public func listModels() async throws -> [ModelInfo] {110        let key = try key()111        let (json, _) = try await http.json(ProviderHTTP.request(baseURL.appendingPathComponent("models"), headers: headers(key)), secrets: [key])112        guard let data = json["data"]?.arrayValue else { throw AstraError.decoding("the model list has no data array") }113        let fetchedAt = Date()114        return data.compactMap { entry -> ModelInfo? in115            guard let id = entry["id"]?.stringValue, Self.isChatModel(id) else { return nil }116            let ref = ModelRef(provider: .openAI, modelID: id)117            let created = entry["created"]?.doubleValue.map { Date(timeIntervalSince1970: $0) }118            if var info = CuratedCatalog.info(for: ref) {119                info.createdAt = created120                info.vendor = entry["owned_by"]?.stringValue ?? info.vendor121                return info122            }123            // Not in the curated table: the API reports no limits, modalities or prices, so none are claimed.124            return ModelInfo(ref: ref, displayName: id, capabilities: [.text], source: .providerAPI(fetchedAt: fetchedAt), vendor: entry["owned_by"]?.stringValue, createdAt: created)125        }126        .sorted { ($0.createdAt ?? .distantPast) > ($1.createdAt ?? .distantPast) }127    }128129    /// `GET /v1/models` lists every model family; keep the ones that answer text over the Responses API.130    static func isChatModel(_ id: String) -> Bool {131        let lower = id.lowercased()132        let families = ["gpt-", "chatgpt-", "chat-latest", "o1", "o3", "o4"]133        guard families.contains(where: { lower.hasPrefix($0) }) else { return false }134        let excluded = ["embedding", "whisper", "tts", "audio", "realtime", "image", "transcribe", "moderation", "dall-e", "instruct", "search-api",135                        "live", "translate", "sora", "computer-use"]136        return !excluded.contains(where: { lower.contains($0) })137    }138139    public func verify() async throws -> ConnectionStatus {140        let models = try await listModels()141        return ConnectionStatus(ok: true, detail: "Key accepted. \(models.count) chat models available.", modelCount: models.count)142    }143144    static func plan(for modelID: String) -> ResponsesModelPlan {145        guard let entry = CuratedCatalog.openAI(modelID) else { return ResponsesModelPlan() }146        return ResponsesModelPlan(acceptsSampling: entry.acceptsSampling, reasoningEfforts: entry.reasoningEfforts,147                                  systemAsDeveloperMessage: entry.systemAsDeveloperMessage, requestSummaryByDefault: !entry.reasoningEfforts.isEmpty)148    }149150    public func stream(_ request: GenerationRequest) -> AsyncThrowingStream<StreamEvent, Error> {151        let http = http, apiKey = apiKey, url = baseURL.appendingPathComponent("responses")152        let secretBox = SecretBox()153        return makeEventStream(secrets: { secretBox.values }) { continuation in154            let key = try resolveKey(apiKey, kind: .openAI, required: true) ?? ""155            secretBox.add(key)156            try await runResponsesStream(http: http, request: request, plan: Self.plan(for: request.model.modelID), secrets: [key], makeRequest: { body in157                ProviderHTTP.request(url, method: "POST", headers: ["Authorization": "Bearer \(key)", "Accept": "text/event-stream"], body: body)158            }, continuation: continuation)159        }160    }161}162
Files main
Menu

Theme