SPB Git

Repository Public MIT

Usage.swift 9.0 KB 181 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Astra9// File             : Packages/AstraPersistence/Sources/Usage.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 Foundation89import GRDB90import AstraCore9192public extension AstraStore {93    /// Adds one finished generation to the ledger. Conversations and arena entries do this themselves when they are finalized.94    func recordUsage(_ record: UsageRecord) async throws { try await write { db in try record.insert(db) } }9596    /// Most recent first.97    func usageRecords(from start: Date? = nil, to end: Date? = nil, limit: Int? = nil) async throws -> [UsageRecord] {98        try await read { db in try Self.usageRecords(db, from: start, to: end, limit: limit) }99    }100101    /// Sums for charts. Days are calendar days in `timeZone`, oldest first; the other groupings are sorted by total tokens, largest first.102    func usageAggregates(by grouping: UsageGrouping, from start: Date? = nil, to end: Date? = nil,103                         timeZone: TimeZone = .current) async throws -> [UsageAggregate] {104        let records = try await read { db in try Self.usageRecords(db, from: start, to: end, limit: nil) }105        var calendar = Calendar(identifier: .gregorian)106        calendar.timeZone = timeZone107        var order: [String] = []108        var groups: [String: UsageAggregate] = [:]109        for record in records {110            let key: String, label: String111            switch grouping {112            case .day:113                let parts = calendar.dateComponents([.year, .month, .day], from: record.date)114                key = String(format: "%04d-%02d-%02d", parts.year ?? 0, parts.month ?? 0, parts.day ?? 0); label = key115            case .provider: key = record.provider.rawValue; label = record.provider.displayName116            case .model: key = record.provider.rawValue + "|" + record.modelID; label = record.modelID117            case .origin: key = record.origin.rawValue; label = record.origin.rawValue118            }119            if groups[key] == nil {120                order.append(key)121                groups[key] = UsageAggregate(key: key, label: label, requests: 0, inputTokens: 0, outputTokens: 0, cachedInputTokens: 0,122                                             reasoningTokens: 0, costUSD: 0, unpricedRequests: 0)123            }124            groups[key]?.requests += 1125            groups[key]?.inputTokens += record.inputTokens126            groups[key]?.outputTokens += record.outputTokens127            groups[key]?.cachedInputTokens += record.cachedInputTokens128            groups[key]?.reasoningTokens += record.reasoningTokens129            if let cost = record.costUSD { groups[key]?.costUSD += cost } else { groups[key]?.unpricedRequests += 1 }130        }131        let all = order.compactMap { groups[$0] }132        switch grouping {133        case .day: return all.sorted { $0.key < $1.key }134        default: return all.sorted { ($0.totalTokens, $1.key) > ($1.totalTokens, $0.key) }135        }136    }137138    /// Totals over a period as a single aggregate.139    func usageTotal(from start: Date? = nil, to end: Date? = nil) async throws -> UsageAggregate {140        try await read { db in141            var sql = "SELECT COUNT(*), TOTAL(inputTokens), TOTAL(outputTokens), TOTAL(cachedInputTokens), TOTAL(reasoningTokens), TOTAL(costUSD), SUM(costUSD IS NULL) FROM usage"142            let (condition, arguments) = Self.usageRange(start, end)143            sql += condition144            let row = try Row.fetchOne(db, sql: sql, arguments: arguments)145            func int(_ index: Int) -> Int { Int((row?[index] as Double?) ?? 0) }146            return UsageAggregate(key: "total", label: "Total", requests: (row?[0] as Int?) ?? 0, inputTokens: int(1), outputTokens: int(2),147                                  cachedInputTokens: int(3), reasoningTokens: int(4), costUSD: (row?[5] as Double?) ?? 0,148                                  unpricedRequests: (row?[6] as Int?) ?? 0)149        }150    }151152    func exportUsage(_ format: ExportFormat, from start: Date? = nil, to end: Date? = nil) async throws -> String {153        let records = try await usageRecords(from: start, to: end)154        let header = ["date", "provider", "model", "input_tokens", "output_tokens", "cached_input_tokens", "reasoning_tokens", "cost_usd",155                      "cost_basis", "origin"]156        let rows = records.map { r in157            [ExportCoding.iso(r.date), r.provider.rawValue, r.modelID, String(r.inputTokens), String(r.outputTokens), String(r.cachedInputTokens),158             String(r.reasoningTokens), CSVWriter.number(r.costUSD), r.costBasis.rawValue, r.origin.rawValue]159        }160        switch format {161        case .json: return String(decoding: try ExportCoding.encoder.encode(records), as: UTF8.self)162        case .csv: return CSVWriter.document(header: header, rows: rows)163        case .markdown: return Markdown.table(header: header, rows: rows)164        }165    }166}167168extension AstraStore {169    static func usageRange(_ start: Date?, _ end: Date?) -> (String, StatementArguments) {170        var conditions: [String] = []; var arguments: [Double] = []171        if let start { conditions.append("date >= ?"); arguments.append(start.dbValue) }172        if let end { conditions.append("date < ?"); arguments.append(end.dbValue) }173        return (conditions.isEmpty ? "" : " WHERE " + conditions.joined(separator: " AND "), StatementArguments(arguments))174    }175176    static func usageRecords(_ db: Database, from start: Date?, to end: Date?, limit: Int?) throws -> [UsageRecord] {177        let (condition, arguments) = usageRange(start, end)178        return try UsageRecord.fetchReadable(db, sql: "SELECT * FROM usage\(condition) ORDER BY date DESC, id LIMIT \(limit ?? -1)", arguments: arguments)179    }180}181
Files main
Menu

Theme