Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Astra9// File : Packages/AstraCore/Sources/Budget.swift10// Module : Packages11// Repository : https://git.spboucher.ai/orix-astra12// Created : 2026-11-2113// Last Modified : 2026-11-2114//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 Foundation8990/// Token estimation used when no tokenizer is available. Always labelled as an estimate in the UI.91public enum TokenEstimator {92 /// Conservative heuristic: about 3.6 UTF-8 bytes per token for Latin text, 1.6 characters for CJK. Overestimates slightly on purpose.93 public static func estimate(_ text: String) -> Int {94 guard !text.isEmpty else { return 0 }95 var cjk = 0, other = 096 for scalar in text.unicodeScalars {97 switch scalar.value {98 case 0x3040...0x30FF, 0x3400...0x4DBF, 0x4E00...0x9FFF, 0xAC00...0xD7AF, 0xF900...0xFAFF: cjk += 199 default: other += scalar.utf8.count100 }101 }102 return Int((Double(other) / 3.6).rounded(.up)) + Int((Double(cjk) / 1.6).rounded(.up))103 }104105 /// Per-image allowance; providers bill images differently, so this is a deliberately generous flat figure.106 public static let imageAllowance = 1_200107108 public static func estimate(_ message: PromptMessage) -> Int {109 var n = 4 + estimate(message.text) + message.images.count * imageAllowance110 for call in message.toolCalls {111 n += 8 + estimate(call.id) + estimate(call.name) + estimate(call.arguments.serialized())112 // reasoning state replayed with the call (thinking blocks, encrypted reasoning) is sent too113 if let state = call.providerState { n += estimate(state.serialized()) }114 }115 if let name = message.toolName { n += estimate(name) }116 return n117 }118}119120public enum TruncationStrategy: String, Sendable, Codable, CaseIterable, Identifiable {121 /// Drop the oldest turns until the conversation fits.122 case dropOldest123 /// Keep the first exchange (which usually sets the task) and the most recent turns; drop the middle.124 case keepFirstAndRecent125 /// Never drop anything: fail before sending when the conversation does not fit.126 case strict127 public var id: String { rawValue }128 public var title: String {129 switch self {130 case .dropOldest: "Drop oldest turns"131 case .keepFirstAndRecent: "Keep first exchange and recent turns"132 case .strict: "Never truncate"133 }134 }135}136137public struct ContextBudget: Sendable, Hashable, Codable {138 /// Total window in tokens (model limit, or the user's lower cap).139 public var window: Int140 /// Tokens reserved for the answer.141 public var reservedForOutput: Int142 public var strategy: TruncationStrategy143 public init(window: Int, reservedForOutput: Int, strategy: TruncationStrategy = .dropOldest) {144 self.window = max(256, window); self.reservedForOutput = max(0, reservedForOutput); self.strategy = strategy145 }146 public var inputBudget: Int { max(64, window - reservedForOutput) }147148 public struct Plan: Sendable, Hashable {149 public var messages: [PromptMessage]150 public var droppedCount: Int151 public var estimatedInputTokens: Int152 public var inputBudget: Int153 public var systemTokens: Int154 public var fits: Bool155 public var fraction: Double { inputBudget > 0 ? min(1, Double(estimatedInputTokens) / Double(inputBudget)) : 1 }156 }157158 /// Fits `messages` in the budget. Turns are dropped in whole units so a tool result never loses the call it answers,159 /// and the final user turn is never dropped.160 public func plan(system: String?, messages: [PromptMessage], toolsOverhead: Int = 0, count: (PromptMessage) -> Int = TokenEstimator.estimate) -> Plan {161 let systemTokens = (system.map(TokenEstimator.estimate) ?? 0) + toolsOverhead162 let units = Self.units(messages)163 let costs = units.map { $0.reduce(0) { $0 + count($1) } }164 let total = systemTokens + costs.reduce(0, +)165 if total <= inputBudget || units.count <= 1 || strategy == .strict {166 return Plan(messages: messages, droppedCount: 0, estimatedInputTokens: total, inputBudget: inputBudget, systemTokens: systemTokens, fits: total <= inputBudget)167 }168 // The turn being answered is the unit holding the last user message, together with everything after it (the tool169 // exchanges of the answer in progress). Nothing from there on is ever dropped.170 let protectedFrom = units.lastIndex { $0.first?.role == .user } ?? (units.count - 1)171 var keep = Array(repeating: true, count: units.count)172 var running = total173 let candidates: [Int] = switch strategy {174 case .keepFirstAndRecent: Array(min(Self.firstExchangeEnd(units), protectedFrom)..<protectedFrom)175 default: Array(0..<protectedFrom)176 }177 for i in candidates where running > inputBudget { keep[i] = false; running -= costs[i] }178 if running > inputBudget, strategy == .keepFirstAndRecent {179 for i in 0..<protectedFrom where keep[i] && running > inputBudget { keep[i] = false; running -= costs[i] }180 }181 // A conversation must not start with an assistant or tool turn after truncation: leading units go whole, so a tool182 // result never loses the call it answers.183 for i in 0..<protectedFrom where keep[i] {184 if units[i].first?.role == .user { break }185 keep[i] = false; running -= costs[i]186 }187 var kept: [PromptMessage] = []; var dropped = 0188 for (i, unit) in units.enumerated() { if keep[i] { kept += unit } else { dropped += unit.count } }189 return Plan(messages: kept, droppedCount: dropped, estimatedInputTokens: running, inputBudget: inputBudget, systemTokens: systemTokens, fits: running <= inputBudget)190 }191192 /// Groups an assistant turn that called tools with the tool results that answer it.193 static func units(_ messages: [PromptMessage]) -> [[PromptMessage]] {194 var out: [[PromptMessage]] = []195 for m in messages {196 if m.role == .tool, let last = out.last, last.first?.role == .assistant, !(last.first?.toolCalls.isEmpty ?? true) { out[out.count - 1].append(m) }197 else { out.append([m]) }198 }199 return out200 }201202 static func firstExchangeEnd(_ units: [[PromptMessage]]) -> Int {203 var i = 0204 if i < units.count, units[i].first?.role == .user { i += 1 }205 while i < units.count, units[i].first?.role != .user { i += 1 }206 return min(i, max(0, units.count - 1))207 }208}209210// MARK: - Cost211212/// A cost figure with its basis. `amountUSD` is nil when either usage or pricing is unavailable; it is never guessed.213public struct CostEstimate: Sendable, Hashable, Codable {214 public enum Basis: String, Sendable, Codable {215 case reportedByProvider, estimatedFromUsage, estimatedFromText, onDevice, unavailable216 }217 public var amountUSD: Double?218 public var basis: Basis219 public var pricingAsOf: String?220 public init(amountUSD: Double?, basis: Basis, pricingAsOf: String? = nil) { self.amountUSD = amountUSD; self.basis = basis; self.pricingAsOf = pricingAsOf }221 public static let unavailable = CostEstimate(amountUSD: nil, basis: .unavailable)222 public static let onDevice = CostEstimate(amountUSD: 0, basis: .onDevice)223224 public var label: String {225 switch basis {226 case .onDevice: return "On device"227 case .unavailable: return "Cost unavailable"228 default:229 guard let amountUSD else { return "Cost unavailable" }230 let prefix = basis == .reportedByProvider ? "" : "≈ "231 return prefix + Self.format(amountUSD)232 }233 }234235 public static func format(_ usd: Double) -> String {236 if usd == 0 { return "$0" }237 if usd < 0.0001 { return "< $0.0001" }238 if usd < 0.01 { return String(format: "$%.4f", usd) }239 if usd < 1 { return String(format: "$%.3f", usd) }240 return String(format: "$%.2f", usd)241 }242}243244public enum UsageAccounting {245 /// Cost of a finished generation: the provider's own figure when it reports one, otherwise usage × published price.246 public static func cost(usage: TokenUsage?, pricing: Pricing?, provider: ProviderKind) -> CostEstimate {247 if provider.isLocal { return .onDevice }248 if let reported = usage?.reportedCostUSD { return CostEstimate(amountUSD: reported, basis: .reportedByProvider) }249 guard let usage, let pricing, usage.inputTokens != nil || usage.outputTokens != nil else { return .unavailable }250 let cached = usage.cachedInputTokens ?? 0251 let written = usage.cacheWriteTokens ?? 0252 // Providers differ on whether cached tokens are included in input_tokens; adapters normalise so that253 // `inputTokens` is the total prompt and cached / written counts are subsets of it.254 let fresh = max(0, (usage.inputTokens ?? 0) - cached - written)255 var usd = Double(fresh) * pricing.inputPerMTok256 usd += Double(cached) * (pricing.cachedInputPerMTok ?? pricing.inputPerMTok)257 usd += Double(written) * (pricing.cacheWritePerMTok ?? pricing.inputPerMTok)258 usd += Double(usage.outputTokens ?? 0) * pricing.outputPerMTok259 return CostEstimate(amountUSD: usd / 1_000_000, basis: .estimatedFromUsage, pricingAsOf: pricing.asOf)260 }261262 /// Upper-bound estimate before sending (Arena guard): estimated prompt tokens plus the full output cap.263 public static func preflight(inputTokens: Int, maxOutputTokens: Int, pricing: Pricing?, provider: ProviderKind) -> CostEstimate {264 if provider.isLocal { return .onDevice }265 guard let pricing else { return .unavailable }266 let usd = (Double(inputTokens) * pricing.inputPerMTok + Double(maxOutputTokens) * pricing.outputPerMTok) / 1_000_000267 return CostEstimate(amountUSD: usd, basis: .estimatedFromText, pricingAsOf: pricing.asOf)268 }269}270271/// Drops or adjusts parameters a model does not accept, and reports what was changed so the UI can say so.272public enum ParameterNegotiator {273 public struct Result: Sendable, Hashable {274 public var parameters: GenerationParameters275 public var tools: [ToolDefinition]276 public var notes: [String]277 }278279 public static func negotiate(_ parameters: GenerationParameters, tools: [ToolDefinition], images: Bool, for model: ModelInfo) -> Result {280 var p = parameters; var t = tools; var notes: [String] = []281 if let supported = model.supportedParameters {282 if p.temperature != nil, !supported.contains("temperature") { p.temperature = nil; notes.append("Temperature is not accepted by this model.") }283 if p.topP != nil, !supported.contains("top_p") { p.topP = nil; notes.append("Top-p is not accepted by this model.") }284 if p.seed != nil, !supported.contains("seed") { p.seed = nil; notes.append("Seed is not accepted by this model.") }285 if !p.stop.isEmpty, !supported.contains("stop") { p.stop = []; notes.append("Stop sequences are not accepted by this model.") }286 }287 if let effort = p.reasoning, effort != .off, !model.capabilities.contains(.reasoning) {288 p.reasoning = nil; notes.append("This model has no reasoning control.")289 }290 if !t.isEmpty, !model.capabilities.contains(.tools) { t = []; notes.append("This model does not support tools.") }291 if images, !model.capabilities.contains(.vision) { notes.append("This model cannot read images; they were left out.") }292 if let cap = model.maxOutputTokens, let requested = p.maxOutputTokens, requested > cap {293 p.maxOutputTokens = cap; notes.append("Output limit lowered to the model's maximum (\(cap)).")294 }295 return Result(parameters: p, tools: t, notes: notes)296 }297}298