SPB Git

Repository Public License

Pricing.swift 7.3 KB 141 lines swift

1import Foundation23/// Where a price came from. Shown next to every estimate so the user can judge it.4public enum PriceSource: Sendable, Hashable, Codable {5    /// Shipped with the app; `asOf` is the day the public price list at `url` was read.6    case builtIn(asOf: String, url: String)7    /// Typed by the user.8    case user9    /// Published by the provider's own model list (OpenRouter).10    case providerList(url: String, fetchedAt: Date)11}1213/// List prices in US dollars per million tokens.14public struct ModelPrice: Sendable, Hashable, Codable {15    public var inputPerMillion: Double16    public var outputPerMillion: Double17    /// Price of input tokens read from the prompt cache; `nil` bills them as ordinary input.18    public var cacheReadPerMillion: Double?19    /// Price of input tokens written to the prompt cache; `nil` bills them as ordinary input.20    public var cacheWritePerMillion: Double?21    public var source: PriceSource2223    public init(inputPerMillion: Double, outputPerMillion: Double, cacheReadPerMillion: Double? = nil, cacheWritePerMillion: Double? = nil,24                source: PriceSource = .user) {25        self.inputPerMillion = inputPerMillion; self.outputPerMillion = outputPerMillion26        self.cacheReadPerMillion = cacheReadPerMillion; self.cacheWritePerMillion = cacheWritePerMillion; self.source = source27    }28}2930/// A cost figure. Always an estimate: the provider's invoice is the only authoritative number.31public struct CostEstimate: Sendable, Hashable, Codable {32    public enum Basis: Sendable, Hashable, Codable {33        /// The provider reported this cost with the response (OpenRouter's `usage.cost`).34        case providerReported35        /// Reported token counts multiplied by a list price.36        case priceTable(PriceSource)37    }3839    public var usd: Double40    public var basis: Basis4142    /// Text for the UI. Says "estimate" in every case.43    public var label: String {44        let amount = usd < 0.01 ? String(format: "$%.4f", usd) : String(format: "$%.2f", usd)45        switch basis {46        case .providerReported: return "≈ \(amount) (estimate, as reported by the provider)"47        case .priceTable(.builtIn(let asOf, _)): return "≈ \(amount) (estimate from list prices of \(asOf))"48        case .priceTable(.user): return "≈ \(amount) (estimate from your price)"49        case .priceTable(.providerList): return "≈ \(amount) (estimate from the provider's published price)"50        }51    }52}5354/// An editable price list keyed by provider family and model id.55///56/// The built-in entries are a small convenience and go stale; the user can replace or add any entry, and live prices57/// from OpenRouter's model list take precedence for that family. A model with no entry has no estimate: the UI shows58/// "cost unknown", never a guess.59public struct PriceTable: Sendable, Hashable, Codable {60    private var entries: [String: ModelPrice]6162    public init(entries: [ProviderFamily: [String: ModelPrice]] = [:]) {63        self.entries = [:]64        for (family, models) in entries { for (model, price) in models { self.entries[Self.key(family, model)] = price } }65    }6667    private static func key(_ family: ProviderFamily, _ model: String) -> String { family.rawValue + "|" + model.lowercased() }6869    public mutating func setPrice(_ price: ModelPrice?, family: ProviderFamily, model: String) {70        entries[Self.key(family, model)] = price71    }7273    /// The price of `model`: an exact entry, or the entry of the alias a dated snapshot id belongs to74    /// (`claude-haiku-4-5-20251001` uses the `claude-haiku-4-5` entry). No other fuzzy matching is done.75    public func price(family: ProviderFamily, model: String) -> ModelPrice? {76        let lower = model.lowercased()77        if let exact = entries[Self.key(family, lower)] { return exact }78        if let range = lower.range(of: #"[-@]\d{8}$"#, options: .regularExpression) {79            return entries[Self.key(family, String(lower[..<range.lowerBound]))]80        }81        return nil82    }8384    public var count: Int { entries.count }8586    /// Merges the prices a model list published (OpenRouter).87    public mutating func merge(liveModels: [ModelInfo], family: ProviderFamily) {88        for model in liveModels { if let price = model.price { setPrice(price, family: family, model: model.id) } }89    }9091    /// Public list prices read on the dates below (standard tier, USD per million tokens). A convenience that ages:92    /// see docs/AI_PROVIDERS.md.93    public static let builtIn: PriceTable = {94        let anthropic = PriceSource.builtIn(asOf: "2026-11-03", url: "https://platform.claude.com/docs/en/about-claude/pricing")95        let openAI = PriceSource.builtIn(asOf: "2026-11-21", url: "https://developers.openai.com/api/docs/pricing")96        func a(_ input: Double, _ output: Double, read: Double, write: Double) -> ModelPrice {97            ModelPrice(inputPerMillion: input, outputPerMillion: output, cacheReadPerMillion: read, cacheWritePerMillion: write, source: anthropic)98        }99        func o(_ input: Double, _ output: Double, read: Double) -> ModelPrice {100            ModelPrice(inputPerMillion: input, outputPerMillion: output, cacheReadPerMillion: read, source: openAI)101        }102        return PriceTable(entries: [103            .anthropic: [104                "claude-fable-5-2": a(8, 40, read: 0.20, write: 10),105                "claude-opus-5-5": a(4, 20, read: 0.20, write: 5),106                "claude-opus-5": a(5, 25, read: 0.50, write: 6.25),107                "claude-opus-4-8": a(5, 25, read: 0.50, write: 6.25),108                "claude-sonnet-5-5": a(2, 10, read: 0.10, write: 2.50),109                "claude-sonnet-5": a(2, 10, read: 0.20, write: 2.50),110                "claude-sonnet-4-6": a(3, 15, read: 0.30, write: 3.75),111                // Up to 100,000 prompt tokens; longer prompts are billed at a higher rate, which this table ignores.112                "claude-haiku-5-5": a(0.10, 0.50, read: 0.01, write: 0.125),113                "claude-haiku-4-5": a(1, 5, read: 0.10, write: 1.25),114            ],115            .openAI: [116                "gpt-6.2-astra": o(8, 40, read: 0.40),117                "gpt-6.2-sol": o(2, 10, read: 0.10),118                "gpt-6.1-terra": o(1, 5, read: 0.05),119                "gpt-6-luna": o(0.10, 0.50, read: 0.01),120            ],121        ])122    }()123}124125public enum CostEstimator {126    /// The cost of one response, or `nil` when it cannot be estimated honestly: the provider reported no usage, or127    /// no price is known for the model.128    public static func estimate(usage: ProviderUsage?, price: ModelPrice?) -> CostEstimate? {129        guard let usage else { return nil }130        if let reported = usage.reportedCostUSD, reported >= 0 { return CostEstimate(usd: reported, basis: .providerReported) }131        guard usage.isReported, let price else { return nil }132        let read = max(0, usage.cacheReadTokens ?? 0), write = max(0, usage.cacheWriteTokens ?? 0)133        let fresh = max(0, (usage.inputTokens ?? 0) - read - write)134        let usd = (Double(fresh) * price.inputPerMillion135            + Double(read) * (price.cacheReadPerMillion ?? price.inputPerMillion)136            + Double(write) * (price.cacheWritePerMillion ?? price.inputPerMillion)137            + Double(max(0, usage.outputTokens ?? 0)) * price.outputPerMillion) / 1_000_000138        return CostEstimate(usd: usd, basis: .priceTable(price.source))139    }140}141
Files main
Menu

Theme