Text2SQL with LLMs: An End-to-End Engineering Practice Guide
This article walks through an end-to-end approach to building LLM-driven Text2SQL systems for production use. It explains why single-query demos fall short, compares four mainstream technical paradigms, and uses credit risk control as a concrete business scenario. The core of the article is a seven-stage workflow covering intent recognition, semantic retrieval, context assembly, query generation, static validation, execution with adaptive retry, and result processing. It closes with key engineering practices, common failure modes, and optimization directions for teams that want a repeatable, observable, and governable Text2SQL pipeline.
1. Why End-to-End Text2SQL Is Still Hard
Turning natural language into a structured query looks like a translation problem, but in real business settings it is a long chain that spans semantic understanding, schema matching, constraint satisfaction, and result trustworthiness. Demo-grade implementations usually cover only single-table, unambiguous, read-only queries, while production environments must handle multi-table joins, inconsistent metric definitions, permission isolation, slow queries, and secondary computation on results. The value of an end-to-end reproduction therefore lies not in getting one query to run, but in establishing a repeatable, observable, and governable engineering loop.
2. Mainstream Paradigms and Their Trade-offs
Common industry approaches fall into four categories. The first is pure prompt engineering, which writes the database schema into the context and lets the model produce the query directly. It is fast to integrate, but once the schema grows it exceeds the context window and tends to hallucinate fields. The second is retrieval augmentation, which vectorizes tables and fields for recall and injects only relevant fragments into the context, balancing scale and accuracy. The third is a semantic layer or metric layer abstraction, which wraps physical tables as business entities and measures; the model generates a constrained intermediate expression that an engine then translates into a query, giving the best consistency in metric definitions. The fourth is an agent-style multi-step flow that chains intent clarification, candidate generation, execution validation, and failure retry into a closed loop. In practice, teams usually combine retrieval augmentation, semantic constraints, and multi-step validation.
3. Scenario Breakdown: Credit Risk Control
Take credit risk control as an example. Analysis needs typically revolve around metrics such as overdue rate, credit approval rate, limit distribution, customer segmentation, and channel conversion. This scenario has three distinct characteristics: metric definitions are strict, and the same “overdue” status may have multiple aging definitions; data is scattered across multiple fact tables for application, approval, disbursement, and repayment; and analytical conclusions must be traceable to specific customer groups. This means the system cannot output only a query statement; it must also output definition notes and a verifiable result set.
4. End-to-End Workflow in Depth
A robust flow can be split into seven nodes. Node one is intent recognition and slot extraction, clarifying the metric, time range, dimensions, and filter conditions. Node two is semantic retrieval, recalling relevant tables, fields, and historically similar questions. Node three is context assembly, injecting a schema summary, a definition dictionary, and few-shot examples. Node four is query generation, requiring the model to output both the statement and an explanation. Node five is static validation, checking whether tables and fields exist, whether the query is read-only, and whether it stays within a scan-volume threshold. Node six is execution with adaptive retry, feeding error messages back for correction on failure. Node seven is result processing, where a code execution node computes ratios, year-over-year and period-over-period comparisons, and prepares data for visualization.
A schematic orchestration looks like this:
def run(question, ctx):slots = extract_slots(question)schema = retrieve_schema(slots, top_k=5)sql = generate_sql(question, schema, ctx.examples)check = validate(sql, readonly=True, max_scan_mb=512)if not check.ok:sql = repair(sql, check.error)df = execute(sql)return summarize(df, slots)
5. Key Engineering Practices
First, build the semantic layer first. Capture metric definitions in a configurable dictionary so the model does not invent its own. Second, retrieval quality sets the ceiling, so table and field descriptions must clearly state business meaning, enumerated values, and join keys. Third, security boundaries are non-negotiable: least-privilege accounts, enforced pagination, scan-volume limits, and timeout control are all required. Fourth, observability must be built in early, recording retrieval hits, generation latency, validation failure reasons, and retry counts to form an evaluation set for continuous regression. Fifth, deliver result trustworthiness through a three-part package of statement explanation, definition references, and sample row previews so business users can verify results.
6. Common Failure Modes and Optimization Directions
Frequent problems include field hallucination, time-granularity mismatch, wrong join keys that cause Cartesian explosion, and inconsistent aggregation levels. Corresponding optimizations are: build templates with parameterized slots for high-frequency questions; ask a clarifying question first for vague requests; introduce an execution feedback loop for a limited number of self-repairs; and turn stable conclusions into reusable query assets. Combined with relevant general capabilities from Baidu AI Cloud, the workflow can run on a container platform, evaluation sets can be stored in object storage, and log and monitoring services with alerting can track pipeline quality, upgrading a one-off demo into a system that keeps iterating.
