A Natural-Language Data Analyst That Queries SQL, Plots Charts, and Sanitizes Its Own Output
Natural-language SQL agents are easy to prototype and dangerous to deploy. This architecture addresses the two failure modes that block production use: destructive queries and accidental PII exposure. The three-layer security model and mandatory audit trail are directly portable to any internal analytics tool that lets non-technical users query a database.
A LangChain agent backed by GPT-4o reads a condensed database schema, generates SELECT-only SQL, and executes it against SQLite. A second tool produces matplotlib charts from query results. The pipeline runs inside a three-layer security fence: prompt-level rules, tool-level keyword blocking, and output-level sanitization that masks phone numbers, emails, and ID numbers.
An audit logger records every query with a risk score, flagging unlimited queries that lack a LIMIT clause as medium risk. The reporting layer converts raw results into structured markdown with statistical summaries, trend analysis, and actionable recommendations, enforcing a rule that every claim must cite a specific number rather than vague directional language.
The full agent wraps execution, sanitization, and auditing into a single `analyze()` call, making it straightforward to embed in a Streamlit frontend or an internal analytics bot.
Schema condensation is a cheap, high-leverage optimization. Dropping sample rows and keeping only column names and types cuts token usage dramatically without measurably degrading SQL accuracy for most analytical queries.
The risk-scoring heuristic that flags any query without LIMIT or COUNT as medium risk is a practical, low-effort guardrail against accidental full-table scans that could spike database load or leak large datasets.
Wrapping the entire agent lifecycle — execution, sanitization, audit — into a single method call reduces the surface area for mistakes when integrating into a frontend. The caller doesn't need to remember to sanitize or log separately.