Repository Public MIT
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Astra9// File : Packages/AstraProviders/Sources/OpenRouterProvider.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/// OpenRouter through Chat Completions (`POST /api/v1/chat/completions`).92public struct OpenRouterProvider: ChatProvider {93 public let kind: ProviderKind = .openRouter94 public static let defaultBaseURL = URL(string: "https://openrouter.ai/api/v1")!95 public static let referer = "https://www.orixlab.dev"96 public static let title = "ORIX Astra"97 static let dialect = ChatCompletionsDialect(reasoning: .object, requestsUsage: false, includesRouting: true)9899 private let http: ProviderHTTP100 private let apiKey: KeyProvider101 private let baseURL: URL102103 public init(transport: any HTTPTransport, apiKey: @escaping KeyProvider, diagnostics: (any DiagnosticsSink)? = nil, baseURL: URL = OpenRouterProvider.defaultBaseURL) {104 self.http = ProviderHTTP(kind: .openRouter, transport: transport, diagnostics: diagnostics)105 self.apiKey = apiKey106 self.baseURL = baseURL107 }108109 /// App attribution. `X-OpenRouter-Title` is the current name; `X-Title` is still honoured and kept for older deployments.110 static func headers(_ key: String?) -> [String: String] {111 var h = ["HTTP-Referer": referer, "X-Title": title, "X-OpenRouter-Title": title]112 if let key, !key.isEmpty { h["Authorization"] = "Bearer \(key)" }113 return h114 }115116 // MARK: Models117118 public func listModels() async throws -> [ModelInfo] {119 // The catalogue is public; the key is sent when there is one so account-specific availability applies.120 let key = try resolveKey(apiKey, kind: kind, required: false)121 let (json, _) = try await http.json(ProviderHTTP.request(baseURL.appendingPathComponent("models"), headers: Self.headers(key)), secrets: [key].compactMap { $0 })122 guard let data = json["data"]?.arrayValue else { throw AstraError.decoding("the model list has no data array") }123 let fetchedAt = Date()124 return data.compactMap { Self.modelInfo($0, fetchedAt: fetchedAt) }125 }126127 static func modelInfo(_ entry: JSONValue, fetchedAt: Date) -> ModelInfo? {128 guard let id = entry["id"]?.stringValue else { return nil }129 let outputs = entry["architecture"]?["output_modalities"]?.arrayValue?.compactMap(\.stringValue) ?? ["text"]130 guard outputs.contains("text") else { return nil }131 let inputs = Set(entry["architecture"]?["input_modalities"]?.arrayValue?.compactMap(\.stringValue) ?? [])132 let parameters = entry["supported_parameters"]?.arrayValue.map { Set($0.compactMap(\.stringValue)) }133 var capabilities: Set<Capability> = [.text]134 if inputs.contains("image") { capabilities.insert(.vision) }135 if inputs.contains("audio") { capabilities.insert(.audioInput) }136 if inputs.contains("file") { capabilities.insert(.documents) }137 if let parameters {138 if parameters.contains("tools") { capabilities.insert(.tools) }139 if parameters.contains("reasoning") || parameters.contains("include_reasoning") { capabilities.insert(.reasoning) }140 if parameters.contains("structured_outputs") { capabilities.insert(.structuredOutput) }141 }142 // Prices are strings in US dollars per token; a negative price marks a router whose cost depends on the model it picks.143 var pricing: Pricing?144 let prices = entry["pricing"]145 if let input = prices?["prompt"]?.doubleValue, let output = prices?["completion"]?.doubleValue, input >= 0, output >= 0 {146 let read = prices?["input_cache_read"]?.doubleValue.map { $0 * 1_000_000 }147 let write = prices?["input_cache_write"]?.doubleValue.map { $0 * 1_000_000 }148 if read != nil { capabilities.insert(.promptCaching) }149 pricing = Pricing(inputPerMTok: Self.perMillion(input), outputPerMTok: Self.perMillion(output), cachedInputPerMTok: read.map(Self.rounded),150 cacheWritePerMTok: write.map(Self.rounded), asOf: fetchedAt.isoDay, sourceURL: "https://openrouter.ai/api/v1/models")151 }152 let summary = entry["description"]?.stringValue.map { String($0.prefix(400)) }153 return ModelInfo(ref: ModelRef(provider: .openRouter, modelID: id), displayName: entry["name"]?.stringValue ?? id, summary: summary,154 contextLength: entry["context_length"]?.intValue ?? entry["top_provider"]?["context_length"]?.intValue,155 maxOutputTokens: entry["top_provider"]?["max_completion_tokens"]?.intValue, capabilities: capabilities,156 source: .providerAPI(fetchedAt: fetchedAt), pricing: pricing, supportedParameters: parameters,157 vendor: id.split(separator: "/").first.map(String.init), createdAt: entry["created"]?.doubleValue.map { Date(timeIntervalSince1970: $0) })158 }159160 static func perMillion(_ perToken: Double) -> Double { rounded(perToken * 1_000_000) }161 /// Removes binary floating-point noise (0.000002 × 1e6 = 2.0000000000000004).162 static func rounded(_ value: Double) -> Double { (value * 1_000_000).rounded() / 1_000_000 }163164 // MARK: Key165166 public func verify() async throws -> ConnectionStatus {167 let key = try resolveKey(apiKey, kind: kind, required: true) ?? ""168 let (json, _) = try await http.json(ProviderHTTP.request(baseURL.appendingPathComponent("key"), headers: Self.headers(key)), secrets: [key])169 let data = json["data"] ?? json170 var remaining = data["limit_remaining"]?.doubleValue171 var detail = "Key accepted."172 if remaining == nil {173 // A key without its own limit: the account balance is the bound. Not every key may read it, so a failure is not an error.174 if let (credits, _) = try? await http.json(ProviderHTTP.request(baseURL.appendingPathComponent("credits"), headers: Self.headers(key)), secrets: [key]),175 let total = (credits["data"] ?? credits)["total_credits"]?.doubleValue, let used = (credits["data"] ?? credits)["total_usage"]?.doubleValue {176 remaining = max(0, total - used)177 }178 }179 if data["is_free_tier"]?.boolValue == true { detail += " Free tier." }180 return ConnectionStatus(ok: true, detail: detail, remainingCreditUSD: remaining)181 }182183 // MARK: Stream184185 public func stream(_ request: GenerationRequest) -> AsyncThrowingStream<StreamEvent, Error> {186 let http = http, apiKey = apiKey, url = baseURL.appendingPathComponent("chat/completions")187 let secretBox = SecretBox()188 return makeEventStream(secrets: { secretBox.values }) { continuation in189 let key = try resolveKey(apiKey, kind: .openRouter, required: true) ?? ""190 secretBox.add(key)191 var headers = Self.headers(key)192 headers["Accept"] = "text/event-stream"193 try await runChatCompletionsStream(http: http, request: request, dialect: Self.dialect, secrets: [key], makeRequest: { body in194 ProviderHTTP.request(url, method: "POST", headers: headers, body: body)195 }, continuation: continuation)196 }197 }198}199