Bucksley / app / Sources / BucksleyKit / SmartModel.swift
| 1 | import Foundation |
| 2 | #if canImport(FoundationModels) |
| 3 | import FoundationModels |
| 4 | #endif |
| 5 | |
| 6 | /// The two places Bucksley lets Apple's on-device model help beyond Ask: wording the monthly recap |
| 7 | /// and suggesting categories. Both stay on the device, and both fall back to plain numbers. |
| 8 | extension AskBucksley { |
| 9 | |
| 10 | /// The recap in friendlier words. Any dollar figure the model writes that isn't in the recap's |
| 11 | /// own numbers throws the wording away, so it can't invent or miscount money. |
| 12 | public static func wordRecap(_ recap: Ledger.Recap) async -> (text: String, reworded: Bool) { |
| 13 | #if canImport(FoundationModels) |
| 14 | if #available(macOS 26, iOS 26, *), appleModelAvailable { |
| 15 | let session = LanguageModelSession(instructions: """ |
| 16 | Rewrite these facts about the user's month as a warm, plain three or four sentence recap. \ |
| 17 | Keep every dollar amount exactly as written, add no new numbers, give no advice, no headings. |
| 18 | """) |
| 19 | if let text = try? await session.respond(to: recap.facts).content.trimmingCharacters(in: .whitespacesAndNewlines), |
| 20 | !text.isEmpty, recapFiguresAreValid(text, recap: recap) { |
| 21 | return (text, true) |
| 22 | } |
| 23 | } |
| 24 | #endif |
| 25 | return (recap.facts, false) |
| 26 | } |
| 27 | |
| 28 | /// True when every "$…" figure in the text is one of the recap's own. |
| 29 | public static func recapFiguresAreValid(_ text: String, recap: Ledger.Recap) -> Bool { |
| 30 | let allowed = recap.allowedFigures.map { $0.replacingOccurrences(of: "−", with: "") } |
| 31 | let pattern = try! NSRegularExpression(pattern: #"\$[0-9][0-9,]*(\.[0-9]{2})?"#) |
| 32 | let found = pattern.matches(in: text, range: NSRange(text.startIndex..., in: text)).compactMap { Range($0.range, in: text).map { String(text[$0]) } } |
| 33 | return found.allSatisfy { allowed.contains($0) } |
| 34 | } |
| 35 | |
| 36 | /// Categories for transactions Bucksley left in "Other", from the on-device model. Answers that |
| 37 | /// name a category the user doesn't have are dropped. Empty without Apple Intelligence. |
| 38 | public static func suggestCategories(for entries: [LedgerEntry], categories: [Category]) async -> [Ledger.CategorySuggestion] { |
| 39 | #if canImport(FoundationModels) |
| 40 | guard #available(macOS 26, iOS 26, *), appleModelAvailable, !entries.isEmpty else { return [] } |
| 41 | let choices = categories.filter { $0.kind == .expense && $0.id != "other" } |
| 42 | let ids = Set(choices.map(\.id)) |
| 43 | let session = LanguageModelSession(instructions: """ |
| 44 | You sort bank transactions into budget categories. The categories are: \ |
| 45 | \(choices.map { "\($0.id) (\($0.name))" }.joined(separator: ", ")). \ |
| 46 | For each line, answer one line "number: category_id", or "number: none" when unsure. Nothing else. |
| 47 | """) |
| 48 | let batch = Array(entries.prefix(25)) |
| 49 | let prompt = batch.enumerated().map { "\($0.offset + 1). \($0.element.name) | \($0.element.transaction.description) | \(Money.format(abs($0.element.amount)))" }.joined(separator: "\n") |
| 50 | guard let reply = try? await session.respond(to: prompt).content else { return [] } |
| 51 | return reply.split(separator: "\n").compactMap { line -> Ledger.CategorySuggestion? in |
| 52 | let parts = line.split(separator: ":", maxSplits: 1).map { $0.trimmingCharacters(in: .whitespaces.union(.punctuationCharacters)) } |
| 53 | guard parts.count == 2, let n = Int(parts[0]), (1...batch.count).contains(n), ids.contains(parts[1].lowercased()) else { return nil } |
| 54 | let id = parts[1].lowercased() |
| 55 | return Ledger.CategorySuggestion(entryID: batch[n - 1].id, categoryID: id, |
| 56 | reason: "Apple Intelligence thinks \(batch[n - 1].name) is \(categories.first { $0.id == id }?.name ?? id).") |
| 57 | } |
| 58 | #else |
| 59 | return [] |
| 60 | #endif |
| 61 | } |
| 62 | } |