budgetbench / systems /tools.mjs
n3r's picture
BudgetBench v1.0.1
46f490b verified
Raw History Blame Contribute Delete
8.4 kB
// BudgetBench REFERENCE TOOLS: what a general model gets to read a household with (the open-model rows and the cloud
// row). They read view/view.csv: the household's own files after correct column parsing (the date, the description
// as the source writes it, the signed amount, the account, the source's own category and type, pending, currency),
// plus the account list and the app's public help. They hold no benchmark truth: no clean shop names, no
// benchmark categories, no "is this spending" flag. Deciding what counts is the model's work, as it is the app's.
// Sums are per currency; no tool ever adds two currencies.
import fs from "node:fs";
import path from "node:path";
import {fileURLToPath} from "node:url";
import {parseCsvLine} from "../households/csv.mjs";
const HELP = fs.readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), "../help/HELP.md"), "utf8");
const r2 = (v) => Math.round(v * 100) / 100;
export function loadView(hhDir, setup) {
const lines = fs.readFileSync(path.join(hhDir, "view/view.csv"), "utf8").replace(/\r/g, "").trim().split("\n");
const head = parseCsvLine(lines[0]);
const rows = lines.slice(1).map((l) => { const v = parseCsvLine(l); const o = Object.fromEntries(head.map((h, i) => [h, v[i]])); return {...o, amount: Number(o.amount), pending: o.pending === "true"}; });
// balances only where a source states one (a connected bank's page)
const balances = {};
for (const f of setup.load ?? []) if (f.kind === "plaid") {
const p = JSON.parse(fs.readFileSync(path.join(hhDir, f.file), "utf8"));
for (const a of p.accounts) if (a.balance_current != null) balances[a.name] = a.balance_current;
}
return {rows, accounts: setup.accounts.map((a) => ({name: a.name, kind: a.kind, currency: a.currency ?? setup.currency, ...(balances[a.name] != null ? {balance: balances[a.name]} : {})}))};
}
const sumsByCurrency = (rows) => {
const out = {};
for (const r of rows) {
const s = (out[r.currency] ??= {money_out: 0, money_in: 0, rows: 0});
if (r.amount < 0) s.money_out += -r.amount; else s.money_in += r.amount;
s.rows++;
}
for (const s of Object.values(out)) { s.money_out = r2(s.money_out); s.money_in = r2(s.money_in); }
return out;
};
function filterRows(view, a) {
const text = a.text ? String(a.text).toLowerCase() : null;
return view.rows.filter((r) => (!a.start || r.date >= String(a.start).slice(0, 10)) && (!a.end || r.date <= String(a.end).slice(0, 10))
&& (!text || r.description.toLowerCase().includes(text))
&& (!a.account || r.account.toLowerCase() === String(a.account).toLowerCase())
&& (!a.category || r.source_category.toLowerCase().includes(String(a.category).toLowerCase()))
&& (!a.currency || r.currency === a.currency)
&& (a.direction !== "out" || r.amount < 0) && (a.direction !== "in" || r.amount > 0));
}
const ARITH = /^[\d\s.+\-*/()%]+$/;
export function makeTools(view) {
const impl = {
list_accounts: () => view.accounts,
list_categories: () => {
const c = {};
for (const r of view.rows) { const k = r.source_category || "(none)"; c[k] = (c[k] ?? 0) + 1; }
return Object.entries(c).sort((a, b) => b[1] - a[1]).map(([category, rows]) => ({category, rows}));
},
search_transactions: (a) => {
const rows = filterRows(view, a);
const limit = Math.min(Number(a.limit) || 60, 200);
return {count: rows.length, sums_by_currency: sumsByCurrency(rows), rows: rows.slice(0, limit), ...(rows.length > limit ? {truncated: true} : {})};
},
monthly_totals: (a) => {
const rows = filterRows(view, a);
const out = {};
for (const r of rows) { const k = `${r.date.slice(0, 7)} ${r.currency}`; const s = (out[k] ??= {money_out: 0, money_in: 0, rows: 0}); if (r.amount < 0) s.money_out += -r.amount; else s.money_in += r.amount; s.rows++; }
for (const s of Object.values(out)) { s.money_out = r2(s.money_out); s.money_in = r2(s.money_in); }
return out;
},
calculate: (a) => {
const e = String(a.expression ?? "");
if (!ARITH.test(e)) return {error: "only numbers and + - * / % ( )"};
try { return {result: Math.round(Function(`"use strict"; return (${e});`)() * 10000) / 10000}; } catch (err) { return {error: String(err.message)}; }
},
search_help: (a) => {
const words = String(a.query ?? "").toLowerCase().split(/\W+/).filter((w) => w.length > 2);
const paras = HELP.split(/\n\s*\n/).map((p) => p.trim()).filter((p) => p.length > 30);
const scored = paras.map((p) => [words.filter((w) => p.toLowerCase().includes(w)).length, p]).filter(([s]) => s > 0).sort((x, y) => y[0] - x[0]);
return {passages: scored.slice(0, 4).map(([, p]) => p)};
}
};
const P = {start: {type: "string", description: "first day, YYYY-MM-DD"}, end: {type: "string", description: "last day, YYYY-MM-DD"}};
const F = {...P, text: {type: "string", description: "text contained in the description"}, account: {type: "string"}, category: {type: "string", description: "text contained in the source's own category"},
currency: {type: "string"}, direction: {type: "string", enum: ["out", "in"]}};
const schema = [
{name: "list_accounts", description: "The accounts, each with its kind and currency (and its balance today when the bank states one).", parameters: {type: "object", properties: {}}},
{name: "list_categories", description: "The categories as the person's files write them, with row counts.", parameters: {type: "object", properties: {}}},
{name: "search_transactions", description: "Transactions matching the filters, oldest first, with the count and the money out and in PER CURRENCY. Amounts: negative = money out. Rows carry the source's own category and type and whether they are pending.",
parameters: {type: "object", properties: {...F, limit: {type: "integer"}}}},
{name: "monthly_totals", description: "Money out and money in per month and currency for the rows matching the filters.", parameters: {type: "object", properties: F}},
{name: "calculate", description: "Evaluate an arithmetic expression exactly.", parameters: {type: "object", properties: {expression: {type: "string"}}, required: ["expression"]}},
{name: "search_help", description: "Search the app's help pages (how to import, budgets, privacy, how totals are counted).", parameters: {type: "object", properties: {query: {type: "string"}}, required: ["query"]}},
{name: "ask_user", description: "When the question can be read two or more ways, ask which one the person means and offer short options. The person taps one option; it is sent back as their next message.",
parameters: {type: "object", properties: {question: {type: "string"}, options: {type: "array", items: {type: "string"}}}, required: ["question", "options"]}}
];
return {impl, schema: schema.map((f) => ({type: "function", function: f}))};
}
export function systemPromptFor(setup, view) {
const accts = view.accounts.map((a) => `${a.name} (${a.kind}, ${a.currency})`).join("; ");
return `You are a personal-finance assistant inside a budgeting app. You read one household's transactions through the tools provided.
Today is ${setup.today}. The current month runs to today. Accounts: ${accts}. The ledger's home currency is ${setup.currency}.
Definitions: spending is purchases minus refunds; pending purchases count; income, card cashback, transfers between the person's own accounts and card payments are not spending. Money in is pay and card cashback.
Each account keeps its own currency. Never convert between currencies and never add amounts in two currencies; give each currency's figure apart.
Use the tools for every figure and never invent one. Answer briefly in plain English with the figure.
You describe the person's money; you never tell them what to buy, sell, cancel or do: a decision is theirs. If something is not in the ledger (market prices, the future, other people, exchange rates), say so.
For how to use the app, use search_help. If a question can be read two ways, call ask_user with the readings as options.`;
}