Text2SQL with LLMs: An End-to-End Engineering Guide
This article walks through an end-to-end approach to building a Text2SQL system powered by large language models. It compares the main technical paradigms, shows how to model business requirements using credit risk analytics as an example, and explains why a semantic layer and metadata quality form the foundation of accuracy. The core of the guide is a seven-node workflow covering intent handling, retrieval, generation, static validation, execution, explanation, and self-correction, followed by notes on coordinating Text2SQL with a code interpreter, an evaluation framework that goes beyond "does it run," deployment and optimization directions, and common pitfalls with practical ways to avoid them.
1. Why End-to-End Text2SQL Has Become an Engineering Focus
Turning natural language into a structured query looks like a translation problem, but in practice it spans four threads at once: semantic understanding, domain knowledge, constraint adherence, and result trustworthiness. Early approaches relied on rule templates and grammar parsing, which offered narrow coverage and high maintenance cost. The field then moved to fine-tuning, which requires labeled corpora and training resources. With large language models, cold starts from zero-shot to few-shot became possible, and the end-to-end pipeline became reproducible as an engineering artifact for the first time.
End-to-end here does not mean handing a sentence to the model and taking back a result. It covers a closed loop: intent recognition and clarification, database and table retrieval with semantic alignment, query generation, static validation, execution, result self-checking, and automatic correction when needed. Accuracy and stability only become controllable when every stage is an observable, rollback-capable node.
2. Mainstream Technical Paradigms and Their Trade-Offs
- Pure prompting: relies on the model’s built-in capability and carefully designed prompt templates. Fast to deliver, and suitable when there are few tables and stable metric definitions. The drawback is insufficient recall when facing hundreds of tables.
- Retrieval-augmented: hybrid vector and keyword retrieval first recalls relevant tables, fields, and historical Q&A samples, then hands them to the model for generation. It substantially mitigates the problem of a schema too long to fit in the context window.
- Semantic layer: metrics, dimensions, definitions, and synonym mappings are built on top of physical tables, so the model faces business semantics rather than raw table structures. This is the key lever for improving accuracy.
- Tool orchestration: query generation is delegated to the model, while complex computation, charts, and statistics go to a code interpreter, forming a combined “query plus compute” capability.
- Multi-round validation: static syntax checks, field existence checks, execution feedback, and self-reflection turn one-shot generation into a convergent iterative process.
In engineering practice, a combination strategy is common: the semantic layer makes sure the query says the right thing, retrieval augmentation makes sure the right tables are found, multi-round validation makes sure nothing goes wrong, and tool orchestration makes sure the math is correct.
3. Modeling Business Requirements: A Credit Risk Example
A typical risk analytics ask is to query metrics such as overdue rates, approval rates, and credit limit distributions in natural language. Such scenarios have three distinct characteristics: strict metric definitions, sensitivity to time windows, and tiered data permissions. Requirement breakdown therefore starts by classifying the question:
- Metric queries: overdue rate, approval rate, average credit limit.
- Grouped comparisons: split by channel, product, customer segment, or account age.
- Time-series trends: rolling performance over the last N days or months.
- Detail and list queries: application records that hit a specific rule.
- Attribution analysis: drilling down into the dimensions behind a metric’s movement.
For each category, the answerable boundary must be defined. The model should not be asked to infer beyond what the data covers; instead it should proactively ask when information is missing, for example the time range, the product definition, or whether revoked applications are included. This directly determines whether the production experience is trustworthy.
4. The Semantic Layer and Metadata: The Foundation of Accuracy
The semantic layer carries at least four kinds of information: physical structure (databases, tables, fields, types, primary and foreign keys), business semantics (metric definitions, dimension hierarchies, enum meanings), retrieval index (natural language descriptions of tables and fields, synonyms, example questions), and permission tags (row-level and column-level visibility).
An illustrative semantic description structure:
metric:name: overdue_rate_30ddescription: 30+ overdue rate; denominator is the number of loans due for repaymentformula: "count(case when overdue_days >= 30 then 1 end) / count(*)"dimensions: [channel, product, vintage_month]synonyms: ["30-day overdue", "M3+", "overdue 30+"]sensitivity: L2
It is worth stressing that field comment quality often determines the ceiling more than model choice does. Vague comments, missing definitions, and the same metric defined in multiple places are the most common root causes of failure in practice.
5. Workflow Deep Dive: Seven Nodes
- Session and intent node: decide whether the request is a query, chit-chat, or out of scope; extract slots such as time, product, and channel; trigger clarification if any are missing.
- Retrieval node: hybrid recall of relevant tables and fields, plus recall of similar historical questions and their human-confirmed queries to serve as few-shot examples.
- Generation node: output the structured query and require the model to also state its “definition assumptions” for later auditing.
- Static validation node: syntax parsing, field and enum existence checks, interception of dangerous operations (read-only queries only), row count limits, and timeout limits.
- Execution node: run in a read-only replica or a controlled sandbox, returning the result set and execution time.
- Explanation and visualization node: turn results into a conclusion-style answer, and hand off to a code interpreter when year-over-year or period-over-period comparisons, percentile statistics, and chart data preparation are needed.
- Reflection and correction node: if execution errors out or the result is empty, feed the error message back to the model, cap the number of retries, and record the trace of each correction.
Illustrative validation pseudocode:
def guarded_run(sql: str, ctx):assert is_readonly(sql), "Read-only queries only"assert tables_in(sql) <= ctx.allowed_tables, "Unauthorized table access"df = engine.execute(sql, timeout=ctx.timeout, row_limit=ctx.row_limit)if df.empty:raise EmptyResult("Go back to clarification or relax the filters")return df
6. Coordinating Text2SQL with a Code Interpreter
Structured queries are good at fetching data but poor at complex statistics and visualization. Separating data retrieval from computation is an effective way to raise accuracy on complex questions: the model first generates a query to obtain detail or aggregated results, then generates analysis code for weighting, segmentation, trend fitting, and chart data organization. Three things matter when coordinating them: controlling data volume (aggregate first, then transfer), isolating the code sandbox, and maintaining a dependency allowlist. This avoids pushing large result sets back into the context and keeps the analysis reproducible.
7. Evaluation: Do Not Look Only at “Does It Run”
- Execution accuracy: whether the result set matches the ground truth. This is the primary metric.
- Logical equivalence rate: different phrasings with the same semantics require normalized comparison.
- Clarification trigger accuracy: whether it asks when it should, and stays quiet when it should not.
- Refusal and unauthorized-access interception rate: the baseline metrics for security and compliance.
- Latency and cost distribution: focus on the long tail rather than the average.
Build a labeled evaluation set of at least several hundred cases, covering synonym rewrites, vague time expressions, multi-table joins, empty results, and permission-restricted cases, and run a regression after every prompt or semantic layer change.
8. Production Deployment and Optimization Directions
For deployment, stateless workflow nodes can run on a container platform, the semantic layer and evaluation sets can be stored in object storage, a message queue can absorb traffic spikes and support asynchronous long-running tasks, and logging plus monitoring and alerting can provide full-pipeline tracing. If you use the relevant general capabilities from Baidu AI Cloud, the same principles apply: separate compute from storage, keep nodes stateless, and make the whole pipeline observable.
Continuous optimization can proceed along four paths: turn the semantic layer into managed assets by capturing definitions as reusable configuration; improve retrieval quality with reranking and query rewriting; feed failure samples back into the system to build a data flywheel; and apply tiered routing, where simple questions take a lightweight path and complex ones take the multi-round validation path, balancing cost and accuracy.
9. Common Pitfalls and How to Avoid Them
Ambiguous table and field names, inconsistent time definitions, unmapped enum values, missing foreign keys for cross-database joins, permission filters “optimized away” by the model, and overconfidence that leads to answering without clarification. The remedies are not mysterious: express constraints as executable validation rules, expose assumptions explicitly to the user, and record every failure in a structured way.
The essence of reproducing Text2SQL end to end is using engineering constraints to converge the model’s uncertainty into a range the business can accept. The semantic layer sets the ceiling, the validation pipeline sets the floor, and the evaluation system determines iteration speed. Only when all three are in place is the solution truly deliverable.
