Deploy BudgetBuddy update
Browse filesFiles changed (5)
- README.md+85-38
- app.py+6-3
- core/agent.py+278-40
- frontend/assets/app.js+22-3
- frontend/index.html+4-1
6 unmodified lines78910111213141516171819202122232425262728293031324 unmodified lines373839404142434445464748495051525354551 unmodified line5758596061626364656667686970717273747576777879802 unmodified lines838485868788896 unmodified linessdk_version: 6.18.0app_file: app.pypinned: falseshort_description: Snap a bill, ask where your money went — on-device AI---# 🧾 BudgetBuddy**A spend tracker for real people — built entirely on tiny, on-device models.**Snap a messy receipt or a UPI/card screenshot (or just type it), and BudgetBuddyreads it, fixes the totals, categorises it, saves it privately, and lets you**chat with an AI agent** about where your money went — with a custom dashboardUI. No cloud AI. Two MiniCPM models, ~2.4B parameters total.> Build Small hackathon · **Backyard AI** track. Built for the people around me> (homemakers, parents, small-shop owners) who want to understand their spending> without a spreadsheet — and without sending their receipts to a cloud API.## Why it fits "Build Small"- **Runs on tiny models, on-device.** [MiniCPM-V-4.6](https://huggingface.co/openbmb/MiniCPM-V-4.6)(vision/OCR, **1.3B**) + [MiniCPM5-1B](https://huggingface.co/openbmb/MiniCPM5-1B)(text/agent, **1.1B**). **~2.4B total — both under 4B.** Everything runs on theSpace's ZeroGPU via `transformers`; **no hosted inference API** is called.- **Real problem, honest fit.** Real bills are messy: missing totals, taxes,service charges, round-offs, mixed items, weird date formats. BudgetBuddyreasons about them and reconciles the math, so editing is the exception.4 unmodified lines2. **Read & reconcile** — the vision model extracts vendor, date (normalised to`YYYY-MM-DD`), line items, taxes/service/tip/discount/round-off, and total;computes a missing total; flags anything that doesn't add up.3. **Reason & categorise** — the text model reviews the extraction, fixes obviouserrors, and assigns an overall + per-item category (fixed list).4. **Dashboard** — monthly spend, vs-last-month, top category, spend-by-categorydonut, spend-over-time line, filterable transactions.5. **Agent chat** — ask *"how much did I spend on Groceries this month?"* and a**tool-using agent** plans, calls analytics tools across multiple steps, andanswers with your real numbers (it shows which tools it used).## Custom UI (not stock Gradio)The frontend is a hand-built dark single-page app ([frontend/](frontend/)) servedby **`gradio.Server`** (Gradio 6) — Python API endpoints with the Gradio backend(queue + ZeroGPU), our own HTML/CSS/JS + Chart.js on top. The default Gradioshell is gone.## PrivacySign in with a **username + PIN** (PIN stored salted+hashed, never in plaintext).1 unmodified linefrontend holds a signed session token, so no one can read another user's data.## Badges / prizes targeted- **Best MiniCPM Build** — the whole app is two MiniCPM models.- **Off-Brand** — custom `gradio.Server` frontend.- **Tiny Titan** — both models ≤ 4B.- **Best Agent** — multi-step tool use + planning in the chat.- On-device / no cloud AI APIs throughout.## Structure```core/extract.py # MiniCPM-V-4.6: receipt + payment extraction, reconcile, date-normalisecore/categorize.py # MiniCPM5-1B: refine/repair + categorisecore/agent.py # tool-using spending agent (plan → call tools → answer)core/chat.py # grounded one-shot answer (agent fallback) + text-model generationcore/analytics.py # pure-Python aggregations (summary, by-category, over-time)core/storage.py # per-user transactions in a HF Datasetcore/auth.py # username + PIN accounts, signed session tokenscore/hubio.py # low-level dataset JSONL IOapp.py # gradio.Server: API endpoints + serves the custom frontendfrontend/ # custom dark SPA (index.html + assets/app.js, Chart.js)```## Run locally2 unmodified linespip install -r requirements.txtpython app.py # open http://127.0.0.1:7860```A GPU isn't required to try the UI (CPU is slow; first run downloads the modelweights). On the Space, set an `HF_TOKEN` secret so it can persist to thedataset. **Tip:** log in to Hugging Face in your browser to use your own ZeroGPUquota for the AI features.6 unmodified lines789101112131415161718192021222324252627282930313233343536373839404142434445464748495051524 unmodified lines5758596061626364656667686970717273747576777879808182838485868788899091929394959697981 unmodified line1001011021031041051061071081091101111121131141151161171181191201211221231241251261272 unmodified lines1301311321331341351366 unmodified linessdk_version: 6.18.0app_file: app.pypinned: falseshort_description: Snap a bill, ask where your money went — small-model AItags:- build-small-hackathon- backyard-ai- best-agent- best-minicpm-build- best-use-of-modal- off-brand- best-demo- minicpm- modal- gradio- agent---# 🧾 BudgetBuddy**A spend tracker for real people — built entirely on small, open models.**Snap a messy receipt or a UPI/card screenshot (or just type it), and BudgetBuddyreads it, fixes the totals, categorises it, saves it privately, and lets you**chat with a tool-using agent** about where your money went — all in a customdashboard UI. No third-party AI APIs. Two MiniCPM models do everything.> Build Small hackathon · **Backyard AI** track. Built for the people around me> (homemakers, parents, small-shop owners) who want to understand their spending> without a spreadsheet — and without handing their receipts to a cloud AI API.## ▶️ Demo & links- **Live app:** https://huggingface.co/spaces/build-small-hackathon/BudgetBuddy- **Demo video:** _TODO — add link before submission_- **Social post:** _TODO — add link before submission_## Why it fits "Build Small"- **Small, open models — no third-party AI API.** Vision/OCR is[MiniCPM-V-4.6](https://huggingface.co/openbmb/MiniCPM-V-4.6) (**1.3B**), runningon the Space's **ZeroGPU**. The reasoning + agent brain is[MiniCPM4.1-8B](https://huggingface.co/openbmb/MiniCPM4.1-8B) (**8B**), running onour own **[Modal](https://modal.com)** GPU. **~9.3B total — well under the 32Bcap.** We never call a hosted AI inference API (no OpenAI/Anthropic/Gemini) — onlyopen weights we run ourselves.- **Real problem, honest fit.** Real bills are messy: missing totals, taxes,service charges, round-offs, mixed items, weird date formats. BudgetBuddyreasons about them and reconciles the math, so editing is the exception.4 unmodified lines2. **Read & reconcile** — the vision model extracts vendor, date (normalised to`YYYY-MM-DD`), line items, taxes/service/tip/discount/round-off, and total;computes a missing total; flags anything that doesn't add up.3. **Reason & categorise** — the 8B reviews the extraction, fixes obvious errors,and assigns an overall + per-item category (fixed 23-category list).4. **Dashboard** — monthly spend, vs-last-month, top category, spend-by-categorydonut, spend-over-time chart, a budget ring, a calendar heatmap, and afilterable transaction list that shows every line item **and** every tax/charge.5. **Agent chat** — ask *"how much did I spend on Groceries last month?"* or*"what's my biggest expense?"* and the agent answers with your real numbers,showing which **tools** it used.## 🤖 The agent (Best Agent)The assistant is a real tool-using agent over `core/analytics`, not a chatbot thatguesses. It exposes **11 tools** — `total_spend`, `category_spend`, `item_spend`,`vendor_spend`, `top_categories`, `biggest_expense`, `average_spend`,`count_transactions`, `budget_status`, `monthly_trend`, `recent` — each scoped by aflexible **period** (`this_month`, `last_month`, `this_year`, a specific month like`2026-07`, a year, or `all`).Two layers keep it **fast and reliable**: a deterministic router resolves clearquestions to the exact tool instantly (no hallucinated numbers), while open-ended /multi-part questions drive a **ReAct loop** on the 8B that plans, calls a tool,reads the result, and either calls another or answers. Every reply shows the**trace of tools used**, so the reasoning is auditable.## Custom UI (Off-Brand)The frontend is a hand-built dark single-page app ([frontend/](frontend/)) servedby **`gradio.Server`** (Gradio 6): Python API endpoints on the Gradio backend(queue + ZeroGPU), our own HTML/CSS/JS + Chart.js on top. The default Gradio shellis gone entirely.## ⚡ Modal (Best Use of Modal)MiniCPM4.1-8B's `trust_remote_code` targets transformers ~4.56 and breaks on the5.7 that MiniCPM-V-4.6 needs. Modal resolves the conflict cleanly: the 8B runs inits own container/env on an A10G, loaded once into a **memory snapshot** for fastcold starts and kept warm (`scaledown_window`), and the Space calls it through theModal SDK ([core/modal_backend.py](core/modal_backend.py),[modal_app.py](modal_app.py)). That's what makes the agent quick.## PrivacySign in with a **username + PIN** (PIN stored salted+hashed, never in plaintext).1 unmodified linefrontend holds a signed session token, so no one can read another user's data.## Badges / prizes targeted- **Backyard AI** track — a practical, everyday-life spending app.- **Best MiniCPM Build** — the whole app is two MiniCPM models (vision + 8B).- **Best Use of Modal** — the 8B reasoning/agent model runs on Modal.- **Off-Brand** — a fully custom `gradio.Server` frontend.- **Best Agent** — multi-step tool use + planning, with a visible trace.- **Best Demo** — great app + demo video + social post.## Structure```core/extract.py # MiniCPM-V-4.6: receipt + payment extraction, reconcile, date-normalisecore/categorize.py # 8B: refine/repair + categorise (overall + per-item)core/agent.py # tool-using spending agent (router + ReAct loop, 11 tools)core/chat.py # grounded one-shot answer (agent fallback)core/analytics.py # pure-Python aggregations (summary, by-category, over-time, calendar)core/inference.py # one place that owns the models / routes vision + text generationcore/modal_backend.py # client for the Modal 8B servicecore/storage.py # per-user transactions + budget in a HF Datasetcore/auth.py # username + PIN accounts, signed session tokenscore/hubio.py # low-level dataset JSONL IOapp.py # gradio.Server: API endpoints + serves the custom frontendmodal_app.py # Modal service hosting MiniCPM4.1-8B (deploy: modal deploy modal_app.py)frontend/ # custom dark SPA (index.html + assets/app.js, Chart.js)```## Run locally2 unmodified linespip install -r requirements.txtpython app.py # open http://127.0.0.1:7860```A GPU isn't required to try the UI (first run downloads the vision weights). On theSpace, set an `HF_TOKEN` secret (dataset persistence) and `MODAL_TOKEN_ID` /`MODAL_TOKEN_SECRET` (the 8B backend), and `BB_INFERENCE=modal`. **Tip:** log in toHugging Face in your browser to use your own ZeroGPU quota for the vision model.
12 unmodified lines13141516171819202122232425171 unmodified lines19719819920020120220312 unmodified linesimport jsonfrom datetime import datefrom pathlib import Pathfrom typing import Anyimport gradio as grfrom fastapi.responses import HTMLResponsefrom fastapi.staticfiles import StaticFilesfrom core.extract import extract_receipt, extract_payment, reconcile, EMPTY_RESULTfrom core.categorize import CATEGORIES, understandfrom core import storage, analytics, auth, agent171 unmodified linesif not user:return {"reply": "Please sign in again.", "trace": []}records = storage.load(user, force=True)result = agent.run(message, records)return {"reply": result["reply"], "trace": result.get("trace", [])}12 unmodified lines131415161718192021222324171 unmodified lines19619719819920020120220320420520612 unmodified linesimport jsonfrom datetime import datefrom pathlib import Pathimport gradio as grfrom fastapi.responses import HTMLResponsefrom fastapi.staticfiles import StaticFilesfrom core.extract import extract_receipt, extract_payment, reconcilefrom core.categorize import CATEGORIES, understandfrom core import storage, analytics, auth, agent171 unmodified linesif not user:return {"reply": "Please sign in again.", "trace": []}records = storage.load(user, force=True)try:budget = storage.get_budget(user)except Exception:budget = 0.0result = agent.run(message, records, budget=budget)return {"reply": result["reply"], "trace": result.get("trace", [])}
123456789101112138 unmodified lines22232425262728293025 unmodified lines5657585960615 unmodified lines676869707172733 unmodified lines777879808182838485868788899091929394959697984 unmodified lines1031041051061071081091101111121131141151161171181191201211221231241251261271286 unmodified lines1351361371381391401411421434 unmodified lines14814915015115215315415515615715815943 unmodified lines2032042052062072082092102112122132142152162172182192201 unmodified line22222322422522622711 unmodified lines2392402412422432442453 unmodified lines249250251252253254"""Tool-using spending agent (Best Agent badge): plan + multi-step tool calls.Unlike the one-shot grounded chat, this agent does real ReAct-style reasoning:MiniCPM5-1B decides which analytics *tool* to call, reads the result, optionallycalls another, then answers — all on a ≤4B on-device model, no cloud. It returnsa visible trace of the tools it used (shown in the UI + good for judging).Reuses the text model loader / generation from core.chat; tools are thin wrappersover core.analytics. Falls back to the grounded one-shot answer if the smallmodel doesn't produce a clean plan."""from __future__ import annotations8 unmodified linesMAX_STEPS = 2 # fewer Modal round-trips -> fasterAGENT_TOKENS = 220# --------------------------------------------------------------------------- ## Period filtering# --------------------------------------------------------------------------- #def _period_records(records, period: str) -> list[dict]:"""Filter records by a flexible period: all | this_month | last_month |25 unmodified linesreturn keep(lambda d: (d.year, d.month) == (y, m))def _cur(records) -> str:c = analytics.dominant_currency(records)return f"{c} " if c else ""5 unmodified linesdef _t_total_spend(records, period="this_month", **_):recs = _period_records(records, period)tot = sum(analytics._num(r.get("total", 0)) for r in recs)return f"Total spend ({period}): {_cur(records)}{tot:.2f} over {len(recs)} transaction(s)."def _t_category_spend(records, category="", period="this_month", **_):3 unmodified linesif not matched: # fall back to a fuzzy contains-match (e.g. "food" ~ "Dining")matched = [r for r in recs if cat and cat in analytics._category(r).lower()]tot = sum(analytics._num(r.get("total", 0)) for r in matched)return f"{category or '?'} spend ({period}): {_cur(records)}{tot:.2f} over {len(matched)} transaction(s)."def _t_top_categories(records, period="this_month", **_):rows = analytics.spend_by_category(_period_records(records, period))[:3]if not rows:return f"No spending found ({period})."return f"Top categories ({period}): " + ", ".join(f"{r['category']} {_cur(records)}{r['amount']:.2f}" for r in rows)def _t_monthly_trend(records, **_):rows = analytics.spend_over_time(records, "Monthly")if not rows:return "No dated transactions yet."return "Monthly totals: " + ", ".join(f"{r['period']}={r['amount']:.2f}" for r in rows[-6:])def _t_recent(records, n=5, **_):4 unmodified linesrows = analytics.transactions_table(records)[:max(1, min(n, 12))]if not rows:return "No transactions yet."return "Recent: " + "; ".join(f"{d} {v} {t:.2f} ({c})" for d, v, t, c in rows)def _t_item_spend(records, query="", period="all", **_):recs = _period_records(records, period)q = (query or "").strip().lower()total, n = 0.0, 0for r in recs:for it in (r.get("line_items") or []):if q and q in str(it.get("name", "")).lower():total += analytics._num(it.get("amount"))n += 1return f"'{query}' ({period}): {_cur(records)}{total:.2f} across {n} item(s)."TOOLS = {"total_spend": _t_total_spend,"category_spend": _t_category_spend,"item_spend": _t_item_spend,"top_categories": _t_top_categories,"monthly_trend": _t_monthly_trend,"recent": _t_recent,}6 unmodified lines"a SPECIFIC month like '2026-07' (for 'July 2026'), or a year like '2026'.\n""Tools:\n""- total_spend({\"period\": ...})\n""- category_spend({\"category\": <a category name>, \"period\": ...})\n""- item_spend({\"query\": <item name, e.g. 'misal pav'>, \"period\": ...})\n""- top_categories({\"period\": ...})\n""- monthly_trend({})\n""- recent({\"n\": 5})\n""To call a tool, reply with EXACTLY one line:\n"4 unmodified lines"Always finish with an ANSWER line. Do not invent numbers.")# --------------------------------------------------------------------------- ## Parsing the model's action# --------------------------------------------------------------------------- #_CALL_RE = re.compile(r"CALL\s+(\w+)\s*\((.*)\)", re.S)_BARE_RE = re.compile(r"\b(total_spend|category_spend|item_spend|top_categories|monthly_trend|recent)\b\s*\((.*?)\)", re.S)_PERIODS = ("this_month", "last_month", "this_year", "last_year", "all", "year")43 unmodified linesreturn {"type": "unknown", "text": t}def _run_tool(name: str, records, args: dict) -> str:try:return TOOLS[name](records, **(args or {}))except Exception as e: # pragma: no coverreturn f"(tool error: {e})"# --------------------------------------------------------------------------- ## Agent loop# --------------------------------------------------------------------------- #def run(question: str, records: list[dict], max_steps: int = MAX_STEPS) -> dict:"""Plan + call tools + answer. Returns {reply, trace:[{tool,args,result}]}."""question = (question or "").strip()if not question:return {"reply": "Ask me anything about your spending.", "trace": []}1 unmodified linereturn {"reply": "You have no saved transactions yet — add a few and ask again.","trace": []}transcript = [{"role": "system", "content": SYSTEM_PROMPT},{"role": "user", "content": f"Today is {date.today().isoformat()}.\nQuestion: {question}\n"11 unmodified linesif action["type"] == "answer" and action["text"]:return {"reply": action["text"], "trace": trace}if action["type"] == "call":obs = _run_tool(action["name"], records, action["args"])trace.append({"tool": action["name"], "args": action["args"], "result": obs})transcript.append({"role": "assistant", "content": out})transcript.append({3 unmodified lineselse:break# Fallback: if the small model didn't produce a clean plan/answer, use the# grounded one-shot answer — but keep any tool trace we did gather.return {"reply": chat.answer(question, records), "trace": trace}12345678910111213141516178 unmodified lines262728293031323334353637383940414243444546474849505152535455565758596061626325 unmodified lines89909192939495969798991001011021031041051061071081095 unmodified lines1151161171181191201213 unmodified lines1251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012024 unmodified lines2072082092102112122132142152162172182192202212222232242256 unmodified lines2322332342352362372382392402412422432442454 unmodified lines25025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038143 unmodified lines4254264274284294304314324334344354364374384394404414424434444454464474484494501 unmodified line45245345445545645745845946046146246346446546611 unmodified lines4784794804814824834843 unmodified lines488489490491492"""Tool-using spending agent (Best Agent badge): plan + multi-step tool calls.Two layers, both grounded in core.analytics, both emitting a visible tool trace:1. A deterministic **router** (`_fast_answer`) maps a clear, single-intent questionstraight to the right analytics tool — instant, no model round-trip, no chanceof a hallucinated number. Most everyday questions land here.2. For open-ended / multi-part questions, a **ReAct loop** drives MiniCPM4.1-8B(on Modal): it picks a tool, reads the result, optionally calls another, thenanswers. If the small model never produces a clean plan, we fall back to thegrounded one-shot answer.Either way the UI gets `trace:[{tool,args,result}]`, so judges can see the toolsthe agent used. Everything stays well under the 32B cap (1.3B vision + 8B text)."""from __future__ import annotations8 unmodified linesMAX_STEPS = 2 # fewer Modal round-trips -> fasterAGENT_TOKENS = 220_MONTH_NAMES = ["January", "February", "March", "April", "May", "June", "July","August", "September", "October", "November", "December"]_MONTHS = {}for _i, _full in enumerate(_MONTH_NAMES, start=1):_MONTHS[_full.lower()] = _i_MONTHS[_full.lower()[:3]] = _i_MONTHS["sept"] = 9# Synonyms -> canonical category name, so "food"/"petrol"/"cab" resolve._CAT_SYNONYMS = {"food": "Dining", "restaurant": "Dining", "restaurants": "Dining","eating out": "Dining", "dine": "Dining", "dining": "Dining","grocery": "Groceries", "groceries": "Groceries","coffee": "Cafe", "cafe": "Cafe", "tea": "Cafe","fuel": "Fuel", "petrol": "Fuel", "diesel": "Fuel", "gas": "Fuel","transport": "Transport", "cab": "Transport", "taxi": "Transport","uber": "Transport", "ola": "Transport", "bus": "Transport", "metro": "Transport","medicine": "Pharmacy", "medicines": "Pharmacy", "pharmacy": "Pharmacy","health": "Health", "doctor": "Health", "hospital": "Health","clothes": "Clothing", "clothing": "Clothing", "apparel": "Clothing","rent": "Rent", "electricity": "Utilities", "water": "Utilities","utility": "Utilities", "utilities": "Utilities", "bills": "Utilities","shopping": "Shopping", "phone": "Telecom", "mobile": "Telecom","recharge": "Telecom", "subscription": "Subscriptions","subscriptions": "Subscriptions", "entertainment": "Entertainment","movie": "Entertainment", "travel": "Travel", "education": "Education","school": "Education", "fees": "Fees & Charges",}# --------------------------------------------------------------------------- ## Period filtering + labels# --------------------------------------------------------------------------- #def _period_records(records, period: str) -> list[dict]:"""Filter records by a flexible period: all | this_month | last_month |25 unmodified linesreturn keep(lambda d: (d.year, d.month) == (y, m))def _plabel(period: str) -> str:"""Human-friendly label for a period, always stated back to the user."""p = (period or "all").strip().lower()fixed = {"all": "all time", "this_month": "this month", "last_month": "last month","this_year": "this year", "last_year": "last year", "year": "this year"}if p in fixed:return fixed[p]m = re.match(r"^(\d{4})-(\d{1,2})$", p)if m:return f"{_MONTH_NAMES[int(m.group(2)) - 1]} {m.group(1)}"if re.match(r"^\d{4}$", p):return preturn p.replace("_", " ")def _cur(records) -> str:c = analytics.dominant_currency(records)return f"{c} " if c else ""5 unmodified linesdef _t_total_spend(records, period="this_month", **_):recs = _period_records(records, period)tot = sum(analytics._num(r.get("total", 0)) for r in recs)return f"Total spend ({_plabel(period)}): {_cur(records)}{tot:,.2f} over {len(recs)} transaction(s)."def _t_category_spend(records, category="", period="this_month", **_):3 unmodified linesif not matched: # fall back to a fuzzy contains-match (e.g. "food" ~ "Dining")matched = [r for r in recs if cat and cat in analytics._category(r).lower()]tot = sum(analytics._num(r.get("total", 0)) for r in matched)return f"{category or '?'} spend ({_plabel(period)}): {_cur(records)}{tot:,.2f} over {len(matched)} transaction(s)."def _t_item_spend(records, query="", period="all", **_):recs = _period_records(records, period)q = (query or "").strip().lower()total, n = 0.0, 0for r in recs:for it in (r.get("line_items") or []):if q and q in str(it.get("name", "")).lower():total += analytics._num(it.get("amount"))n += 1return f"'{query}' ({_plabel(period)}): {_cur(records)}{total:,.2f} across {n} item(s)."def _t_vendor_spend(records, vendor="", period="all", **_):recs = _period_records(records, period)v = (vendor or "").strip().lower()matched = [r for r in recs if v and v in str(r.get("vendor", "")).lower()]tot = sum(analytics._num(r.get("total", 0)) for r in matched)return f"Spend at '{vendor}' ({_plabel(period)}): {_cur(records)}{tot:,.2f} over {len(matched)} transaction(s)."def _t_top_categories(records, period="this_month", **_):rows = analytics.spend_by_category(_period_records(records, period))[:5]if not rows:return f"No spending found ({_plabel(period)})."return f"Top categories ({_plabel(period)}): " + ", ".join(f"{r['category']} {_cur(records)}{r['amount']:,.2f}" for r in rows)def _t_biggest_expense(records, period="all", **_):recs = _period_records(records, period)if not recs:return f"No transactions ({_plabel(period)})."r = max(recs, key=lambda r: analytics._num(r.get("total")))return (f"Biggest expense ({_plabel(period)}): {_cur(records)}{analytics._num(r.get('total')):,.2f} "f"at {r.get('vendor') or '(no name)'} on {r.get('date') or '?'} ({analytics._category(r)}).")def _t_average_spend(records, period="all", **_):recs = _period_records(records, period)n = len(recs)tot = sum(analytics._num(r.get("total", 0)) for r in recs)avg = tot / n if n else 0.0return (f"Average transaction ({_plabel(period)}): {_cur(records)}{avg:,.2f} "f"across {n} transaction(s) totalling {_cur(records)}{tot:,.2f}.")def _t_count_transactions(records, period="all", **_):recs = _period_records(records, period)tot = sum(analytics._num(r.get("total", 0)) for r in recs)return f"{len(recs)} transaction(s) ({_plabel(period)}), totalling {_cur(records)}{tot:,.2f}."def _t_budget_status(records, budget=0.0, **_):spent = sum(analytics._num(r.get("total", 0)) for r in _period_records(records, "this_month"))cur = _cur(records)budget = analytics._num(budget)if budget <= 0:return f"No monthly budget set yet. This month you've spent {cur}{spent:,.2f}."left = budget - spentif left >= 0:return f"Budget this month: {cur}{budget:,.2f}. Spent {cur}{spent:,.2f}. You have {cur}{left:,.2f} left."return f"Budget this month: {cur}{budget:,.2f}. Spent {cur}{spent:,.2f}. You are {cur}{abs(left):,.2f} over budget."def _t_monthly_trend(records, **_):rows = analytics.spend_over_time(records, "Monthly")if not rows:return "No dated transactions yet."return "Monthly totals: " + ", ".join(f"{r['period']}={r['amount']:,.2f}" for r in rows[-6:])def _t_recent(records, n=5, **_):4 unmodified linesrows = analytics.transactions_table(records)[:max(1, min(n, 12))]if not rows:return "No transactions yet."return "Recent: " + "; ".join(f"{d} {v} {t:,.2f} ({c})" for d, v, t, c in rows)TOOLS = {"total_spend": _t_total_spend,"category_spend": _t_category_spend,"item_spend": _t_item_spend,"vendor_spend": _t_vendor_spend,"top_categories": _t_top_categories,"biggest_expense": _t_biggest_expense,"average_spend": _t_average_spend,"count_transactions": _t_count_transactions,"budget_status": _t_budget_status,"monthly_trend": _t_monthly_trend,"recent": _t_recent,}6 unmodified lines"a SPECIFIC month like '2026-07' (for 'July 2026'), or a year like '2026'.\n""Tools:\n""- total_spend({\"period\": ...})\n""- category_spend({\"category\": <name>, \"period\": ...})\n""- item_spend({\"query\": <item name, e.g. 'misal pav'>, \"period\": ...})\n""- vendor_spend({\"vendor\": <shop/payee name>, \"period\": ...})\n""- top_categories({\"period\": ...})\n""- biggest_expense({\"period\": ...})\n""- average_spend({\"period\": ...})\n""- count_transactions({\"period\": ...})\n""- budget_status({})\n""- monthly_trend({})\n""- recent({\"n\": 5})\n""To call a tool, reply with EXACTLY one line:\n"4 unmodified lines"Always finish with an ANSWER line. Do not invent numbers.")HELP_TEXT = ("I'm your spending assistant — I read your saved transactions and answer with real numbers. ""Try things like:\n""• \"How much did I spend this month?\" or \"…in July 2026?\"\n""• \"What's my top category?\" / \"Where did my money go?\"\n""• \"How much on Groceries last month?\"\n""• \"What's my biggest expense?\" • \"What's my average spend?\"\n""• \"How many transactions this year?\" • \"Am I over budget?\"")# --------------------------------------------------------------------------- ## Deterministic router (fast, reliable, still emits a tool trace)# --------------------------------------------------------------------------- #def _parse_period(ql: str):"""Resolve a time phrase to a canonical period, or None if unspecified."""if re.search(r"\b(all[\s-]?time|overall|in total|altogether|ever|so far|to date|lifetime)\b", ql):return "all"if re.search(r"\b(last|previous|prev)\s+month\b", ql):return "last_month"if re.search(r"\bthis\s+month\b|\bcurrent\s+month\b|\bthis\s+mth\b", ql):return "this_month"if re.search(r"\b(last|previous|prev)\s+year\b", ql):return "last_year"if re.search(r"\bthis\s+year\b|\bcurrent\s+year\b", ql):return "this_year"ym = re.search(r"\b(20\d{2})-(\d{1,2})\b", ql)if ym:return f"{ym.group(1)}-{int(ym.group(2)):02d}"mon = re.search(r"\b(jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|jun(?:e)?|"r"jul(?:y)?|aug(?:ust)?|sep(?:t)?(?:ember)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?)\b", ql)if mon:mo = _MONTHS.get(mon.group(1)) or _MONTHS.get(mon.group(1)[:3])yr = re.search(r"\b(20\d{2})\b", ql)year = int(yr.group(1)) if yr else date.today().yearif mo:return f"{year}-{mo:02d}"yr = re.search(r"\b(20\d{2})\b", ql)if yr:return yr.group(1)return Nonedef _detect_category(ql: str):from core.categorize import CATEGORIESfor cat in CATEGORIES:if re.search(r"\b" + re.escape(cat.lower()) + r"\b", ql):return catfor syn, cat in _CAT_SYNONYMS.items():if re.search(r"\b" + re.escape(syn) + r"\b", ql):return catreturn Nonedef _detect_vendor(ql: str, records):"""Match a known vendor name appearing in the question (longest first)."""seen = {}for r in records:v = str(r.get("vendor", "")).strip()if len(v) >= 3:seen[v.lower()] = vfor low in sorted(seen, key=len, reverse=True):if re.search(r"\b" + re.escape(low) + r"\b", ql):return seen[low]return Nonedef _fast_answer(question: str, records, budget):"""Return (reply, trace) for a clear single-intent question, else None."""bare = question.lower().strip()ql = " " + bare + " "if re.fullmatch(r"(hi|hello|hey|yo|hiya|howdy|sup|namaste|hi there|hey there)[\s!.,]*", bare) or \re.search(r"\bwhat can you (do|help)\b|\bhow do you work\b|\bwho are you\b|\bwhat do you do\b", ql) or \bare in ("help", "?", "??", "menu", "options"):return HELP_TEXT, []period = _parse_period(ql)P = period or "all"def fire(tool, args, fn):obs = fn()return obs, [{"tool": tool, "args": args, "result": obs}]if re.search(r"\bbudget\b|\bover\s?spend|under\s?spend|can i (afford|spend)\b", ql):return fire("budget_status", {}, lambda: _t_budget_status(records, budget=budget))if re.search(r"\bhow many\b.*\b(transaction|bill|receipt|purchase|entr|payment)|number of (transaction|bill|receipt|purchase)", ql):return fire("count_transactions", {"period": P}, lambda: _t_count_transactions(records, period=P))if re.search(r"\b(biggest|largest|highest|most expensive|priciest|max(imum)?|single largest)\b", ql) and "categor" not in ql:return fire("biggest_expense", {"period": P}, lambda: _t_biggest_expense(records, period=P))if re.search(r"\b(average|avg|mean|typical|on average)\b", ql):return fire("average_spend", {"period": P}, lambda: _t_average_spend(records, period=P))if re.search(r"\b(trend|over time|by month|each month|month by month|monthly|per month|month[\s-]?wise)\b", ql):return fire("monthly_trend", {}, lambda: _t_monthly_trend(records))if re.search(r"\b(recent|latest|last few|show me|list).*(transaction|spend|purchase|bought|buy)|what did i (buy|spend on) (recently|lately)", ql):return fire("recent", {"n": 5}, lambda: _t_recent(records, n=5))if re.search(r"\b(top categor|biggest categor|main categor|where.*(money|spend|spent).*(go|went)|"r"spend most|most on|breakdown|by category|categor(y|ies))\b", ql):return fire("top_categories", {"period": P}, lambda: _t_top_categories(records, period=P))cat = _detect_category(ql)if cat and re.search(r"\b(spend|spent|spending|cost|how much|total|pay|paid)\b", ql):return fire("category_spend", {"category": cat, "period": P},lambda: _t_category_spend(records, category=cat, period=P))ven = _detect_vendor(ql, records)if ven and re.search(r"\b(spend|spent|how much|total|pay|paid|at|from)\b", ql):return fire("vendor_spend", {"vendor": ven, "period": P},lambda: _t_vendor_spend(records, vendor=ven, period=P))if re.search(r"\b(how much|total|spend|spent|spending)\b", ql):return fire("total_spend", {"period": P}, lambda: _t_total_spend(records, period=P))return None# --------------------------------------------------------------------------- ## Parsing the model's action (ReAct loop)# --------------------------------------------------------------------------- #_CALL_RE = re.compile(r"CALL\s+(\w+)\s*\((.*)\)", re.S)_BARE_RE = re.compile(r"\b(" + "|".join(TOOLS) + r")\b\s*\((.*?)\)", re.S)_PERIODS = ("this_month", "last_month", "this_year", "last_year", "all", "year")43 unmodified linesreturn {"type": "unknown", "text": t}def _run_tool(name: str, records, args: dict, budget: float = 0.0) -> str:try:call_args = dict(args or {})if name == "budget_status":call_args.setdefault("budget", budget)return TOOLS[name](records, **call_args)except Exception as e: # pragma: no coverreturn f"(tool error: {e})"# --------------------------------------------------------------------------- ## Agent entry point# --------------------------------------------------------------------------- #def run(question: str, records: list[dict], max_steps: int = MAX_STEPS,budget: float = 0.0) -> dict:"""Answer a spending question. Returns {reply, trace:[{tool,args,result}]}.Tries the deterministic router first (instant, exact), then the ReAct loop,then the grounded one-shot fallback."""question = (question or "").strip()if not question:return {"reply": "Ask me anything about your spending.", "trace": []}1 unmodified linereturn {"reply": "You have no saved transactions yet — add a few and ask again.","trace": []}# 1) Fast, deterministic router.try:fast = _fast_answer(question, records, budget)if fast is not None:return {"reply": fast[0], "trace": fast[1]}except Exception as e: # pragma: no cover - never let the router break chatprint(f"[agent] fast path failed: {e}")# 2) ReAct loop on the 8B (for open-ended / multi-part questions).transcript = [{"role": "system", "content": SYSTEM_PROMPT},{"role": "user", "content": f"Today is {date.today().isoformat()}.\nQuestion: {question}\n"11 unmodified linesif action["type"] == "answer" and action["text"]:return {"reply": action["text"], "trace": trace}if action["type"] == "call":obs = _run_tool(action["name"], records, action["args"], budget)trace.append({"tool": action["name"], "args": action["args"], "result": obs})transcript.append({"role": "assistant", "content": out})transcript.append({3 unmodified lineselse:break# 3) Fallback: grounded one-shot answer (keep any trace we gathered).return {"reply": chat.answer(question, records), "trace": trace}
271 unmodified lines27227327427527627727827928028132 unmodified lines314315316317318319320271 unmodified lines/* chat */function bubble(text, who) { const d = document.createElement("div"); d.className = "bubble " + who; d.textContent = text; $("#chat-msgs").appendChild(d); $("#chat-msgs").scrollTop = 1e9; return d; }async function chat() {const q = $("#chat-in").value.trim(); if (!q) return; $("#chat-in").value = ""; bubble(q, "me"); const b = bubble("…", "bot");try { const r = await api("chat", { token: S.token, message: q, history_json: JSON.stringify(S.chat.slice(-3)) }); b.textContent = r.reply; if (r.trace && r.trace.length) { const t = document.createElement("div"); t.className = "tr"; t.textContent = "used: " + r.trace.map(x => x.tool).join(" → "); b.appendChild(t); } S.chat.push({ q, a: r.reply }); }catch (e) { b.textContent = "Error: " + e; }}/* file pickers + camera — native <label for> opens the picker; we just react to change */32 unmodified lines$("#see-all").onclick = () => view("txns");["#tx-q", "#tx-cat", "#tx-period"].forEach(s => $(s).addEventListener("input", () => { if (s === "#tx-q") renderTxnList(); else loadTxns(); }));$("#chat-send").onclick = chat; $("#chat-in").addEventListener("keydown", e => { if (e.key === "Enter") chat(); });$("#chat-chips").innerHTML = ["How much did I spend this month?", "What's my top category?", "How much on Dining?"].map(q => `<button class="chip">${q}</button>`).join("");$$("#chat-chips .chip").forEach(c => c.onclick = () => { $("#chat-in").value = c.textContent; chat(); });if (S.token) { showApp(); loadDashboard(); } else showLogin();}271 unmodified lines27227327427527627727827928028128228328428528628728828929029129229329429529629729829930032 unmodified lines333334335336337338339271 unmodified lines/* chat */function bubble(text, who) { const d = document.createElement("div"); d.className = "bubble " + who; d.textContent = text; $("#chat-msgs").appendChild(d); $("#chat-msgs").scrollTop = 1e9; return d; }function prettyPeriod(p) {if (!p) return ""; const f = { this_month: "this month", last_month: "last month", this_year: "this year", last_year: "last year", year: "this year", all: "all time" };if (f[p]) return f[p]; const m = /^(\d{4})-(\d{1,2})$/.exec(p); if (m) return `${MON[+m[2] - 1]} ${m[1]}`; return p;}function traceLabel(x) {const a = x.args || {}, parts = [];if (a.category) parts.push(a.category); if (a.vendor) parts.push(a.vendor); if (a.query) parts.push(a.query);if (a.period) parts.push(prettyPeriod(a.period)); if (a.n) parts.push(a.n + " rows");return x.tool + (parts.length ? ` (${parts.join(", ")})` : "");}async function chat() {const q = $("#chat-in").value.trim(); if (!q) return; $("#chat-in").value = ""; bubble(q, "me"); const b = bubble("…", "bot");try {const r = await api("chat", { token: S.token, message: q, history_json: JSON.stringify(S.chat.slice(-3)) });b.textContent = r.reply;if (r.trace && r.trace.length) {const t = document.createElement("div"); t.className = "tr";t.innerHTML = `<span class="tr-h">🔧 tools used</span>` + r.trace.map(x => `<span class="tr-step">${traceLabel(x)}</span>`).join('<span class="tr-arrow">→</span>');b.appendChild(t);}S.chat.push({ q, a: r.reply });}catch (e) { b.textContent = "Sorry — I couldn't reach the assistant. Please try again."; }}/* file pickers + camera — native <label for> opens the picker; we just react to change */32 unmodified lines$("#see-all").onclick = () => view("txns");["#tx-q", "#tx-cat", "#tx-period"].forEach(s => $(s).addEventListener("input", () => { if (s === "#tx-q") renderTxnList(); else loadTxns(); }));$("#chat-send").onclick = chat; $("#chat-in").addEventListener("keydown", e => { if (e.key === "Enter") chat(); });$("#chat-chips").innerHTML = ["How much did I spend this month?", "Where did my money go?", "What's my biggest expense?", "Am I over budget?"].map(q => `<button class="chip">${q}</button>`).join("");$$("#chat-chips .chip").forEach(c => c.onclick = () => { $("#chat-in").value = c.textContent; chat(); });if (S.token) { showApp(); loadDashboard(); } else showLogin();}
125 unmodified lines126127128129130131132125 unmodified lines.bubble{max-width:82%;padding:12px 15px;border-radius:18px;font-size:.9rem;line-height:1.5;white-space:pre-wrap}.bubble.me{align-self:flex-end;background:var(--lime);color:var(--lime-ink);border-bottom-right-radius:6px;font-weight:600}.bubble.bot{align-self:flex-start;background:var(--surface2);border:1px solid var(--line);border-bottom-left-radius:6px}.bubble .tr{font-size:.69rem;color:var(--muted);margin-top:8px;border-top:1px solid #ffffff14;padding-top:6px}.chips{display:flex;gap:8px;flex-wrap:wrap;margin:12px 0}.chip{background:var(--surface2);border:1px solid var(--line);color:var(--muted);border-radius:999px;padding:8px 13px;font-size:.8rem}.chip:hover{color:var(--ink);border-color:var(--lav)}125 unmodified lines126127128129130131132133134135125 unmodified lines.bubble{max-width:82%;padding:12px 15px;border-radius:18px;font-size:.9rem;line-height:1.5;white-space:pre-wrap}.bubble.me{align-self:flex-end;background:var(--lime);color:var(--lime-ink);border-bottom-right-radius:6px;font-weight:600}.bubble.bot{align-self:flex-start;background:var(--surface2);border:1px solid var(--line);border-bottom-left-radius:6px}.bubble .tr{font-size:.69rem;color:var(--muted);margin-top:9px;border-top:1px solid #ffffff14;padding-top:7px;display:flex;flex-wrap:wrap;align-items:center;gap:5px}.bubble .tr-h{color:var(--lime);font-weight:700;letter-spacing:.02em;margin-right:2px}.bubble .tr-step{background:#ffffff10;border:1px solid var(--line);border-radius:7px;padding:2px 7px;font-family:ui-monospace,Menlo,Consolas,monospace;font-size:.66rem;color:var(--ink)}.bubble .tr-arrow{color:var(--muted);opacity:.7}.chips{display:flex;gap:8px;flex-wrap:wrap;margin:12px 0}.chip{background:var(--surface2);border:1px solid var(--line);color:var(--muted);border-radius:999px;padding:8px 13px;font-size:.8rem}.chip:hover{color:var(--ink);border-color:var(--lav)}
README.md+85-38
app.py+6-3
core/agent.py+278-40
frontend/assets/app.js+22-3
frontend/index.html+4-1