# NL-to-SQL Analytics Agent

> A schema-grounded analytics agent that turns plain-English questions into safe, read-only SQL — cost-guarded, PII-aware, and clarifying ambiguity instead of guessing.

- **Category:** Data Analysis & BI
- **Difficulty:** Advanced
- **Setup time:** 40 min
- **Stacks:** Claude, LangGraph, OpenAI
- **Version:** 2.0.0 (updated 2026-06-21)
- **Source:** https://agent-kits.com/kit/nl-to-sql-analyst

## Overview

Question → grounded SQL → validated answer: ask in English, get a correct, explained result backed by real, runnable SQL.

Schema-grounded: it only references tables and columns that exist in the schema it's given, so it can't invent fields or join nonexistent keys.

Safe by construction: read-only, cost- and row-capped, PII-aware, and it refuses writes, DDL, and unbounded scans.

Honest about ambiguity: it states its assumptions and asks one clarifying question when a request could mean materially different things, instead of guessing.

## When to use it

- You want non-analysts to self-serve answers from a database without writing SQL or waiting on the data team.
- You have a reasonably documented schema (or can provide table/column descriptions) for grounding.
- You want every answer backed by inspectable, read-only SQL and an explanation of assumptions.
- You need cost and safety guardrails on a shared analytics database.
- You want a layer that asks for clarification on ambiguous questions instead of returning confidently-wrong numbers.

## When not to use it

- You need write operations, ETL, or schema changes — this agent is strictly read-only by design.
- Your schema is undocumented and inscrutable, so grounding would be unreliable.
- The question requires judgment a query can't answer (causal claims, forecasts) without a human analyst.
- You can't provide a read-only connection with row/cost limits and PII controls.

## Architecture

- **Schema grounding** — Loads the database schema (tables, columns, types, keys, and descriptions) and exposes only it to the model, so generated SQL can reference real objects and nothing else.
- **Question understanding** — Parses the natural-language request into the metric, dimensions, filters, and time range it implies, and detects ambiguity that warrants a clarifying question.
- **SQL generation** — Drafts a single read-only SELECT grounded in the schema, with explicit assumptions (definitions, date ranges, filters) surfaced for the user.
- **Safety & cost gate** — A deterministic gate parses the SQL to reject any write/DDL, enforce a LIMIT, run EXPLAIN/dry-run, and block queries whose estimated cost or rows exceed the budget, plus PII/tenant filters.
- **Execution & validation** — Runs the approved query on a read-only connection within row/cost caps, then sanity-checks the result (row counts, ranges) before it's reported.
- **Answer composition** — Returns a plain-language answer with the key numbers, the exact SQL used, the assumptions encoded, and any caveats so the result is trustworthy and reproducible.
- **Audit & learning** — Logs every question, SQL, cost, and outcome; thumbs-up/down and corrections feed prompt and schema-description improvements over time.

## Files in this bundle

- `system-prompt.md` — the agent's system prompt
- `tools.json` — tool/function definitions the agent expects
- `workflow.md` — step-by-step run loop
- `.env.example` — environment variables to fill in
- `kit.json` — full structured metadata
- `starters/` — minimal starter snippets
- `LICENSE` — Apache-2.0 (code, configuration, and schema)
- `LICENSE-CONTENT` — CC BY 4.0 (specification text and documentation)
- `NOTICE` — attribution and trademark notice
- `run.py` — **runnable demo**: real agent loop with mock tools (`pip install anthropic`, set `ANTHROPIC_API_KEY`, `python run.py`)
- `agentaz.json` / `agentaz.schema.json` — AgentAz™ governance spec + schema

## Implementation notes

- Connect with a least-privilege, read-only database role. Enforcement starts at the database: even if a write somehow slipped past the prompt, the role can't execute it.
- Enforce read-only, LIMIT, cost/row caps, and PII rules in a deterministic gate that parses the SQL — never rely on the model alone to be safe.
- Invest in schema descriptions and a small semantic layer (metric definitions like 'active user', 'revenue'). This is the single biggest driver of accuracy and consistency.
- Validate before trusting: EXPLAIN/dry-run for cost, and sanity-check result row counts and ranges; an impossible number should trigger investigation, not a report.
- Make 'clarify on ambiguity' a first-class behavior. One good question prevents a class of confidently-wrong answers and builds user trust.
- Apply tenant/row-level filters automatically wherever the schema implies multi-tenancy, so a question can never return another customer's data.
- Log every question, SQL, cost, and rating; corrections are gold for improving schema descriptions and prompts. Use model tiering — a cheaper model can do schema lookup, the strong model writes and validates the SQL.

## Variations

- **Basic — Read-only Q&A:** Answers natural-language questions with grounded, read-only SQL, shows the query and assumptions, and enforces row/cost caps. The simplest safe self-serve layer.
- **Advanced — Semantic-layer analyst:** Adds a governed metric/semantic layer (canonical definitions of revenue, active user, etc.), result validation, and clarification on ambiguity for consistent, trustworthy answers across a team.
- **Enterprise — Governed self-serve analytics:** Adds row-level security and tenant isolation, per-role data policies, PII controls, full query audit, cost governance across a warehouse, and feedback-driven tuning of the semantic layer.

## FAQ

**Can it modify or delete data?**

No. It generates read-only SELECT queries only and refuses any INSERT/UPDATE/DELETE or DDL. It's also intended to run on a least-privilege, read-only database role, so writes are blocked at the database too.

**How does it avoid making up tables or columns?**

It's grounded in the schema you provide and may only reference tables and columns that actually exist there. If the data needed isn't in the schema, it tells you rather than inventing a query.

**What stops a runaway, expensive query?**

A deterministic cost gate: every query must be bounded with a LIMIT, it's EXPLAIN/dry-run-checked, and anything whose estimated cost or rows exceed your budget is blocked and narrowed or refused — never run blindly.

**How does it handle ambiguous questions?**

It asks one focused clarifying question instead of guessing. Vague asks like 'best products' (revenue? units? margin? what period?) get a quick question so you get the answer you actually meant.

**How does it protect sensitive data?**

It avoids selecting raw PII columns unless explicitly required and allowed, prefers aggregates and redaction, and applies tenant/row-level filters where the schema implies multi-tenancy so it can't return another customer's data.

**How accurate is it?**

Accuracy depends heavily on schema quality — adding column/table descriptions and a small set of canonical metric definitions is the biggest lever. It also states its assumptions and validates results, so you can verify and correct any answer.


---

© 2026 AgentKits · www.agent-kits.com

**Open source.** Code, configuration, and the AgentAz™ schema are licensed under
**Apache-2.0**; specification text and documentation under **CC BY 4.0** (with
attribution to AgentKits, link to https://www.agent-kits.com). See LICENSE, LICENSE-CONTENT,
and NOTICE in this bundle. "AgentAz" and "AgentKits" are trademarks of AgentKits.

**Flagship reference blueprint.** View the source, AgentAz™ spec, and frozen v1.0 schema
in the public registry: https://github.com/agent-kits/agentaz
Original: https://agent-kits.com/kit/nl-to-sql-analyst
