AI and LLMs / case study
Text2SQL Agent
A local-first, execution-guided Text-to-SQL agent, QLoRA fine-tuning pipeline, and empirical ablation harness benchmarked on BIRD Dev (SQLite).
- Python
- Qwen2.5-Coder-7B
- Ollama
- QLoRA
- BIRD
- SQLite
- 8,954
- ChatML examples exported for QLoRA
- BIRD train.json + train_tables.json, raw DDL
- 5
- candidate queries generated per question
- 1 greedy at temp 0.0, 4 sampled at temp 0.7
- 0.6
- voting agreement that triggers cloud escalation
- cascade_conf_threshold in Text2SQLAgent.answer()
- 36/36
- unit tests passing
- python -m pytest -q
Built around Qwen2.5-Coder-7B served locally via Ollama, the project systematically evaluates inference-time scaling (hybrid schema linking, execution-guided repair, parallel result-set voting, and live confidence-based cloud cascading) against 1-epoch QLoRA fine-tuning, with paired statistical significance testing, held-out validation, and an automated 100-failure error taxonomy.
Benchmark scope: all empirical results are evaluated on BIRD Dev (SQLite). PostgreSQL execution is implemented in t2s/db.py but untested; Spider is not evaluated.
Core engineering components
- Read-only safety layer (t2s/db.py, t2s/safety.py): enforces SELECT-only queries, table allowlists, 100,000 row caps, 30s timeouts, and optional PII column masking.
- Hybrid schema linking with a decoupled pruner (t2s/linking.py, t2s/retrieval.py): fuses BM25 and dense embeddings via Reciprocal Rank Fusion (RRF), prunes columns with a configurable llm.pruner_model so JSON pruning is decoupled from SQL generation, and expands foreign-key join paths.
- Parallel candidate generation (t2s/generate.py): runs Candidate 0 greedily (direct, temp=0.0) and Candidates 1-4 across direct/cot/decompose (temp=0.7) concurrently via ThreadPoolExecutor(max_workers=min(n, 4)) with deterministic ordering.
- Execution-guided repair and voting (t2s/repair.py, t2s/select.py): repairs syntax errors, runtime errors and empty result sets (up to 2 iterations), clusters candidates by identical execution results, and outputs the winning cluster's agreement fraction as a confidence signal.
- Live confidence cascade (t2s/agent.py): wired directly into Text2SQLAgent.answer() with cascade_conf_threshold=0.6 to escalate low-agreement or failed local queries to openai/gpt-oss-120b on Groq.
- QLoRA fine-tuning pipeline (bench/export_sft.py): exports 8,954 ChatML examples directly from BIRD train.json + train_tables.json (raw DDL) for 4-bit QLoRA (r=16, alpha=32) via Unsloth, then a 16-bit merge and a Q4_K_M GGUF in Ollama.
- Test suite (tests/): 36/36 unit tests passing, covering safety validation, schema linking, API end-to-end behaviour, parallel candidate ordering and usage aggregation, and live cascade escalation and skipping.
Why the safety layer comes first
A Text-to-SQL agent runs model-written SQL against a real database, so the boundary is enforced outside the prompt rather than trusted to it. Every generated statement has to clear the same validator before it reaches the executor, which keeps a bad generation from turning into a write, an unbounded scan, or a leak of masked columns.
Schema linking without a monolithic prompt
The pruner decides which columns are in play before the generator ever writes SQL. Keeping that as its own model call means the pruning output can be scored, swapped and ablated independently of the generator, and it keeps a large schema from crowding the generation prompt.
Retrieval pipeline, in order
question
-> BM25 candidates + dense embedding candidates
-> Reciprocal Rank Fusion
-> llm.pruner_model keeps the columns that matter
-> foreign-key join-path expansion
-> pruned schema handed to candidate generationCandidates, repair, then vote
Diversity comes from decoding strategy rather than temperature alone: one direct greedy candidate anchors quality, while direct, chain-of-thought and decomposition prompts run concurrently at temperature 0.7. Results that fail or return nothing are repaired and re-executed, then candidates are grouped by the rows they actually produce. Agreement across independently generated queries is a cheap, model-free confidence estimate, and it is the signal the cascade reads.
Evaluation protocol
- Inference-time scaling is compared against 1-epoch QLoRA fine-tuning on the same benchmark.
- Paired statistical significance testing, held-out validation, and an automated 100-failure error taxonomy keep the comparison honest.
- Every reported number is BIRD Dev on SQLite; PostgreSQL support exists in t2s/db.py but is untested, and Spider is out of scope.