Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Astra9// File : Packages/AstraProviders/Sources/DeepSeekProvider.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/// DeepSeek through Chat Completions (`POST https://api.deepseek.com/chat/completions`; the documented base URL has no `/v1`).92///93/// Thinking is on by default and returned in `delta.reasoning_content`. It is switched off with `thinking: {"type": "disabled"}`.94/// In thinking mode a request that carries tools must replay `reasoning_content` on earlier assistant turns or it is a 400.95/// A tool-calling turn's reasoning is kept in `ToolCall.providerState` and replayed; a turn without it (a plain answer, a96/// conversation from an older build) gets an empty `reasoning_content`, which the live API accepted on 2026-11-22.97public struct DeepSeekProvider: ChatProvider {98 public let kind: ProviderKind = .deepSeek99 public static let defaultBaseURL = URL(string: "https://api.deepseek.com")!100 static let dialect = ChatCompletionsDialect(reasoning: .managed, replay: .reasoningField(format: "deepseek.reasoning_content", field: "reasoning_content"), requestsUsage: true, includesRouting: false,101 prepare: DeepSeekProvider.prepare, normalize: DeepSeekProvider.normalize)102103 private let core: KeyedChatCompletions104105 public init(transport: any HTTPTransport, apiKey: @escaping KeyProvider, diagnostics: (any DiagnosticsSink)? = nil, baseURL: URL = DeepSeekProvider.defaultBaseURL) {106 core = KeyedChatCompletions(kind: .deepSeek, transport: transport, apiKey: apiKey, diagnostics: diagnostics, baseURL: baseURL, dialect: Self.dialect)107 }108109 /// DeepSeek documents three efforts (`low`, `high`, `max`) and folds `medium` into `high`; the app's three levels map onto the three.110 static func effort(_ effort: ReasoningEffort) -> String {111 switch effort {112 case .off, .low: "low"113 case .medium: "high"114 case .high: "max"115 }116 }117118 static func prepare(_ request: GenerationRequest, _ body: inout [String: JSONValue]) {119 let reasoning = request.parameters.reasoning120 switch reasoning {121 case nil: break // provider default: thinking enabled, effort high122 case .off?: body["thinking"] = ["type": "disabled"]123 case let level?:124 body["thinking"] = ["type": "enabled"]125 body["reasoning_effort"] = .string(effort(level))126 }127 // Thinking mode with tools: every earlier assistant turn must carry `reasoning_content`. Turns that replay their128 // own reasoning already have it; the empty string is the fallback for the others.129 let usesTools = !request.tools.isEmpty || request.messages.contains { !$0.toolCalls.isEmpty || $0.role == .tool }130 guard reasoning != .off, usesTools, let messages = body["messages"]?.arrayValue else { return }131 body["messages"] = .array(messages.map { message in132 guard case .object(var fields) = message, fields["role"] == "assistant", fields["reasoning_content"] == nil else { return message }133 fields["reasoning_content"] = ""134 return .object(fields)135 })136 }137138 /// An unknown model is a 400 ("The supported API model names are …, but you passed …"); a rejected key is echoed as `****abcd`.139 static func normalize(_ failure: ProviderHTTP.Failure) -> ProviderHTTP.Failure {140 var f = failure141 let message = (f.body.message ?? "").lowercased()142 if f.status == 400, message.contains("supported api model names") { f.status = 404 }143 if let text = f.body.message {144 f.body.message = text.replacingOccurrences(of: #"\*{3,}[A-Za-z0-9_\-]{1,8}"#, with: "•••", options: .regularExpression)145 }146 return f147 }148149 public func listModels() async throws -> [ModelInfo] {150 let key = try core.key()151 let fetchedAt = Date()152 return try await core.modelEntries(key: key).compactMap { Self.modelInfo($0, fetchedAt: fetchedAt) }153 }154155 /// Limits, modalities and effort levels come from the API; tool calling, caching and prices from the documentation table.156 static func modelInfo(_ entry: JSONValue, fetchedAt: Date) -> ModelInfo? {157 guard let id = entry["id"]?.stringValue else { return nil }158 let outputs = entry["output_modalities"]?.arrayValue?.compactMap(\.stringValue) ?? ["text"]159 guard outputs.contains("text") else { return nil }160 let inputs = entry["input_modalities"]?.arrayValue?.compactMap(\.stringValue) ?? []161 let curated = CuratedCatalog.deepSeek(id)162 var capabilities: Set<Capability> = curated?.capabilities ?? [.text]163 if inputs.contains("image") { capabilities.insert(.vision) }164 if let levels = entry["effort"]?["supported_levels"]?.arrayValue, !levels.isEmpty { capabilities.insert(.reasoning) }165 return ModelInfo(ref: ModelRef(provider: .deepSeek, modelID: id), displayName: entry["name"]?.stringValue ?? id,166 contextLength: entry["context_window"]?.intValue, maxOutputTokens: entry["max_output_tokens"]?.intValue,167 capabilities: capabilities, source: .providerAPI(fetchedAt: fetchedAt), pricing: curated.map(CuratedCatalog.pricing),168 vendor: entry["owned_by"]?.stringValue ?? "deepseek")169 }170171 public func verify() async throws -> ConnectionStatus {172 let models = try await listModels()173 return ConnectionStatus(ok: true, detail: "Key accepted. \(models.count) models available.", modelCount: models.count)174 }175176 public func stream(_ request: GenerationRequest) -> AsyncThrowingStream<StreamEvent, Error> { core.stream(request) }177}178