SPB Git

Repository Public License

UsageLedger.swift 4.7 KB 111 lines swift

1import Foundation2import NavigatorCore34/// One finished (or interrupted) request.5public struct UsageRecord: Sendable, Hashable, Codable {6    public var date: Date7    /// `ProviderConfiguration.id`.8    public var providerID: String9    public var family: ProviderFamily10    public var model: String11    /// The Orbit space the request was made in, when the caller said so.12    public var spaceID: SpaceID?13    /// `nil` when the provider reported no usage for this request.14    public var usage: ProviderUsage?15    /// `nil` when no cost could be estimated.16    public var cost: CostEstimate?1718    public init(date: Date = .now, providerID: String, family: ProviderFamily, model: String, spaceID: SpaceID? = nil,19                usage: ProviderUsage?, cost: CostEstimate?) {20        self.date = date; self.providerID = providerID; self.family = family; self.model = model21        self.spaceID = spaceID; self.usage = usage; self.cost = cost22    }23}2425/// Sums over a set of records. Unknown values are counted apart instead of being treated as zero.26public struct UsageTotals: Sendable, Hashable, Codable {27    public var requests = 028    /// Requests for which the provider reported no token usage; their tokens are missing from the sums below.29    public var requestsWithUnknownUsage = 030    /// Requests whose cost could not be estimated; their cost is missing from `estimatedCostUSD`.31    public var requestsWithUnknownCost = 032    public var inputTokens = 033    public var outputTokens = 034    public var cacheReadTokens = 035    public var cacheWriteTokens = 036    /// An estimate (see `CostEstimate`), and a lower bound whenever `requestsWithUnknownCost > 0`.37    public var estimatedCostUSD: Double = 03839    public init() {}4041    public mutating func add(_ record: UsageRecord) {42        requests += 143        if let usage = record.usage, usage.isReported {44            inputTokens += usage.inputTokens ?? 045            outputTokens += usage.outputTokens ?? 046            cacheReadTokens += usage.cacheReadTokens ?? 047            cacheWriteTokens += usage.cacheWriteTokens ?? 048        } else {49            requestsWithUnknownUsage += 150        }51        if let cost = record.cost { estimatedCostUSD += cost.usd } else { requestsWithUnknownCost += 1 }52    }5354    /// The shared `TokenUsage` of NavigatorCore. The cost is `nil` when no request had an estimate.55    public var tokenUsage: TokenUsage {56        TokenUsage(inputTokens: inputTokens, outputTokens: outputTokens,57                   estimatedCostUSD: requests > requestsWithUnknownCost ? estimatedCostUSD : nil)58    }59}6061/// Where usage is accumulated. The app can implement it over its database; `InMemoryUsageLedger` keeps it for the62/// lifetime of the process.63public protocol UsageLedger: Sendable {64    func record(_ record: UsageRecord) async65    /// Totals over records matching every given filter, from `since` (inclusive) onwards.66    func totals(providerID: String?, spaceID: SpaceID?, since: Date?) async -> UsageTotals67    func totalsByProvider(since: Date?) async -> [String: UsageTotals]68    func totalsBySpace(since: Date?) async -> [SpaceID: UsageTotals]69    func removeAll() async70}7172public actor InMemoryUsageLedger: UsageLedger {73    private var records: [UsageRecord] = []74    /// Oldest records are dropped beyond this count so a long session cannot grow without bound.75    private let capacity: Int7677    public init(capacity: Int = 50_000) { self.capacity = max(1, capacity) }7879    public func record(_ record: UsageRecord) {80        records.append(record)81        if records.count > capacity { records.removeFirst(records.count - capacity) }82    }8384    public func allRecords() -> [UsageRecord] { records }8586    public func totals(providerID: String? = nil, spaceID: SpaceID? = nil, since: Date? = nil) -> UsageTotals {87        var totals = UsageTotals()88        for record in records where (providerID == nil || record.providerID == providerID) && (spaceID == nil || record.spaceID == spaceID)89            && (since == nil || record.date >= since!) {90            totals.add(record)91        }92        return totals93    }9495    public func totalsByProvider(since: Date? = nil) -> [String: UsageTotals] {96        var out: [String: UsageTotals] = [:]97        for record in records where since == nil || record.date >= since! { out[record.providerID, default: UsageTotals()].add(record) }98        return out99    }100101    public func totalsBySpace(since: Date? = nil) -> [SpaceID: UsageTotals] {102        var out: [SpaceID: UsageTotals] = [:]103        for record in records where since == nil || record.date >= since! {104            if let space = record.spaceID { out[space, default: UsageTotals()].add(record) }105        }106        return out107    }108109    public func removeAll() { records.removeAll() }110}111
Files main
Menu

Theme