import Foundation #if canImport(FoundationModels) import FoundationModels #endif /// The lookups Ask Bucksley's model can run on your own numbers: find transactions, spending by /// category, recurring charges and accounts. Every transaction a lookup returns is remembered, so the /// app can show those transactions under the answer as links. public final class AskTools: @unchecked Sendable { let ledger: Ledger let today: String private let lock = NSLock() private var found: [String] = [] private var planned = false public init(ledger: Ledger, today: String = DayKey.today) { self.ledger = ledger; self.today = today } /// Transactions the lookups returned, in the order they were found, without repeats. public var transactionIDs: [String] { lock.withLock { var seen = Set(); return found.filter { seen.insert($0).inserted } } } private func remember(_ entries: [LedgerEntry]) { lock.withLock { found += entries.map(\.id) } } /// True once the model looked at a budget plan, so the app can offer to set it up. public var madeBudgetPlan: Bool { lock.withLock { planned } } // MARK: Lookups public struct Search: Sendable { public var query: String?, category: String?, month: String?, from: String?, to: String? public var minAmount: Decimal?, direction: String?, sort: String?, limit: Int? public init(query: String? = nil, category: String? = nil, month: String? = nil, from: String? = nil, to: String? = nil, minAmount: Decimal? = nil, direction: String? = nil, sort: String? = nil, limit: Int? = nil) { self.query = query; self.category = category; self.month = month; self.from = from; self.to = to self.minAmount = minAmount; self.direction = direction; self.sort = sort; self.limit = limit } } public func findTransactions(_ search: Search) -> String { let ws = ledger.workspace let query = search.query?.lowercased().trimmingCharacters(in: .whitespaces) ?? "" let category = search.category.flatMap { name in ws.categories.first { $0.name.lowercased() == name.lowercased() || $0.id == name.lowercased() } ?? ws.categories.first { $0.name.lowercased().contains(name.lowercased()) } } if let name = search.category, !name.isEmpty, category == nil { return "There's no category called \(name). Categories: \(ws.categories.map(\.name).joined(separator: ", "))." } let direction = search.direction?.lowercased() ?? "any" var matches = ledger.entries.filter { e in if let month = search.month, !month.isEmpty, MonthKey.of(e.day) != month { return false } if let from = search.from, !from.isEmpty, e.day < from { return false } if let to = search.to, !to.isEmpty, e.day > to { return false } if let category, e.categoryID != category.id { return false } if direction == "spending" && (e.amount >= 0 || ledger.kind(e.categoryID) == .transfer) { return false } if direction == "income" && (e.amount <= 0 || ledger.kind(e.categoryID) == .transfer) { return false } if let min = search.minAmount, abs(e.amount) < min { return false } if !query.isEmpty { let text = [e.name, e.transaction.description, e.transaction.payee ?? "", e.note ?? "", e.tags.joined(separator: " ")].joined(separator: " ").lowercased() if !text.contains(query) { return false } } return true } if search.sort?.lowercased() == "largest" { matches.sort { abs($0.amount) > abs($1.amount) } } guard !matches.isEmpty else { return "No transactions match." } let shown = Array(matches.prefix(min(max(search.limit ?? 10, 1), 25))) remember(shown) let total = matches.reduce(Decimal(0)) { $0 + $1.amount } return "\(matches.count) transaction\(matches.count == 1 ? "" : "s") match, adding up to \(Money.format(total, signed: true))." + (shown.count < matches.count ? " The \(shown.count) shown are \(search.sort?.lowercased() == "largest" ? "the largest" : "the newest")." : "") + "\n" + shown.map(line).joined(separator: "\n") } public func spendingByCategory(month: String?) -> String { let month = month.flatMap { $0.isEmpty ? nil : $0 } ?? MonthKey.of(today) let spend = ledger.spending(month: month) let total = spend.reduce(Decimal(0)) { $0 + $1.amount } let largest = ledger.entries(in: month).filter { $0.amount < 0 && ledger.kind($0.categoryID) == .expense } .sorted { $0.amount < $1.amount }.prefix(5) remember(Array(largest)) 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" + spend.map { "\(name($0.categoryID)): \(Money.format($0.amount))" }.joined(separator: "\n") + (largest.isEmpty ? "" : "\nLargest charges:\n" + largest.map(line).joined(separator: "\n")) } public func recurringCharges() -> String { let items = ledger.recurring(today: today).filter { $0.status != .dismissed } guard !items.isEmpty else { return "No recurring charges found yet. They show up after three on a steady schedule." } let monthly = items.reduce(Decimal(0)) { $0 + $1.amount * 30 / Decimal($1.cadence.days) }.rounded(2) return "\(items.count) recurring charges, about \(Money.format(monthly)) a month.\n" + items.map { "\($0.name): \(Money.format($0.amount)) \($0.cadence.rawValue), next on \($0.nextDay)" }.joined(separator: "\n") } public func accounts() -> String { "These are balances, not transactions. A negative balance is money owed.\n" + ledger.visibleAccounts.map { "\($0.displayName) (\($0.institution), \($0.kind.title)): balance \(Money.format($0.balance))" }.joined(separator: "\n") + "\nNet worth: \(Money.format(ledger.netWorth))" } public func smartBudgetPlan(savingsRate: Int?) -> String { lock.withLock { planned = true } let plan = ledger.smartBudgetPlan(savingsRate: savingsRate ?? 20, today: today) guard !plan.items.isEmpty else { return plan.summary } let existing = ledger.workspace.budgets.isEmpty ? "No budgets are set yet." : "Budgets already set: " + ledger.workspace.budgets.map { "\(name($0.categoryID)) \(Money.format($0.amount, cents: false))" }.joined(separator: ", ") + "." let fixed = plan.fixedItems.reduce(Decimal(0)) { $0 + $1.recommended }, flexible = plan.flexible.reduce(Decimal(0)) { $0 + $1.recommended } 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))." return plan.summary + " " + existing + "\n" + totals + "\nRecommended monthly budgets (from the last \(plan.months) months):\n" + 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") + "\nThe app shows a button under your answer that walks the user through creating these budgets." } private func name(_ categoryID: String) -> String { ledger.workspace.category(categoryID)?.name ?? categoryID } private func line(_ e: LedgerEntry) -> String { let account = ledger.workspace.accounts.first { $0.id == e.accountID }?.displayName ?? "" return "\(e.day) · \(e.name) · \(Money.format(e.amount, signed: true)) · \(name(e.categoryID))" + (account.isEmpty ? "" : " · \(account)") + (e.transaction.pending ? " · pending" : "") } // MARK: Tool definitions for Claude and OpenAI struct Definition { let name: String; let description: String; let properties: [String: Any] } static var definitions: [Definition] { [ .init(name: "find_transactions", 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.", properties: ["query": ["type": "string", "description": "Text in the merchant name, description, note or tags"], "category": ["type": "string", "description": "Category name, such as Dining"], "month": ["type": "string", "description": "yyyy-MM"], "from": ["type": "string", "description": "yyyy-MM-dd"], "to": ["type": "string", "description": "yyyy-MM-dd"], "min_amount": ["type": "number", "description": "Smallest absolute amount"], "direction": ["type": "string", "enum": ["spending", "income", "any"]], "sort": ["type": "string", "enum": ["newest", "largest"]], "limit": ["type": "integer", "minimum": 1, "maximum": 25]]), .init(name: "spending_by_category", description: "Spending by category, income and the largest charges for a month (default this month).", properties: ["month": ["type": "string", "description": "yyyy-MM"]]), .init(name: "recurring_charges", description: "Recurring charges and subscriptions with amounts and next dates.", properties: [:]), .init(name: "accounts", description: "Account balances and net worth. Balances are not transactions.", properties: [:]), .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.", properties: ["savings_rate": ["type": "integer", "minimum": 0, "maximum": 60, "description": "Percent of income to keep free for savings, default 20"]]) ] } func run(_ name: String, _ input: [String: Any]) -> String { func text(_ key: String) -> String? { (input[key] as? String).flatMap { $0.isEmpty ? nil : $0 } } switch name { case "find_transactions": let min = (input["min_amount"] as? NSNumber).map { Decimal($0.doubleValue) } return findTransactions(.init(query: text("query"), category: text("category"), month: text("month"), from: text("from"), to: text("to"), minAmount: min, direction: text("direction"), sort: text("sort"), limit: (input["limit"] as? NSNumber)?.intValue)) case "spending_by_category": return spendingByCategory(month: text("month")) case "recurring_charges": return recurringCharges() case "accounts": return accounts() case "smart_budget_plan": return smartBudgetPlan(savingsRate: (input["savings_rate"] as? NSNumber)?.intValue) default: return "Unknown tool \(name)." } } // MARK: Apple Intelligence tools #if canImport(FoundationModels) @available(macOS 26, iOS 26, *) var appleTools: [any Tool] { [FindTransactions(tools: self), SpendingByCategory(tools: self), RecurringCharges(tools: self), Accounts(tools: self), SmartBudgetPlanTool(tools: self)] } #endif } #if canImport(FoundationModels) @available(macOS 26, iOS 26, *) struct FindTransactions: Tool { let tools: AskTools let name = "findTransactions" 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." @Generable struct Arguments { @Guide(description: "Text in the merchant name, description, note or tags, or empty") var query: String? @Guide(description: "Category name, such as Dining, or empty") var category: String? @Guide(description: "Month as yyyy-MM, or empty") var month: String? @Guide(description: "Smallest absolute amount in dollars, or 0") var minAmount: Double? @Guide(description: "spending, income or any") var direction: String? @Guide(description: "newest or largest") var sort: String? @Guide(description: "How many to show, 1 to 25") var limit: Int? } func call(arguments: Arguments) async throws -> String { tools.findTransactions(.init(query: arguments.query, category: arguments.category, month: arguments.month, minAmount: arguments.minAmount.flatMap { $0 > 0 ? Decimal($0) : nil }, direction: arguments.direction, sort: arguments.sort, limit: arguments.limit)) } } @available(macOS 26, iOS 26, *) struct SpendingByCategory: Tool { let tools: AskTools let name = "spendingByCategory" let description = "Spending by category, income and the largest charges for a month." @Generable struct Arguments { @Guide(description: "Month as yyyy-MM, or empty for this month") var month: String? } func call(arguments: Arguments) async throws -> String { tools.spendingByCategory(month: arguments.month) } } @available(macOS 26, iOS 26, *) struct RecurringCharges: Tool { let tools: AskTools let name = "recurringCharges" let description = "Recurring charges and subscriptions with amounts and next dates." @Generable struct Arguments {} func call(arguments: Arguments) async throws -> String { tools.recurringCharges() } } @available(macOS 26, iOS 26, *) struct SmartBudgetPlanTool: Tool { let tools: AskTools let name = "smartBudgetPlan" 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." @Generable struct Arguments { @Guide(description: "Percent of income to save, 0 to 60, usually 20") var savingsRate: Int? } func call(arguments: Arguments) async throws -> String { tools.smartBudgetPlan(savingsRate: arguments.savingsRate) } } @available(macOS 26, iOS 26, *) struct Accounts: Tool { let tools: AskTools let name = "accounts" let description = "Account balances and net worth. Balances are not transactions." @Generable struct Arguments {} func call(arguments: Arguments) async throws -> String { tools.accounts() } } #endif