Branchwell

Bucksley / app · bucksley.ai / Sources / BucksleyKit / AskTools.swift

Raw 14.3 KB on 07e410940d4dd3ce1e1e51286babef75b272eb4f
1import Foundation
2#if canImport(FoundationModels)
3import FoundationModels
4#endif
5
6/// The lookups Ask Bucksley's model can run on your own numbers: find transactions, spending by
7/// category, recurring charges and accounts. Every transaction a lookup returns is remembered, so the
8/// app can show those transactions under the answer as links.
9public final class AskTools: @unchecked Sendable {
10 let ledger: Ledger
11 let today: String
12 private let lock = NSLock()
13 private var found: [String] = []
14 private var planned = false
15
16 public init(ledger: Ledger, today: String = DayKey.today) { self.ledger = ledger; self.today = today }
17
18 /// Transactions the lookups returned, in the order they were found, without repeats.
19 public var transactionIDs: [String] { lock.withLock { var seen = Set<String>(); return found.filter { seen.insert($0).inserted } } }
20
21 private func remember(_ entries: [LedgerEntry]) { lock.withLock { found += entries.map(\.id) } }
22
23 /// True once the model looked at a budget plan, so the app can offer to set it up.
24 public var madeBudgetPlan: Bool { lock.withLock { planned } }
25
26 // MARK: Lookups
27
28 public struct Search: Sendable {
29 public var query: String?, category: String?, month: String?, from: String?, to: String?
30 public var minAmount: Decimal?, direction: String?, sort: String?, limit: Int?
31 public init(query: String? = nil, category: String? = nil, month: String? = nil, from: String? = nil, to: String? = nil,
32 minAmount: Decimal? = nil, direction: String? = nil, sort: String? = nil, limit: Int? = nil) {
33 self.query = query; self.category = category; self.month = month; self.from = from; self.to = to
34 self.minAmount = minAmount; self.direction = direction; self.sort = sort; self.limit = limit
35 }
36 }
37
38 public func findTransactions(_ search: Search) -> String {
39 let ws = ledger.workspace
40 let query = search.query?.lowercased().trimmingCharacters(in: .whitespaces) ?? ""
41 let category = search.category.flatMap { name in
42 ws.categories.first { $0.name.lowercased() == name.lowercased() || $0.id == name.lowercased() }
43 ?? ws.categories.first { $0.name.lowercased().contains(name.lowercased()) }
44 }
45 if let name = search.category, !name.isEmpty, category == nil { return "There's no category called \(name). Categories: \(ws.categories.map(\.name).joined(separator: ", "))." }
46 let direction = search.direction?.lowercased() ?? "any"
47 var matches = ledger.entries.filter { e in
48 if let month = search.month, !month.isEmpty, MonthKey.of(e.day) != month { return false }
49 if let from = search.from, !from.isEmpty, e.day < from { return false }
50 if let to = search.to, !to.isEmpty, e.day > to { return false }
51 if let category, e.categoryID != category.id { return false }
52 if direction == "spending" && (e.amount >= 0 || ledger.kind(e.categoryID) == .transfer) { return false }
53 if direction == "income" && (e.amount <= 0 || ledger.kind(e.categoryID) == .transfer) { return false }
54 if let min = search.minAmount, abs(e.amount) < min { return false }
55 if !query.isEmpty {
56 let text = [e.name, e.transaction.description, e.transaction.payee ?? "", e.note ?? "", e.tags.joined(separator: " ")].joined(separator: " ").lowercased()
57 if !text.contains(query) { return false }
58 }
59 return true
60 }
61 if search.sort?.lowercased() == "largest" { matches.sort { abs($0.amount) > abs($1.amount) } }
62 guard !matches.isEmpty else { return "No transactions match." }
63 let shown = Array(matches.prefix(min(max(search.limit ?? 10, 1), 25)))
64 remember(shown)
65 let total = matches.reduce(Decimal(0)) { $0 + $1.amount }
66 return "\(matches.count) transaction\(matches.count == 1 ? "" : "s") match, adding up to \(Money.format(total, signed: true))." +
67 (shown.count < matches.count ? " The \(shown.count) shown are \(search.sort?.lowercased() == "largest" ? "the largest" : "the newest")." : "") + "\n" +
68 shown.map(line).joined(separator: "\n")
69 }
70
71 public func spendingByCategory(month: String?) -> String {
72 let month = month.flatMap { $0.isEmpty ? nil : $0 } ?? MonthKey.of(today)
73 let spend = ledger.spending(month: month)
74 let total = spend.reduce(Decimal(0)) { $0 + $1.amount }
75 let largest = ledger.entries(in: month).filter { $0.amount < 0 && ledger.kind($0.categoryID) == .expense }
76 .sorted { $0.amount < $1.amount }.prefix(5)
77 remember(Array(largest))
78 return "Spending in \(MonthKey.title(month)): \(Money.format(total)), income \(Money.format(ledger.income(month: month))). Transfers between your own accounts aren't counted.\n" +
79 spend.map { "\(name($0.categoryID)): \(Money.format($0.amount))" }.joined(separator: "\n") +
80 (largest.isEmpty ? "" : "\nLargest charges:\n" + largest.map(line).joined(separator: "\n"))
81 }
82
83 public func recurringCharges() -> String {
84 let items = ledger.recurring(today: today).filter { $0.status != .dismissed }
85 guard !items.isEmpty else { return "No recurring charges found yet. They show up after three on a steady schedule." }
86 let monthly = items.reduce(Decimal(0)) { $0 + $1.amount * 30 / Decimal($1.cadence.days) }.rounded(2)
87 return "\(items.count) recurring charges, about \(Money.format(monthly)) a month.\n" +
88 items.map { "\($0.name): \(Money.format($0.amount)) \($0.cadence.rawValue), next on \($0.nextDay)" }.joined(separator: "\n")
89 }
90
91 public func accounts() -> String {
92 "These are balances, not transactions. A negative balance is money owed.\n" +
93 ledger.visibleAccounts.map { "\($0.displayName) (\($0.institution), \($0.kind.title)): balance \(Money.format($0.balance))" }.joined(separator: "\n") +
94 "\nNet worth: \(Money.format(ledger.netWorth))"
95 }
96
97 public func smartBudgetPlan(savingsRate: Int?) -> String {
98 lock.withLock { planned = true }
99 let plan = ledger.smartBudgetPlan(savingsRate: savingsRate ?? 20, today: today)
100 guard !plan.items.isEmpty else { return plan.summary }
101 let existing = ledger.workspace.budgets.isEmpty ? "No budgets are set yet." :
102 "Budgets already set: " + ledger.workspace.budgets.map { "\(name($0.categoryID)) \(Money.format($0.amount, cents: false))" }.joined(separator: ", ") + "."
103 let fixed = plan.fixedItems.reduce(Decimal(0)) { $0 + $1.recommended }, flexible = plan.flexible.reduce(Decimal(0)) { $0 + $1.recommended }
104 let totals = "Totals to quote exactly: fixed bills \(Money.format(fixed, cents: false)) a month, flexible \(Money.format(flexible, cents: false)) a month, whole plan \(Money.format(plan.total, cents: false)), left over \(Money.format(plan.leftOver, cents: false)), savings goal \(Money.format(plan.savingsGoal, cents: false))."
105 return plan.summary + " " + existing + "\n" + totals + "\nRecommended monthly budgets (from the last \(plan.months) months):\n" +
106 plan.items.map { "\($0.name) (\($0.fixed ? "fixed, budgeted at what is spent" : "flexible")): \(Money.format($0.recommended, cents: false)), recent average \(Money.format($0.typical, cents: false))" }.joined(separator: "\n") +
107 "\nThe app shows a button under your answer that walks the user through creating these budgets."
108 }
109
110 private func name(_ categoryID: String) -> String { ledger.workspace.category(categoryID)?.name ?? categoryID }
111
112 private func line(_ e: LedgerEntry) -> String {
113 let account = ledger.workspace.accounts.first { $0.id == e.accountID }?.displayName ?? ""
114 return "\(e.day) · \(e.name) · \(Money.format(e.amount, signed: true)) · \(name(e.categoryID))" + (account.isEmpty ? "" : " · \(account)") + (e.transaction.pending ? " · pending" : "")
115 }
116
117 // MARK: Tool definitions for Claude and OpenAI
118
119 struct Definition { let name: String; let description: String; let properties: [String: Any] }
120
121 static var definitions: [Definition] { [
122 .init(name: "find_transactions",
123 description: "Find the user's transactions. All filters are optional. Use it for any question about specific charges, merchants, the largest purchases or what made up a total.",
124 properties: ["query": ["type": "string", "description": "Text in the merchant name, description, note or tags"],
125 "category": ["type": "string", "description": "Category name, such as Dining"],
126 "month": ["type": "string", "description": "yyyy-MM"],
127 "from": ["type": "string", "description": "yyyy-MM-dd"], "to": ["type": "string", "description": "yyyy-MM-dd"],
128 "min_amount": ["type": "number", "description": "Smallest absolute amount"],
129 "direction": ["type": "string", "enum": ["spending", "income", "any"]],
130 "sort": ["type": "string", "enum": ["newest", "largest"]],
131 "limit": ["type": "integer", "minimum": 1, "maximum": 25]]),
132 .init(name: "spending_by_category", description: "Spending by category, income and the largest charges for a month (default this month).",
133 properties: ["month": ["type": "string", "description": "yyyy-MM"]]),
134 .init(name: "recurring_charges", description: "Recurring charges and subscriptions with amounts and next dates.", properties: [:]),
135 .init(name: "accounts", description: "Account balances and net worth. Balances are not transactions.", properties: [:]),
136 .init(name: "smart_budget_plan", description: "A recommended monthly budget for every category the user spends in, sized from their income and typical spending so it leaves room for a savings goal. Use it for any question about budgets, saving more or cutting back.",
137 properties: ["savings_rate": ["type": "integer", "minimum": 0, "maximum": 60, "description": "Percent of income to keep free for savings, default 20"]])
138 ] }
139
140 func run(_ name: String, _ input: [String: Any]) -> String {
141 func text(_ key: String) -> String? { (input[key] as? String).flatMap { $0.isEmpty ? nil : $0 } }
142 switch name {
143 case "find_transactions":
144 let min = (input["min_amount"] as? NSNumber).map { Decimal($0.doubleValue) }
145 return findTransactions(.init(query: text("query"), category: text("category"), month: text("month"), from: text("from"), to: text("to"),
146 minAmount: min, direction: text("direction"), sort: text("sort"), limit: (input["limit"] as? NSNumber)?.intValue))
147 case "spending_by_category": return spendingByCategory(month: text("month"))
148 case "recurring_charges": return recurringCharges()
149 case "accounts": return accounts()
150 case "smart_budget_plan": return smartBudgetPlan(savingsRate: (input["savings_rate"] as? NSNumber)?.intValue)
151 default: return "Unknown tool \(name)."
152 }
153 }
154
155 // MARK: Apple Intelligence tools
156
157 #if canImport(FoundationModels)
158 @available(macOS 26, iOS 26, *)
159 var appleTools: [any Tool] { [FindTransactions(tools: self), SpendingByCategory(tools: self), RecurringCharges(tools: self), Accounts(tools: self), SmartBudgetPlanTool(tools: self)] }
160 #endif
161}
162
163#if canImport(FoundationModels)
164@available(macOS 26, iOS 26, *)
165struct FindTransactions: Tool {
166 let tools: AskTools
167 let name = "findTransactions"
168 let description = "Find the user's transactions. Use it for any question about specific charges, merchants, the largest purchases or what made up a total."
169
170 @Generable struct Arguments {
171 @Guide(description: "Text in the merchant name, description, note or tags, or empty") var query: String?
172 @Guide(description: "Category name, such as Dining, or empty") var category: String?
173 @Guide(description: "Month as yyyy-MM, or empty") var month: String?
174 @Guide(description: "Smallest absolute amount in dollars, or 0") var minAmount: Double?
175 @Guide(description: "spending, income or any") var direction: String?
176 @Guide(description: "newest or largest") var sort: String?
177 @Guide(description: "How many to show, 1 to 25") var limit: Int?
178 }
179
180 func call(arguments: Arguments) async throws -> String {
181 tools.findTransactions(.init(query: arguments.query, category: arguments.category, month: arguments.month,
182 minAmount: arguments.minAmount.flatMap { $0 > 0 ? Decimal($0) : nil },
183 direction: arguments.direction, sort: arguments.sort, limit: arguments.limit))
184 }
185}
186
187@available(macOS 26, iOS 26, *)
188struct SpendingByCategory: Tool {
189 let tools: AskTools
190 let name = "spendingByCategory"
191 let description = "Spending by category, income and the largest charges for a month."
192 @Generable struct Arguments { @Guide(description: "Month as yyyy-MM, or empty for this month") var month: String? }
193 func call(arguments: Arguments) async throws -> String { tools.spendingByCategory(month: arguments.month) }
194}
195
196@available(macOS 26, iOS 26, *)
197struct RecurringCharges: Tool {
198 let tools: AskTools
199 let name = "recurringCharges"
200 let description = "Recurring charges and subscriptions with amounts and next dates."
201 @Generable struct Arguments {}
202 func call(arguments: Arguments) async throws -> String { tools.recurringCharges() }
203}
204
205@available(macOS 26, iOS 26, *)
206struct SmartBudgetPlanTool: Tool {
207 let tools: AskTools
208 let name = "smartBudgetPlan"
209 let description = "Recommended monthly budgets for every category, from income and typical spending, leaving room for a savings goal. Use it for questions about budgets, saving or cutting back."
210 @Generable struct Arguments { @Guide(description: "Percent of income to save, 0 to 60, usually 20") var savingsRate: Int? }
211 func call(arguments: Arguments) async throws -> String { tools.smartBudgetPlan(savingsRate: arguments.savingsRate) }
212}
213
214@available(macOS 26, iOS 26, *)
215struct Accounts: Tool {
216 let tools: AskTools
217 let name = "accounts"
218 let description = "Account balances and net worth. Balances are not transactions."
219 @Generable struct Arguments {}
220 func call(arguments: Arguments) async throws -> String { tools.accounts() }
221}
222#endif