SPB Git

Repository Public License

OpenRouterProvider.swift 5.7 KB 90 lines swift

1import Foundation23/// OpenRouter: Chat Completions with attribution headers and a public model list that includes per-model prices.4public struct OpenRouterProvider: ChatProvider {5    public let family: ProviderFamily = .openRouter67    /// OpenRouter reports usage (and the cost it charged) in the final chunk without being asked.8    static let dialect = ChatCompletionsDialect(reasoning: .object, requestsUsage: false, reasoningDetailsFormat: "openrouter.reasoning_details")9    static let priceSourceURL = "https://openrouter.ai/api/v1/models"1011    private let http: ProviderHTTP12    private let apiKey: KeySource13    private let baseURL: URL1415    public init(apiKey: @escaping KeySource, baseURL: URL? = nil, environment: ProviderEnvironment = ProviderEnvironment()) {16        self.http = ProviderHTTP(family: .openRouter, environment: environment)17        self.apiKey = apiKey18        self.baseURL = baseURL ?? ProviderFamily.openRouter.defaultBaseURL!19    }2021    /// `HTTP-Referer` and `X-Title` identify the application to OpenRouter (its documented attribution headers).22    static func headers(_ key: String?) -> [String: String] {23        var headers = ["HTTP-Referer": ProviderKit.applicationURL, "X-Title": ProviderKit.applicationName]24        if let key, !key.isEmpty { headers["Authorization"] = "Bearer \(key)" }25        return headers26    }2728    public func listModels() async throws -> [ModelInfo] {29        // The catalogue is public; the key is sent when there is one so account-specific availability applies.30        let key = try await resolveKey(apiKey, family: family, required: false)31        let request = ProviderHTTP.request(baseURL.appendingPathComponent("models"), headers: Self.headers(key), timeout: http.environment.timeouts.request)32        let json = try await http.json(request, secrets: [key].compactMap { $0 })33        guard let data = json["data"]?.arrayValue else { throw ProviderError.malformedResponse("the model list has no data array.") }34        let fetchedAt = Date()35        return data.compactMap { Self.modelInfo($0, fetchedAt: fetchedAt) }36    }3738    static func modelInfo(_ entry: JSONValue, fetchedAt: Date) -> ModelInfo? {39        guard let id = entry["id"]?.stringValue else { return nil }40        let outputs = entry["architecture"]?["output_modalities"]?.arrayValue?.compactMap(\.stringValue) ?? ["text"]41        guard outputs.contains("text") else { return nil }42        let inputs = entry["architecture"]?["input_modalities"]?.arrayValue.map { Set($0.compactMap(\.stringValue)) }43        let parameters = entry["supported_parameters"]?.arrayValue.map { Set($0.compactMap(\.stringValue)) }44        return ModelInfo(id: id, displayName: entry["name"]?.stringValue,45                         contextLength: entry["context_length"]?.intValue ?? entry["top_provider"]?["context_length"]?.intValue,46                         maxOutputTokens: entry["top_provider"]?["max_completion_tokens"]?.intValue,47                         supportsTools: parameters.map { $0.contains("tools") }, supportsImages: inputs.map { $0.contains("image") },48                         price: price(entry["pricing"], fetchedAt: fetchedAt),49                         createdAt: entry["created"]?.doubleValue.map { Date(timeIntervalSince1970: $0) })50    }5152    /// Prices are strings in US dollars per token. A negative price marks a router whose cost depends on the model it53    /// picks: no price is recorded for those.54    static func price(_ pricing: JSONValue?, fetchedAt: Date) -> ModelPrice? {55        guard let input = pricing?["prompt"]?.doubleValue, let output = pricing?["completion"]?.doubleValue, input >= 0, output >= 0 else { return nil }56        func perMillion(_ perToken: Double) -> Double { (perToken * 1_000_000 * 1_000_000).rounded() / 1_000_000 }57        return ModelPrice(inputPerMillion: perMillion(input), outputPerMillion: perMillion(output),58                          cacheReadPerMillion: pricing?["input_cache_read"]?.doubleValue.map(perMillion),59                          cacheWritePerMillion: pricing?["input_cache_write"]?.doubleValue.map(perMillion),60                          source: .providerList(url: priceSourceURL, fetchedAt: fetchedAt))61    }6263    public func testConnection() async throws -> ConnectionReport {64        let started = Date()65        let key = try await resolveKey(apiKey, family: family, required: true) ?? ""66        let request = ProviderHTTP.request(baseURL.appendingPathComponent("key"), headers: Self.headers(key), timeout: http.environment.timeouts.request)67        let json = try await http.json(request, secrets: [key])68        let data = json["data"] ?? json69        var summary = "Key accepted."70        if data["is_free_tier"]?.boolValue == true { summary += " Free tier." }71        return ConnectionReport(family: family, summary: summary, remainingCreditUSD: data["limit_remaining"]?.doubleValue,72                                latencyMilliseconds: Int(Date().timeIntervalSince(started) * 1_000))73    }7475    public func stream(_ request: ChatRequest) -> AsyncThrowingStream<ChatEvent, Error> {76        let http = http, apiKey = apiKey, url = baseURL.appendingPathComponent("chat/completions")77        let secrets = SecretBox()78        return makeEventStream(secrets: secrets) { continuation in79            let key = try await resolveKey(apiKey, family: .openRouter, required: true) ?? ""80            secrets.add(key)81            var headers = Self.headers(key)82            headers["Accept"] = "text/event-stream"83            let timeout = http.environment.timeouts.streamIdle84            try await runChatCompletionsStream(http: http, request: request, dialect: Self.dialect, secrets: [key], makeRequest: { body in85                ProviderHTTP.request(url, method: "POST", headers: headers, body: body, timeout: timeout)86            }, continuation: continuation)87        }88    }89}90
Files main
Menu

Theme