Building a Data Analyst Agent: Grounding an LLM in Tools, Not Guesses
The hard part of “talk to your data” is not getting an answer; it is getting one you can defend. With code from our analytics agent, here is how we keep every answer anchored to the data, and how the system reports what it refused to do.
Point a language model at a spreadsheet and it will always answer. That is the problem, stated in one sentence. A model asked about a column that does not exist will not stop and tell you the column does not exist. It will reach for the nearest plausible thing, write a query, and hand back a confident, well-formatted number that is quietly fiction. The hard part of a "talk to your data" system is not getting an answer. It is making the answer one you can defend to the person who signs off on it.
This is a technical write-up of how the Data Analyst Agent does that, with the code that does it. The theme throughout is a single discipline: the model is never trusted to be right about what is in the data. It is checked, every time, against the data itself.
Plan and execute over a closed registry
The agent does not improvise. It plans. A planner chooses which tools to run and in what order; an executor loads the dataset and runs them. The planner never touches the data, and the executor never runs a tool that is not in the registry.
The registry is the leverage point. The space of good analytic actions is knowable and small, so it is enumerated: profile_dataset, data_quality_report, correlation_analysis, trend_analysis, anomaly_scan, kmeans_clusters, duckdb_query, multidim_pivot, train_supervised_model, evaluate_ml_predictions, score_with_model, explain_model, shap_explain_prediction, forecast_with_model, auto_insights, and a handful of chart specs. The planner's job is selection and sequencing from that fixed set, not invention.
Every tool declares its arguments as a Pydantic model that forbids anything it did not ask for:
class ToolArgs(BaseModel):
model_config = ConfigDict(extra="forbid", protected_namespaces=())
That extra="forbid" is the first line of defence. A tool call carrying an argument the tool never declared does not get coerced or ignored. It fails validation. The action space is closed, which is exactly what makes it testable.
Tool selection by retrieval, not a wall of prompt
A dozen-plus tools, each with its own arguments and documentation, is more than you want in a prompt at once. Pour every schema in and the planner chooses worse, the way anyone does when handed the whole catalogue and told to pick fast.
So tool documentation lives in a local corpus indexed with FAISS, and the planner is handed a slimmed, retrieval-filtered view of the tools relevant to the question rather than the full set. The prompt stays small and the selection stays sharp.
For a registry this size — around twenty tools — retrieval is a modest optimisation, not a necessity, and it carries its own failure mode: the retriever can quietly filter out the one tool the question actually needed, and the planner never sees it was an option. That failure is silent, which is exactly the kind the rest of this system is built to refuse. So it is measured rather than assumed. A labelled recall-at-k set (behind GET /health/rag-eval) checks that the expected tool doc comes back for a fixed set of questions. The planner is handed the top six docs; the labelled set scores recall at a tighter k, and on the current twelve-query set recall is 1.0 at k = 1, 3 and 5 — the right doc is the top hit every time. Recall@1, not just @5, is what makes that worth anything: a perfect @5 covers a quarter of a twenty-tool registry and would say little, whereas a perfect @1 says the retriever ranks the right doc first, not merely includes it. The set is small and self-authored, so treat the number as a regression guard rather than a benchmark; the day it drops is the day retrieval starts hiding tools.
Validating every call against the real schema
The registry stops the model from inventing a tool. It does nothing about the model inventing a column. That is handled separately, and without exception: every proposed tool call is validated against the actual dataframe before a single row is read. The checks are specific per tool:
def validate_columns(df, columns, arg_name):
missing = [col for col in (columns or []) if col not in df.columns]
if missing:
raise ValueError(f"{arg_name} contains unknown columns: {missing}")
A pivot has its index, columns, and values checked. A training call has its target_col and feature_cols checked. A chart spec has its x and y checked. SQL is the interesting case, because you cannot check SQL with a column list. So we let the database judge it, in a sandbox with external access switched off:
if call_name == "duckdb_query":
query = args.get("query", "")
if query:
con = duckdb.connect(database=":memory:",
config={"enable_external_access": False})
con.register("t", df.head(0))
try:
con.execute(f"EXPLAIN {query}") # parse + bind, never run
except Exception as exc:
actual_cols = ", ".join(str(c) for c in df.columns)
raise ValueError(
f"SQL references unknown columns or has a syntax error. "
f"Table 't' has columns: [{actual_cols}]. Error: {exc}"
) from exc
EXPLAIN binds the query against the real (empty) schema without executing it, so a reference to a column that does not exist fails here, cheaply, before any data is touched. And notice the error message: it hands back the actual column list — the input to the next step, not a note for the human. The same isolation covers the real run, not just this check: when a validated query finally executes, it runs in an in-memory DuckDB with enable_external_access=False as well, so arbitrary SQL cannot read a file, reach the network, or ATTACH its way out of the loaded dataframe.
This check catches a column that does not exist. It cannot catch a column that exists but is the wrong one. If the model asks for net_revenue when the question was about revenue, both columns are real, EXPLAIN binds happily, and the call runs. Schema validation is a guard against invented columns, not against plausible-but-wrong ones. That second, harder failure is caught downstream, by the judge, and only on sampled answers. We come back to it below.
The loop: detect, repair, drop, report
Validation on its own only tells you something broke. What happens next is the design, and the order of the four steps is the whole point. Here is the loop, simplified, returning both the valid calls and a list of notes:
valid, problems = validate(calls, df)
# Record every call that failed, keyed by a stable id, not by tool name:
# two duckdb_query calls can fail independently, and keying by name would
# let one overwrite the other's error. The caller still sees both.
dropped = {p["id"]: p for p in problems}
substitutions = []
attempts = 0
while problems and attempts < max_repair_attempts:
attempts += 1
# repair() must return each call with its original id, or the pop below
# never matches and a fixed call is still reported as dropped.
repaired = repair(problems) # hand the model back its own error
repaired_valid, problems = validate(repaired, df) # check again
for call in repaired_valid:
original = dropped.pop(call.id, None) # this exact call is now valid
if original: # repair may have swapped a
substitutions += changed_columns(original, call) # column in place
for p in problems:
dropped[p["id"]] = p # still broken after repair
valid.extend(repaired_valid)
# A call the model chooses to drop during repair never returns in
# repaired_valid, so its entry stays in `dropped` with its original error:
# a silent drop is still reported.
notes = [f"Dropped tool call '{p['name']}' after validation failed: {p['error']}"
for p in dropped.values()]
notes += substitutions # ...and so is every column swap
return valid, notes
Detect is validation against the live dataframe. Repair hands the model back its own invalid call plus the exact error ("column X not in dataset; the table has columns A, B, C") and the real schema, and asks it to fix the call or drop it. Then the result is validated again. The loop is bounded by a configurable number of repair attempts (default 1), because an unbounded repair loop is just a slower way to hang.
Repair is the one place the model is handed the real column list and told to make the call fit. That is deliberate — it lets the model recover a genuine typo — but it also means the model can remap a missing revenue onto a real net_revenue, and re-validation will pass it, because that column exists. Repair does not protect against a plausible-but-wrong column; it can introduce one. So repair reports what it changed: whenever it alters an argument in place, the response carries a note — "Repaired tool call 'duckdb_query': column 'revenue' → 'net_revenue'" — because a substitution that runs is the riskiest thing the loop does, more dangerous than a drop that doesn't. What repair guarantees is still narrow: nothing runs that references a column the dataset does not have.
Drop is the hard step: a call that cannot be made valid is thrown away rather than forced onto the nearest column that parses. It never runs.
Report is the step most systems skip. Every dropped call becomes a note on the response: "Dropped tool call 'trend_analysis' after validation failed: date_col not in dataset." So does every repair that changed a column in place. The caller finds out what the agent refused to do, what it quietly rewrote, and why. A system that silently discards or silently substitutes will be caught at the worst possible time; one that reports both has told the truth about the edge of its own ability, which is what trust is built on.
Measuring groundedness, including the failures
Refusing to run on invented columns stops the obvious disaster. It does not, by itself, tell you whether the answers the agent does produce are grounded in the data it looked at. For that you measure, and you measure the failures with the same seriousness as the successes.
This is the layer that can catch the failure schema validation and repair both let through: the real-but-wrong column. It can only catch it because it is given more than the answer. A configurable fraction of synthesised answers is scored by a second pass of the model acting as a judge. A few specifics matter, because an under-specified judge is just another unexamined number:
- What it scores against. The judge sees the question, the plan (the tool calls and their column arguments), the answer, and the exact evidence the answer was built from — the
dataset_contextand thetool_resultsreturned to the synthesiser — not the raw dataframe. It scores whether every claim is traceable to that evidence (groundedness), whether the numbers match it (accuracy), whether it addresses the question (completeness), and whether the columns the plan used are the ones the question asked about (column fidelity). It returns the specific sentences it could not support. Column fidelity is the criterion that reaches the real-but-wrong column: when the model repairsrevenuetonet_revenue, the tool returns net-revenue figures and the answer reports them faithfully, so groundedness and accuracy both pass — every claim traces, every number matches. Only comparing the plan against the question exposes that the answer measured the wrong thing. - Which model. It is the same model as the planner and synthesiser, re-prompted as a strict fact-checker, not a separate, stronger referee. That keeps the judge cheap and local, but it is a real limitation: a model that fabricated a claim — or chose the wrong column — may not reliably flag it, which is why "can catch" is the honest verb. The scores are not yet calibrated against human labels, so treat them as a drift signal, not ground truth. Answers scored at or below
3are routed into a review queue. - That it is a signal, not a gate. A failed judge call never blocks an answer. Every answer carries a status, and the set of statuses is the honest accounting:
judged,not_sampled,rule_based,llm_disabled, andfailed. An answer produced without an LLM is markedrule_based, not silently counted as grounded; a judge call that errored isfailed, not dropped from the denominator.
Here is what one window of live traffic actually looked like — the 513 answers judged between 18 June and 3 August 2026, every answer judged because the sample rate ships at 1.0:
| Metric (18 Jun – 3 Aug 2026, live traffic) | Value |
|---|---|
| Answers judged for groundedness | 513 |
| Mean overall score (1–5) | 4.6 |
| Scored ≥ 4 | 93% (479/513) |
| Scored ≤ 3 (routed to the review queue) | 7% (34/513) |
| Scored ≤ 2 | 2% (10/513) |
| Answers with zero unsupported claims flagged | 81% (417/513) |
| Retrieval recall @1 / @3 / @5 (12-query set) | 1.0 / 1.0 / 1.0 |
These are judge scores on live answers: they measure agreement with the evidence, not correctness against the world, and the calibration caveat above still applies. Two numbers that belong in this table are missing from it. The repair-versus-drop rate and the planner fallback rate are kept in process memory, not persisted, so the endpoints below report them live but there is no standing figure to print. That is a real gap: the repair-versus-drop rate measures the exact loop this article is built around, and it ought to be persisted alongside the judge scores. The full set of gauges:
| Endpoint | What it reports |
|---|---|
GET /health/llm-judge |
Groundedness scores and status breakdown |
GET /health/llm-repair |
How often tool calls were repaired vs. dropped |
GET /health/rag-eval |
Retrieval recall and precision at k on a labelled set |
GET /health/planner/fallback-rate |
How often the planner fell back to rules |
GET /health/latency |
Planning and tool-execution latency |
GET /health/llm |
Per-call latency, token usage, and error rate |
You cannot improve what you cannot see. The instrumentation is what lets the system get better instead of slowly, invisibly worse.
Degrading toward honesty, not toward a guess
What does the agent do when there is no model at all? Key expired, budget gone, endpoint down. The default config ships llm_enabled = False, so this is not an edge case; it is the baseline the system is designed to run in. The planning, repair and judging machinery this article describes is opt-in, off by default: the default deployment is the rules-only floor, and the LLM layer switches on above it. The floor is the thing that must never fail, so it is what runs unless a model has been deliberately provisioned.
With no LLM, the planner falls back to keyword routing over the same registry: ask for a profile and you get profile_dataset, ask about correlation and you get correlation_analysis. When nothing matches, it does not grab the nearest tool and hope. It records the miss and returns a clarifying question. The floor never drops out, and it never drops out into a confident invention.
Configuration
None of this is hard-coded behaviour. It is configuration, with conservative defaults:
| Setting | Default | What it controls |
|---|---|---|
llm_enabled |
False |
Whether LLM planning runs at all |
llm_model |
Qwen/Qwen3-32B |
The planning/synthesis model (any OpenAI-compatible endpoint) |
llm_max_repair_attempts |
1 |
Bounded repair round-trips before a call is dropped |
llm_judge_sample_rate |
1.0 |
Fraction of answers scored for groundedness |
llm_json_plan |
True |
Force strict JSON for plan and repair |
The one default that looks odd deserves a word: llm_judge_sample_rate ships at 1.0, which judges every answer even though judging costs a model call. At current volume that is affordable, and judging everything is the right default while the scores are still being watched rather than trusted — you want the full picture before you start throwing some of it away. The knob exists precisely so the rate comes down as volume climbs: dial it to a sample under load, loosen or tighten the repair budget, swap the model. The behaviour is tunable because it was built as a system, not a demo.
Takeaways
Strip away the specifics and a handful of transferable commitments remain.
- Close the action space. A planner choosing from a known registry is testable, auditable, and something you can reason about. A model improvising tools is none of those.
- Validate every model-proposed action against reality before it runs. For analytics that means columns against the live schema, and a sandboxed
EXPLAINto judge SQL rather than a regex. Know its limit: this catches invented columns, not real-but-wrong ones. - Make the loop honest: detect, repair, drop, report. Bound the repair, make the drop real, and report both the drops and the column substitutions repair makes — the swap that runs is riskier than the call that doesn't.
- Measure groundedness, including the failures. Give every answer a status, show real numbers rather than a list of endpoints, and give the judge the question and the plan so it can check the answer measured the right thing, not just that it added up.
- Degrade toward honesty. No model means rules and a clarifying question, never a confident guess.
Put a language model behind an interface, hold it to the truth of the data at every step, and let it say plainly when it cannot do what was asked. The result is rarer than a clever demo: a tool a careful user can actually trust.