SPB Git

Repository Public

CerebrasProvider.swift 8.6 KB 156 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Astra9// File             : Packages/AstraProviders/Sources/CerebrasProvider.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/// Cerebras Inference through Chat Completions (`POST https://api.cerebras.ai/v1/chat/completions`).92///93/// Cerebras hosts other publishers' models. Reasoning arrives in `delta.reasoning` (the default `reasoning_format: "parsed"`),94/// usage on the finishing chunk, errors as a flat `{"message","type","param","code"}` object. `reasoning_effort` values differ95/// per model (`gpt-oss-120b` has no `none`), so a rejected effort is replaced by the nearest one the error lists.96public struct CerebrasProvider: ChatProvider {97    public let kind: ProviderKind = .cerebras98    public static let defaultBaseURL = URL(string: "https://api.cerebras.ai/v1")!99    static let dialect = ChatCompletionsDialect(reasoning: .effortFieldWithNone, replay: .reasoningField(format: "cerebras.reasoning", field: "reasoning"),100                                                requestsUsage: false, includesRouting: false, maxTokensKey: "max_completion_tokens",101                                                adjust: EffortFallback.adjust)102103    private let core: KeyedChatCompletions104105    public init(transport: any HTTPTransport, apiKey: @escaping KeyProvider, diagnostics: (any DiagnosticsSink)? = nil, baseURL: URL = CerebrasProvider.defaultBaseURL) {106        core = KeyedChatCompletions(kind: .cerebras, transport: transport, apiKey: apiKey, diagnostics: diagnostics, baseURL: baseURL, dialect: Self.dialect)107    }108109    /// `{base}/models` (keyed) says which models this key may use and nothing else; the public catalogue110    /// (`/public/v1/models`, no key) carries limits, capabilities, prices and the upstream Hugging Face id.111    var publicCatalogueURL: URL { core.baseURL.deletingLastPathComponent().appendingPathComponent("public").appendingPathComponent(core.baseURL.lastPathComponent).appendingPathComponent("models") }112113    public func listModels() async throws -> [ModelInfo] {114        let key = try core.key()115        let entries = try await core.modelEntries(key: key)116        var details: [String: JSONValue] = [:]117        if let catalogue = try? await core.get(publicCatalogueURL, key: nil) {118            for entry in catalogue["data"]?.arrayValue ?? [] { if let id = entry["id"]?.stringValue { details[id] = entry } }119        }120        let fetchedAt = Date()121        return entries.compactMap { entry in entry["id"]?.stringValue.map { Self.modelInfo(id: $0, listed: entry, detail: details[$0], fetchedAt: fetchedAt) } }122    }123124    static func modelInfo(id: String, listed: JSONValue, detail: JSONValue?, fetchedAt: Date) -> ModelInfo {125        var capabilities: Set<Capability> = [.text]126        let reported = detail?["capabilities"]127        if reported?["tools"]?.boolValue == true || reported?["function_calling"]?.boolValue == true { capabilities.insert(.tools) }128        if reported?["vision"]?.boolValue == true { capabilities.insert(.vision) }129        if reported?["reasoning"]?.boolValue == true { capabilities.insert(.reasoning) }130        if reported?["structured_outputs"]?.boolValue == true { capabilities.insert(.structuredOutput) }131        // Prices are strings in US dollars per token.132        var pricing: Pricing?133        if let input = detail?["pricing"]?["prompt"]?.doubleValue, let output = detail?["pricing"]?["completion"]?.doubleValue, input >= 0, output >= 0 {134            pricing = Pricing(inputPerMTok: roundedPrice(input * 1_000_000), outputPerMTok: roundedPrice(output * 1_000_000), asOf: fetchedAt.isoDay,135                              sourceURL: "https://api.cerebras.ai/public/v1/models")136        }137        let supported = detail?["supported_parameters"]?.objectValue.map { Set($0.filter { $0.value.boolValue == true }.keys) }138        // The publisher is the owner of the upstream Hugging Face repository ("openai/gpt-oss-120b" → "openai"), else what the API names.139        let publisher = detail?["hugging_face_id"]?.stringValue.flatMap(ModelInfo.owner(of:)) ?? ModelInfo.owner(of: id)140            ?? detail?["owned_by"]?.stringValue ?? listed["owned_by"]?.stringValue141        let created = (detail?["created"]?.doubleValue ?? listed["created"]?.doubleValue).flatMap { $0 > 0 ? Date(timeIntervalSince1970: $0) : nil }142        return ModelInfo(ref: ModelRef(provider: .cerebras, modelID: id), displayName: detail?["name"]?.stringValue ?? id,143                         summary: detail?["description"]?.stringValue.map { String($0.prefix(400)) },144                         contextLength: detail?["limits"]?["max_context_length"]?.intValue, maxOutputTokens: detail?["limits"]?["max_completion_tokens"]?.intValue,145                         capabilities: capabilities, source: .providerAPI(fetchedAt: fetchedAt), pricing: pricing, supportedParameters: supported,146                         vendor: publisher, createdAt: created)147    }148149    public func verify() async throws -> ConnectionStatus {150        let models = try await listModels()151        return ConnectionStatus(ok: true, detail: "Key accepted. \(models.count) models available.", modelCount: models.count)152    }153154    public func stream(_ request: GenerationRequest) -> AsyncThrowingStream<StreamEvent, Error> { core.stream(request) }155}156
Files main
Menu

Theme