SPB Git

Repository Public

MoonshotProvider.swift 8.3 KB 173 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Astra9// File             : Packages/AstraProviders/Sources/MoonshotProvider.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/// Kimi (Moonshot AI) through Chat Completions (`POST https://api.moonshot.ai/v1/chat/completions`).92///93/// Moonshot runs two separate platforms with separate keys: the international one (`api.moonshot.ai`, documented at94/// platform.kimi.ai) and the mainland-China one (`api.moonshot.cn`). The default is the international platform; pass95/// `chinaBaseURL` for a key issued by the other.96///97/// Observed on the live API on 2026-11-22: usage arrives inside the finishing choice (`choices[0].usage`), thinking arrives in98/// `delta.reasoning_content`, and each model accepts exactly one `temperature` and one `top_p` value ("invalid temperature: only 199/// is allowed for this model"), so a rejected sampling parameter is dropped and the request retried.100public struct MoonshotProvider: ChatProvider {101    public let kind: ProviderKind = .moonshot102    public static let defaultBaseURL = URL(string: "https://api.moonshot.ai/v1")!103    public static let chinaBaseURL = URL(string: "https://api.moonshot.cn/v1")!104    static let dialect = ChatCompletionsDialect(reasoning: .managed, replay: .reasoningField(format: "moonshot.reasoning_content", field: "reasoning_content"),105                                                requestsUsage: false, includesRouting: false, maxTokensKey: "max_completion_tokens",106                                                prepare: MoonshotProvider.prepare, adjust: MoonshotProvider.adjust)107108    private let core: KeyedChatCompletions109110    public init(transport: any HTTPTransport, apiKey: @escaping KeyProvider, diagnostics: (any DiagnosticsSink)? = nil, baseURL: URL = MoonshotProvider.defaultBaseURL) {111        core = KeyedChatCompletions(kind: .moonshot, transport: transport, apiKey: apiKey, diagnostics: diagnostics, baseURL: baseURL, dialect: Self.dialect)112    }113114    /// The documented efforts are `low`, `high` and `max`.115    static func effort(_ effort: ReasoningEffort) -> String {116        switch effort {117        case .off, .low: "low"118        case .medium: "high"119        case .high: "max"120        }121    }122123    static func prepare(_ request: GenerationRequest, _ body: inout [String: JSONValue]) {124        switch request.parameters.reasoning {125        case nil: break126        case .off?: body["thinking"] = ["type": "disabled"]127        case let level?: body["reasoning_effort"] = .string(effort(level))128        }129    }130131    /// Drops what a model refuses: a fixed sampling parameter, or `thinking` on a model that cannot switch it off (Kimi K2.7 Code).132    static func adjust(_ failure: ProviderHTTP.Failure, _ body: inout [String: JSONValue]) -> Bool {133        guard failure.status == 400 else { return false }134        let message = (failure.body.message ?? "").lowercased()135        for key in ["temperature", "top_p"] where body[key] != nil && message.contains("invalid \(key)") {136            body.removeValue(forKey: key)137            return true138        }139        if body["thinking"] != nil, message.contains("thinking") {140            body.removeValue(forKey: "thinking")141            return true142        }143        return false144    }145146    public func listModels() async throws -> [ModelInfo] {147        let key = try core.key()148        let fetchedAt = Date()149        return try await core.modelEntries(key: key).compactMap { Self.modelInfo($0, fetchedAt: fetchedAt) }150    }151152    static func modelInfo(_ entry: JSONValue, fetchedAt: Date) -> ModelInfo? {153        guard let id = entry["id"]?.stringValue else { return nil }154        let outputs = entry["modalities"]?["output"]?.arrayValue?.compactMap(\.stringValue) ?? ["text"]155        guard outputs.contains("text") else { return nil }156        let inputs = entry["modalities"]?["input"]?.arrayValue?.compactMap(\.stringValue) ?? []157        var capabilities: Set<Capability> = [.text]158        if entry["supports_image_in"]?.boolValue == true || inputs.contains("image") { capabilities.insert(.vision) }159        if entry["supports_reasoning"]?.boolValue == true { capabilities.insert(.reasoning) }160        // The model list does not say which models call functions; that claim comes from the curated table.161        if CuratedCatalog.moonshotToolModels.contains(id) { capabilities.insert(.tools) }162        return ModelInfo(ref: ModelRef(provider: .moonshot, modelID: id), displayName: id, contextLength: entry["context_length"]?.intValue ?? entry["limit"]?["context"]?.intValue,163                         capabilities: capabilities, source: .providerAPI(fetchedAt: fetchedAt), vendor: entry["owned_by"]?.stringValue ?? "moonshot")164    }165166    public func verify() async throws -> ConnectionStatus {167        let models = try await listModels()168        return ConnectionStatus(ok: true, detail: "Key accepted. \(models.count) models available.", modelCount: models.count)169    }170171    public func stream(_ request: GenerationRequest) -> AsyncThrowingStream<StreamEvent, Error> { core.stream(request) }172}173
Files main
Menu

Theme