DEV Community

Nirmana Herath
Nirmana Herath

Posted on Edited on

How I Built an Automated LLM Evaluation Harness to Eliminate AI Math Hallucinations on CSVs

Update (v1.0.0 is LIVE!): You can now try AskGrid free (zero signup, 1-click sample dataset) at AskGrid — or check out the full source code on Github

The Problem With "Chat With Your CSV" Apps

Most AI spreadsheet tools do one of two scary things:

  1. Paste your private CSV rows directly into an LLM prompt and pray it doesn't hallucinate the math, or
  2. Let the LLM write arbitrary Python code and run exec() on the server — a massive Remote Code Execution (RCE) risk.

While building AskGrid ("Don't Scroll, Just Ask.") solo on a \$0 budget with Python 3.12, FastAPI, Pydantic v2, and Pandas, I locked down two non-negotiable rules:

  • Zero raw rows ever go to the LLM (only column names + inferred data types).
  • Zero LLM math and zero exec() — the LLM's only job is to act as a Natural-Language Intent Router, outputting a strict Pydantic JSON AnalysisIntent. Deterministic Pandas code executes 10 allowlisted operations and returns a "How this was calculated" audit trail.

The Architecture: LLM-as-Router + Deterministic Execution

User Question ("Top 3 customers by spend in Colombo?")
        │
        ▼
[Schema-Only Prompt]  ──▶  Gemini Flash-Lite (temperature=0.0, Pydantic Structured Output)
        │                  (sees ONLY {column: type} — ZERO row values!)
        ▼
AnalysisIntent JSON   ──▶  Allowlist Validator (blocks fake columns, bad dtypes, n > 50)
        │
        ▼
Deterministic Pandas  ──▶  Exact Result + ChartSpec + CalculationAudit ("How it was calculated")
Enter fullscreen mode Exit fullscreen mode

To handle real-world cloud flakiness on a free tier, I put Gemini behind a provider-agnostic Python Protocol (AIProvider) with a 5-model fallback chain and a lightweight Circuit Breaker that skips models returning 503 / 429 / transport timeouts during a cooldown window.


3 Real Bugs My Golden Dataset & Eval Harness Caught

You don't appreciate automated tests and eval harnesses until they save you in real life. Mine caught three sneaky bugs before a single user ever touched the UI:

1. The Currency Regex That Ate Order IDs (ORD-1011 → -1011)

My CSV parser cleans currency strings like LKR 125,000.00 into floats. My first regex matched [A-Za-z]{1,5}\s*-?\d+ — which accidentally matched "ORD-1011" as negative currency -1011!

Golden test Q08 caught it immediately. I tightened the regex to require real currency symbols or known currency codes + space, and added a regression test.

2. The httpx2.ReadTimeout That Escaped My Circuit Breaker

My Gemini adapter caught (ServerError, ClientError, ValueError). During a live eval run, a slow free-tier response threw httpx2.ReadTimeout — which isn't a subclass of ServerError! Widening the fallback catch inside the model loop fixed it so network timeouts cleanly trip the Circuit Breaker and route to the next healthy Flash pool.

3. Prompt v1.0 → v1.1: Why "Looks Good in Swagger" Isn't Enough

I built an end-to-end eval harness (server/evals/run_evals.py) that runs 18 synthetic golden cases (15 computable questions across all 10 operations + 3 safety/refusal/prompt-injection cases) all the way from plain English → live Gemini → validator → Pandas → exact ground-truth number assertion.

First run (PROMPT_VERSION = "v1.0"):

  • Intent Accuracy: 17/18 (94.4%)
  • E2E Numerical Exact: 14/15 (93.3%)
  • Safety & Prompt Injection: 3/3 (100.0%)

Why did Q07 ("Who are the top 3 customers by spend in Colombo?") fail? Gemini got the filter, column, and grouping right — but picked group_aggregate (returning all 4 Colombo customers) instead of top_n(n=3)!

The Fix (PROMPT_VERSION = "v1.1"):

I added one explicit disambiguation rule separating top_n (ranked/limited questions) from group_aggregate (all groups) and re-ran the full suite:

Metric Prompt v1.0 Prompt v1.1
Intent Accuracy 17/18 (94.4%) 18/18 (100.0%)
E2E Exact Pandas Math 14/15 (93.3%) 15/15 (100.0%)
Safety & Refusals (incl. Prompt Injection) 3/3 (100.0%) 3/3 (100.0%)
Median Latency (p50) 1.74s 1.17s

What's Next

The entire Python + AI backend (v0.3.0) is now live on GitHub with ruff, strict mypy, pytest (23 offline CI tests), pip-audit, and Gitleaks secret scanning. Next up: building the React + TypeScript + Tailwind CSS interactive workspace UI!

  • Follow the build in public on X: https://x.com/niRmana_dev

Top comments (11)

Collapse
 
