SPB Git

Repository Public

DeepInfraProvider.swift 7.6 KB 145 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Astra9// File             : Packages/AstraProviders/Sources/DeepInfraProvider.swift10// Module           : Packages11// Repository       : https://git.spboucher.ai/orix-astra12// Created          : 2026-11-2213// 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 AstraCore89import Foundation9091/// DeepInfra through its OpenAI-compatible Chat Completions (`POST https://api.deepinfra.com/v1/openai/chat/completions`).92///93/// DeepInfra hosts other publishers' models under `owner/name` ids. The model list is public (readable without a key) and94/// carries context length, output cap, prices in US dollars per million tokens and capability tags. Reasoning is requested with95/// `reasoning_effort` (`none` switches it off; the field has no effect on other models) and is surfaced only when it arrives in a96/// dedicated `reasoning_content` / `reasoning` field; `<think>` text inside `content` is answer text and is passed through untouched.97public struct DeepInfraProvider: ChatProvider {98    public let kind: ProviderKind = .deepInfra99    public static let defaultBaseURL = URL(string: "https://api.deepinfra.com/v1/openai")!100    static let dialect = ChatCompletionsDialect(reasoning: .effortFieldWithNone, requestsUsage: true, includesRouting: false, adjust: EffortFallback.adjust)101102    private let core: KeyedChatCompletions103104    public init(transport: any HTTPTransport, apiKey: @escaping KeyProvider, diagnostics: (any DiagnosticsSink)? = nil, baseURL: URL = DeepInfraProvider.defaultBaseURL) {105        core = KeyedChatCompletions(kind: .deepInfra, transport: transport, apiKey: apiKey, diagnostics: diagnostics, baseURL: baseURL, dialect: Self.dialect)106    }107108    /// The catalogue is public, so it can be browsed before a key is entered; a stored key is sent so that a bad one is reported.109    public func listModels() async throws -> [ModelInfo] {110        let key = try core.key(required: false)111        let fetchedAt = Date()112        return try await core.modelEntries(key: key).compactMap { Self.modelInfo($0, fetchedAt: fetchedAt) }113    }114115    /// Chat models only (`metadata.tags` contains "chat"); image, video, speech and embedding models answer other endpoints.116    static func modelInfo(_ entry: JSONValue, fetchedAt: Date) -> ModelInfo? {117        guard let id = entry["id"]?.stringValue, let metadata = entry["metadata"] else { return nil }118        let tags = Set(metadata["tags"]?.arrayValue?.compactMap(\.stringValue) ?? [])119        guard tags.contains("chat") else { return nil }120        var capabilities: Set<Capability> = [.text]121        if tags.contains("vision") || tags.contains("vlm") { capabilities.insert(.vision) }122        if tags.contains("reasoning") || tags.contains("reasoning_effort") { capabilities.insert(.reasoning) }123        if tags.contains("prompt_cache") { capabilities.insert(.promptCaching) }124        var pricing: Pricing?125        let prices = metadata["pricing"]126        if let input = prices?["input_tokens"]?.doubleValue, let output = prices?["output_tokens"]?.doubleValue, input >= 0, output >= 0 {127            pricing = Pricing(inputPerMTok: roundedPrice(input), outputPerMTok: roundedPrice(output), cachedInputPerMTok: prices?["cache_read_tokens"]?.doubleValue.map(roundedPrice),128                              asOf: fetchedAt.isoDay, sourceURL: "https://api.deepinfra.com/v1/openai/models")129        }130        let name = id.split(separator: "/").last.map(String.init) ?? id131        return ModelInfo(ref: ModelRef(provider: .deepInfra, modelID: id), displayName: name, summary: metadata["description"]?.stringValue.map { String($0.prefix(400)) },132                         contextLength: metadata["context_length"]?.intValue, maxOutputTokens: metadata["max_tokens"]?.intValue, capabilities: capabilities,133                         source: .providerAPI(fetchedAt: fetchedAt), pricing: pricing, vendor: ModelInfo.owner(of: id) ?? entry["owned_by"]?.stringValue)134    }135136    public func verify() async throws -> ConnectionStatus {137        let key = try core.key()138        let fetchedAt = Date()139        let models = try await core.modelEntries(key: key).compactMap { Self.modelInfo($0, fetchedAt: fetchedAt) }140        return ConnectionStatus(ok: true, detail: "Key accepted. \(models.count) chat models available.", modelCount: models.count)141    }142143    public func stream(_ request: GenerationRequest) -> AsyncThrowingStream<StreamEvent, Error> { core.stream(request) }144}145
Files main
Menu

Theme