SPB Git

Repository Public

MistralProvider.swift 7.1 KB 142 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Astra9// File             : Packages/AstraProviders/Sources/MistralProvider.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/// Mistral through Chat Completions (`POST https://api.mistral.ai/v1/chat/completions`).92///93/// Differences from the OpenAI dialect, all observed on the live API on 2026-11-22: the seed is `random_seed` (`seed` is a 422),94/// usage always arrives on the finishing chunk, reasoning arrives inside `delta.content` as typed `thinking` chunks, the accepted95/// `reasoning_effort` values differ per model, an unknown model is a 400 `invalid_model`, and a validation error puts a list in `message`.96public struct MistralProvider: ChatProvider {97    public let kind: ProviderKind = .mistral98    public static let defaultBaseURL = URL(string: "https://api.mistral.ai/v1")!99    static let dialect = ChatCompletionsDialect(reasoning: .effortFieldWithNone, replay: .thinkingChunks(format: "mistral.thinking"), requestsUsage: false, includesRouting: false, seedKey: "random_seed",100                                                adjust: EffortFallback.adjust, normalize: MistralProvider.normalize)101102    private let core: KeyedChatCompletions103104    public init(transport: any HTTPTransport, apiKey: @escaping KeyProvider, diagnostics: (any DiagnosticsSink)? = nil, baseURL: URL = MistralProvider.defaultBaseURL) {105        core = KeyedChatCompletions(kind: .mistral, transport: transport, apiKey: apiKey, diagnostics: diagnostics, baseURL: baseURL, dialect: Self.dialect)106    }107108    /// `{"object":"error","message":"Invalid model: …","type":"invalid_model","code":"1500"}` comes with HTTP 400.109    static func normalize(_ failure: ProviderHTTP.Failure) -> ProviderHTTP.Failure {110        var f = failure111        if f.status == 400, (f.body.code ?? "").lowercased().contains("invalid_model") { f.status = 404 }112        return f113    }114115    public func listModels() async throws -> [ModelInfo] {116        let key = try core.key()117        let fetchedAt = Date()118        return try await core.modelEntries(key: key).compactMap { Self.modelInfo($0, fetchedAt: fetchedAt) }119    }120121    /// Only chat models are listed; embedding, moderation, OCR, transcription and speech models answer other endpoints.122    static func modelInfo(_ entry: JSONValue, fetchedAt: Date) -> ModelInfo? {123        guard let id = entry["id"]?.stringValue, let reported = entry["capabilities"], reported["completion_chat"]?.boolValue == true else { return nil }124        var capabilities: Set<Capability> = [.text]125        if reported["function_calling"]?.boolValue == true { capabilities.insert(.tools) }126        if reported["vision"]?.boolValue == true { capabilities.insert(.vision) }127        if reported["reasoning"]?.boolValue == true { capabilities.insert(.reasoning) }128        if reported["audio"]?.boolValue == true { capabilities.insert(.audioInput) }129        // `created` is the time of the request, not of the model, so it is not used. Prices are not in the API.130        return ModelInfo(ref: ModelRef(provider: .mistral, modelID: id), displayName: id, summary: entry["description"]?.stringValue.map { String($0.prefix(400)) },131                         contextLength: entry["max_context_length"]?.intValue, capabilities: capabilities, source: .providerAPI(fetchedAt: fetchedAt),132                         vendor: entry["owned_by"]?.stringValue ?? "mistralai")133    }134135    public func verify() async throws -> ConnectionStatus {136        let models = try await listModels()137        return ConnectionStatus(ok: true, detail: "Key accepted. \(models.count) chat models available.", modelCount: models.count)138    }139140    public func stream(_ request: GenerationRequest) -> AsyncThrowingStream<StreamEvent, Error> { core.stream(request) }141}142
Files main
Menu

Theme