kami_butt_69b922ade8de012 profile image
Agentic Affairs •

The Q07 miss is the best argument in the whole piece — 94.4% intent accuracy looked fine until the exact-number assertion caught the model picking group_aggregate over top_n. A harness that only checks 'did it roughly understand' would have shipped that bug. Do you re-run the 18 golden cases on every prompt tweak, or only when you change the router itself?

Collapse
 
nirmana11 profile image
Nirmana Herath •

Thanks so much for reading! Completely agree checking only "did it roughly get the intent" would have quietly shipped that 4-row bug.

Right now I split it into two layers:

  1. GitHub Actions CI (every PR): Runs fast offline mocked tests (~0.8s) so CI stays deterministic and free of API rate limits.
  2. Live 18-case eval harness: I re-run it manually on every prompt tweak (with a PROMPT_VERSION bump), intent schema change, or model fallback update — and log the before/after scorecard so nothing silently regresses.
Collapse
 
kami_butt_69b922ade8de012 profile image
Agentic Affairs •

The PROMPT_VERSION bump plus a before/after scorecard is the discipline that makes manual re-runs trustworthy — without the version stamp, a re-run proves nothing about which prompt produced the score. Is the scorecard checked into the repo alongside the prompts, or kept separately? If it's in the repo, the live harness is one step away from running on a schedule instead of by hand.

Thread Thread
 
nirmana11 profile image
Nirmana Herath •

Great point — right now I keep the full benchmark log in my private project notes and publish the summary table in the repo's README.md, while evals/run_evals.py already supports an --output flag to export timestamped JSON scorecards.

Checking those scorecards directly into server/evals/scorecards/ and running the live harness on a weekly GitHub Actions schedule cron (using GEMINI_API_KEY from repo secrets) is a brilliant next step — even when I don't touch prompts.py, it would catch silent upstream model drift automatically at zero cost. Adding that straight to my v1.1.0 roadmap — really appreciate the suggestion!

Thread Thread
 
kami_butt_69b922ade8de012 profile image
Agentic Affairs •

The weekly cron is the real win here — drift happens without anyone touching prompts.py, so a harness that only runs on your own changes would miss exactly the failure it exists to catch. Checking the scorecards in makes the drift visible in the repo history too. Will the scorecards record the model version, so a regression is attributable to the provider and not your code?

Collapse
 
userxnom profile image
Abdullah Naseer •

The two non-negotiable rules are what make this design convincing — sending only column names and inferred types to the LLM, and letting it act purely as a natural-language intent router while deterministic Pandas code runs the 10 allowlisted operations, with a "how this was calculated" audit trail. The Q07 story is the best proof of why the harness matters: 17/18 intent accuracy at 94.4% in v1.0 looked fine until Gemini picked group_aggregate instead of top_n for the top 3 customers in Colombo, and the one-line disambiguation in v1.1 took it to 18/18 and 15/15 exact. The ORD-1011 regex bug turning an order ID into -1011 is another great catch. As you add new operations beyond the current 10, how are you planning to grow the 18-case golden dataset — will you add a case for every new operation, or are you thinking about generating cases from real user questions once the React workspace UI is live?

Collapse
 
nirmana11 profile image
Nirmana Herath •

Really appreciate the thoughtful feedback! I'm planning to grow it using both tracks:

  1. Per new operation / bug fix: Every new allowlisted operation or parser fix gets 2–3 new synthetic cases (happy path + edge case + refusal/regression) before merging.
  2. Privacy-safe beta feedback loop: Once the React UI is live, AskGrid won't log or store users' private CSV rows or PII instead, I've built a simple Correct/Wrong rating button and will turn anonymized failure patterns (and feedback on the built-in sample dataset) into new synthetic golden cases. That way the eval set grows from real phrasing without compromising user privacy!
Collapse
 
ibuildinpublic profile image
Ehsan •

The ORD-1011 currency regex bug is such a classic false positive. Treating group_aggregate vs top_n as a disambiguation rule in the prompt is a smart fix. Are you going to keep expanding the golden set as new operations land in the React UI?

Collapse
 
nirmana11 profile image
Nirmana Herath •

Thank you! That ORD-1011 regex bug definitely humbled me early glad a test caught it instead of a user.

Yes! Every new operation or tricky phrasing we discover once the React UI goes live will become a permanent synthetic test case in the golden suite before we ship changes. Keeping the suite growing alongside the app is the best way to make sure prompt tweaks don't break older operations.

Collapse
 
robertpaschal profile image
Odinaka Robert Nnamani •

ord-1011 turning into -1011 is the bug that sells the harness. a currency regex eating order ids, caught by a golden test before any user saw it.

Collapse
 
nirmana11 profile image
Nirmana Herath •

Haha, honestly that was my favorite catch of the whole build! Nothing teaches you to respect golden-dataset tests faster than watching your own currency parser quietly turn an order ID into -1011. Thanks for reading!