SPB Git

Repository Public License

OpenAIProvider.swift 3.6 KB 63 lines swift

1import Foundation23/// OpenAI Chat Completions (`POST /v1/chat/completions`, streamed, usage requested with `stream_options`).4public struct OpenAIProvider: ChatProvider {5    public let family: ProviderFamily = .openAI67    static let dialect = ChatCompletionsDialect(reasoning: .effortField, requestsUsage: true, maxTokensKey: "max_completion_tokens")89    private let http: ProviderHTTP10    private let apiKey: KeySource11    private let baseURL: URL1213    public init(apiKey: @escaping KeySource, baseURL: URL? = nil, environment: ProviderEnvironment = ProviderEnvironment()) {14        self.http = ProviderHTTP(family: .openAI, environment: environment)15        self.apiKey = apiKey16        self.baseURL = baseURL ?? ProviderFamily.openAI.defaultBaseURL!17    }1819    public func listModels() async throws -> [ModelInfo] {20        let key = try await resolveKey(apiKey, family: family, required: true) ?? ""21        let request = ProviderHTTP.request(baseURL.appendingPathComponent("models"), headers: ["Authorization": "Bearer \(key)", "Accept": "application/json"],22                                           timeout: http.environment.timeouts.request)23        let json = try await http.json(request, secrets: [key])24        guard let data = json["data"]?.arrayValue else { throw ProviderError.malformedResponse("the model list has no data array.") }25        // The list reports ids and dates only: no limits, modalities or prices are claimed.26        return data.compactMap { entry -> ModelInfo? in27            guard let id = entry["id"]?.stringValue, Self.isChatModel(id) else { return nil }28            return ModelInfo(id: id, createdAt: entry["created"]?.doubleValue.map { Date(timeIntervalSince1970: $0) })29        }30        .sorted { ($0.createdAt ?? .distantPast) > ($1.createdAt ?? .distantPast) }31    }3233    /// The endpoint lists every model of the account (embeddings, speech, images…); only chat families are kept.34    /// This filters the suggestion list only: any id can still be typed and used.35    static func isChatModel(_ id: String) -> Bool {36        let lower = id.lowercased()37        guard ["gpt-", "chatgpt-", "o1", "o3", "o4"].contains(where: lower.hasPrefix) else { return false }38        let excluded = ["embedding", "whisper", "tts", "audio", "realtime", "image", "transcribe", "moderation", "dall-e", "instruct",39                        "search-api", "translate", "sora", "computer-use"]40        return !excluded.contains(where: lower.contains)41    }4243    public func testConnection() async throws -> ConnectionReport {44        let started = Date()45        let models = try await listModels()46        return ConnectionReport(family: family, summary: "Key accepted. \(models.count) chat models available.", modelCount: models.count,47                                latencyMilliseconds: Int(Date().timeIntervalSince(started) * 1_000))48    }4950    public func stream(_ request: ChatRequest) -> AsyncThrowingStream<ChatEvent, Error> {51        let http = http, apiKey = apiKey, url = baseURL.appendingPathComponent("chat/completions")52        let secrets = SecretBox()53        return makeEventStream(secrets: secrets) { continuation in54            let key = try await resolveKey(apiKey, family: .openAI, required: true) ?? ""55            secrets.add(key)56            let timeout = http.environment.timeouts.streamIdle57            try await runChatCompletionsStream(http: http, request: request, dialect: Self.dialect, secrets: [key], makeRequest: { body in58                ProviderHTTP.request(url, method: "POST", headers: ["Authorization": "Bearer \(key)", "Accept": "text/event-stream"], body: body, timeout: timeout)59            }, continuation: continuation)60        }61    }62}63
Files main
Menu

Theme