import Foundation #if canImport(FoundationModels) import FoundationModels #endif /// The two places Bucksley lets Apple's on-device model help beyond Ask: wording the monthly recap /// and suggesting categories. Both stay on the device, and both fall back to plain numbers. extension AskBucksley { /// The recap in friendlier words. Any dollar figure the model writes that isn't in the recap's /// own numbers throws the wording away, so it can't invent or miscount money. public static func wordRecap(_ recap: Ledger.Recap) async -> (text: String, reworded: Bool) { #if canImport(FoundationModels) if #available(macOS 26, iOS 26, *), appleModelAvailable { let session = LanguageModelSession(instructions: """ Rewrite these facts about the user's month as a warm, plain three or four sentence recap. \ Keep every dollar amount exactly as written, add no new numbers, give no advice, no headings. """) if let text = try? await session.respond(to: recap.facts).content.trimmingCharacters(in: .whitespacesAndNewlines), !text.isEmpty, recapFiguresAreValid(text, recap: recap) { return (text, true) } } #endif return (recap.facts, false) } /// True when every "$…" figure in the text is one of the recap's own. public static func recapFiguresAreValid(_ text: String, recap: Ledger.Recap) -> Bool { let allowed = recap.allowedFigures.map { $0.replacingOccurrences(of: "−", with: "") } let pattern = try! NSRegularExpression(pattern: #"\$[0-9][0-9,]*(\.[0-9]{2})?"#) let found = pattern.matches(in: text, range: NSRange(text.startIndex..., in: text)).compactMap { Range($0.range, in: text).map { String(text[$0]) } } return found.allSatisfy { allowed.contains($0) } } /// Categories for transactions Bucksley left in "Other", from the on-device model. Answers that /// name a category the user doesn't have are dropped. Empty without Apple Intelligence. public static func suggestCategories(for entries: [LedgerEntry], categories: [Category]) async -> [Ledger.CategorySuggestion] { #if canImport(FoundationModels) guard #available(macOS 26, iOS 26, *), appleModelAvailable, !entries.isEmpty else { return [] } let choices = categories.filter { $0.kind == .expense && $0.id != "other" } let ids = Set(choices.map(\.id)) let session = LanguageModelSession(instructions: """ You sort bank transactions into budget categories. The categories are: \ \(choices.map { "\($0.id) (\($0.name))" }.joined(separator: ", ")). \ For each line, answer one line "number: category_id", or "number: none" when unsure. Nothing else. """) let batch = Array(entries.prefix(25)) let prompt = batch.enumerated().map { "\($0.offset + 1). \($0.element.name) | \($0.element.transaction.description) | \(Money.format(abs($0.element.amount)))" }.joined(separator: "\n") guard let reply = try? await session.respond(to: prompt).content else { return [] } return reply.split(separator: "\n").compactMap { line -> Ledger.CategorySuggestion? in let parts = line.split(separator: ":", maxSplits: 1).map { $0.trimmingCharacters(in: .whitespaces.union(.punctuationCharacters)) } guard parts.count == 2, let n = Int(parts[0]), (1...batch.count).contains(n), ids.contains(parts[1].lowercased()) else { return nil } let id = parts[1].lowercased() return Ledger.CategorySuggestion(entryID: batch[n - 1].id, categoryID: id, reason: "Apple Intelligence thinks \(batch[n - 1].name) is \(categories.first { $0.id == id }?.name ?? id).") } #else return [] #endif } }