`expense-tracker` Asks Gemini for Your Totals, Then Reads the Answer With a Regex

A small FastAPI project shows the clean way to hand an LLM database tools, and the fragile way it reads the prose back.

7 min read • View on GitHub • More from vinishamulpuri8109

An editorial illustration of an open ledger book on a plain desk. The left page is a dense crosshatched grid of small numbers, while a speech bubble rises from the right page with the numbers dissolved into one flowing handwritten sentence. A single taut thread connects one number in the grid up into the bubble. The image states the article's core tension: structured data on one side, spoken language on the other.
Structured data on the left page. Prose on the right. The whole article lives in the thread between them.
Key Takeaways

The Sidebar Draws Its Charts by Reading English

Every time the page loads, the frontend sends a natural-language question to the backend. It asks for the top six spending categories across a fixed date window, and the model answers in a paragraph. Then the browser runs a regex across each line of that paragraph to pull out category names and dollar amounts, and uses the matches to draw the sidebar bar charts.

const m = line.match(/([A-Za-z &]+?)\s*[:\-–—]\s*\$?([\d,]+\.?\d*)/);

Two costs fall out of that one line. The first is fragility. The pattern matches any line with a colon, dash, or en dash followed by a number, so a line reading Date range: 2024-03-29 parses as a category called "Date range" worth 2024. The model is being asked to be a database and a formatter at the same time, and the client is trusting its grammar.

The second is expense. The sidebar fires a paid model call on every page load, against a date window hard-coded to a range that never updates as the data changes. The regex is not a bug in isolation. It is a symptom of a boundary drawn in the wrong place.

The Backend Already Solved This

app/tools.py exposes three deterministic functions the model can call: get_spending, list_transactions, and get_top_categories. The important part is not the SQL. It is what happens on bad input.

cat, err = _validate_category(category)
if err:
    return {"error": err}

The tool returns its failure as data. Not an exception, not a 500. A dict with an error key the model can read. That distinction matters because of where the return value goes: the tool output is handed back to the model as a function response.

A structured error like "Unknown category 'Dining'. Valid values: [...]" gives the model something to act on, so it can retry with a valid category on the next round of the loop. An exception would have to be caught and reshaped anyway, and the useful detail (which value was wrong, what the valid set is) would be lost on the way back. This is the correct pattern for LLM tool design, and it is sitting right there in the repo. The frontend that needed it most does not use it.

Five Rounds, Three Tools, One Guardrail

app/agent.py runs the loop. A system prompt sets the rules, a TOOL_MAP dict dispatches by name, and the loop iterates up to MAX_ROUNDS = 5 before falling back to a plain string.

Two decisions stand out. The round cap is a cost control: every round is a paid API call, so five is a budget as much as a correctness bound. And the system prompt's core rule is a guardrail against hallucinated totals. Never calculate or estimate figures from memory, always call a tool for the numbers.

There is a small crack in that rule. The model is also told to convert cents to dollars by dividing by 100. The tool already returns an integer count of cents. Delegating that arithmetic to the model, rather than returning a dollar string from the tool, is a quiet exception to "never compute from memory."

The self-correction loop. A tool error becomes a model retry instead of a crash, because the tool returns its failure as structured data the model can read. Watch the counter climb toward the round cap when you keep choosing the correction path.

The Whole Database Is a CSV and a Global

app/db.py reads expenses.csv into in-memory SQLite at startup through a FastAPI lifespan hook. The table stores amount_cents as an integer, indexes date and category, and fails fast with a line number when an amount will not parse. Storing money as integers is the right instinct, and the indexes match the query patterns the tools actually use.

Two soft spots remain. The dollar-to-cents conversion routes through float first, so the half-up rounding is only as reliable as the float representation underneath it. And the round-half-up rule is not symmetric for negative values, so refunds would round toward negative infinity.

There is also a real bug. The CSV path is relative to the working directory while the frontend path is computed from __file__. Start the server from anywhere but the repo root and the lifespan raises FileNotFoundError before the first request lands.

CSV columnTypeNote
Transaction_IDTEXT
DateTEXTindexed, normalized before comparison
TimeTEXT
AmountTEXTconverted to integer cents at load
DescriptionTEXT
MerchantTEXT
CategoryTEXTindexed, validated against a fixed set
A close-up editorial illustration of a single printed sentence being cut apart by a small pair of scissors into two neat piles: one pile of labels and one pile of numbers. One stray word, 'Date', has been cut into the numbers pile by mistake and sits slightly askew, while a magnifying glass rests over the sentence revealing faint crosshatch lines threading between the words. The image is the regex operation drawn as a physical act, and the misplaced word makes its fragility visible.
The regex, drawn as a physical act. The stray "Date" in the numbers pile is the failure mode: any line with a colon and a number matches.

The Provider Seam That Isn't

app/llm.py carries a clear promise in its module docstring: Swap this file to change the LLM provider (e.g. AWS Bedrock). The idea is right. One file holds the only code that talks to the provider, and everything else calls into it.

But app/agent.py imports google.generativeai and builds genai.protos.Tool, FunctionDeclaration, Schema, and Type at module load. Swap to Bedrock and you rewrite the schema layer in agent.py too, not just the file that was supposed to be the seam. It is the same pattern as the regex: a boundary drawn in the right place, then not held.

How It Compares

Every other entry below uses the LLM for nothing, or not at all. This repo is the only one in the set where a language model sits between the user and the numbers, which is precisely why its boundary problems are worth studying. The comparison is about approach, not maturity, since the target has no verified feature set beyond its source.

ProjectStackData storeRole of the LLMStandout
vinishamulpuri8109/expense-trackerFastAPI, vanilla JSIn-memory SQLite from CSVQuery engine via tool calls; also answer formatterTools return errors as data; frontend regex-parses the prose
niinpatel/expense-trackerMERN (React, Express, MongoDB)MongoDBNoneConventional full-stack CRUD with pie charts
jakubgarfield/expensesReact PWAGoogle SheetsNoneSpreadsheet as backend; still trusts a third party
Expense.fyiNext.js, Vercel, ResendHostedNoneManual entry, no Plaid integration at launch
ezBookkeepingGo, self-hostedSelf-hostedNonePositioned as full bookkeeping, not lightweight logging
zeroTypeScript, local-firstWatermelonDB on-deviceNoneOffline-first, no cloud
GnuCash / LedgerDesktop / CLILocal file, Git, or PostgreSQLNoneAccounting-grade control, higher setup cost

The comparator projects are documented alternatives in the category, not confirmed influences on the target.

What a Zero-Star Repo Can Still Teach

The value of this repo is not its features or its adoption. It is that it contains both halves of the lesson in one small tree: the tool boundary done right, and the presentation boundary done wrong. The takeaway is plain. When the model already speaks structured data on one side of your app, do not make the other side read its grammar.