End-to-End Text2SQL with LLMs: A Production Implementation Guide
This article walks through an end-to-end Text2SQL implementation with large language models, focusing on what it takes to move beyond demo-level SQL generation into production. It covers the four-stage evolution of Text2SQL, three mainstream engineering routes (prompt engineering, fine-tuning, and retrieval augmentation), a detailed seven-step pipeline with pseudocode, and engineering practices for evaluation, context management, caching, security, and observability, using credit risk analytics as the reference scenario.
1. Why End-to-End Reproduction Is Harder Than Single-Shot Generation
The goal of Text2SQL is to translate a natural language question into an executable structured query. Demo-level implementations usually only care about whether the model can produce a statement that looks correct. End-to-end reproduction has to answer a different set of questions: does the generated statement actually run against real tables, do the results match the business definition, is execution safe and controlled, are latency and cost acceptable, and can errors be located and regression-tested. These dimensions determine whether a solution can move from a demo into production.
The problem becomes even harder in credit risk analytics. Questions from risk analysts often look like “which products saw a month-over-month drop in applications over the last three months while approval rates stayed below the threshold.” Such a question implicitly contains a time window, metric definitions, filter conditions, and aggregation logic. Without a metric semantic layer and a business dictionary, the model can only guess, and the results will be unstable. So the core of an end-to-end solution is not making the model better at writing SQL, but engineering business semantics, table structures, and the validation chain together.
2. The Technical Landscape: Four Stages and Their Trade-Offs
Text2SQL has roughly gone through four stages.
The first stage relies on rules and templates. Mapping is done through syntax parsing, slot filling, and query template assembly. It is controllable, explainable, and low in latency, but coverage is narrow and it breaks as soon as phrasing varies.
The second stage is the deep learning model stage. Sequence-to-sequence architectures, combined with schema-aware encoding and intermediate representations, can perform well on specific datasets, but they depend on labeled data and transfer poorly across databases.
The third stage is the pre-trained language model stage. Joint encoding of table structures, column names, and questions, together with techniques such as schema linking and de-serialization, significantly improves generalization to unseen databases. Representative ideas include two-stage multi-task pre-training and relation-aware encoding schemes.
The fourth stage is the large language model stage. With strong semantic understanding and few-shot learning ability, combined with prompt engineering, fine-tuning, and retrieval augmentation, LLMs have become the mainstream choice for engineering deployment. It is worth stressing that LLMs do not replace the first three stages; they reorganize rule validation, retrieval, and evaluation into a single pipeline.
3. Three Mainstream Engineering Routes
3.1 Prompt Engineering
The idea is to guide the model with carefully designed prompts. Common combinations include: zero-shot prompting, which provides only the table structure and the question; few-shot prompting, which attaches a few question-answer examples; chain-of-thought prompting, which asks the model to restate the constraints before writing SQL; and self-correction, where the model performs static checks and rewrites its own output. This route is fast to deploy and requires no training, which makes it suitable for scenarios with relatively stable structures and medium query complexity. The limitation is sensitivity to context length and noise: once there are many tables, the model tends to pick the wrong table or miss filter conditions.
An illustrative prompt structure:
You are a query generation assistant. Use only the given table structures and do not invent fields.Business definition: approval rate = approved applications / total applications.Table structures: {schema}Reference examples: {examples}Requirements: first list the tables and filter conditions used, then output a single query statement.Question: {question}
3.2 Model Fine-Tuning
When domain terminology is dense and query patterns are fixed, you can run instruction fine-tuning or multi-task fine-tuning on domain data to bake definitions and style into the model. Common approaches include instruction fine-tuning, multi-task joint training, and structured adaptation for the query task. This route delivers stable gains but requires high-quality annotations and a continuous iteration mechanism, and it places demands on the base model’s capability.
3.3 Retrieval Augmentation
Retrieval augmentation supplies context so the model does not have to rely on memory. What can be retrieved includes relevant table and column fragments, similar question-query pairs, metric definitions and the business dictionary, and historical queries with multi-turn context. In practice, vector retrieval is usually used first to recall candidates, then rules trim and rerank them, packing the most relevant structural information into a limited context. This is currently the most cost-effective direction and the main focus of this article.
4. Scenario Requirements: Credit Risk Analytics
Typical credit risk analytics requests fall into four categories: application and disbursement funnel analysis, product approval rate and credit limit distribution, overdue and risk metric monitoring, and strategy rule hit and backtesting. Each places different demands on the system: funnel analysis emphasizes time windows and ordering; metric analysis emphasizes consistent definitions; monitoring emphasizes repeatable execution and stable output; backtesting emphasizes traceability and permission isolation.
This leads to four hard requirements. First, semantic accuracy: each metric must have a single definition. Second, execution safety: only query operations are allowed. Third, explainability: the system must return the tables used, filter conditions, and definition notes. Fourth, operability: there must be an evaluation set, regression testing, and monitoring with alerts.
5. Breaking Down the End-to-End Workflow
A reproducible pipeline should contain seven stages.
- Semantic preprocessing: perform entity recognition and time normalization, converting “the last three months” into an explicit range and mapping “high-net-worth customers” to dictionary codes.
- Schema retrieval and pruning: recall relevant tables from the question, drop irrelevant columns, and output a compact structure description to reduce noise.
- Example retrieval: recall similar samples from a historical question-answer library, with definition notes attached, to improve style consistency.
- Query generation: the model outputs in a “constraints first, then SQL” order, sampling multiple times and taking the best result when necessary.
- Static validation: parse the syntax, check that tables and columns exist, verify read-only access, and estimate cost, blocking Cartesian products and full table scans.
- Execution and fallback: run on a read-only replica with a timeout and row limit; on failure, feed the error message back to trigger one round of self-correction.
- Result explanation and presentation: return a result summary, chart suggestions, and definition notes to close the loop.
Illustrative pseudocode:
def text2sql(question, session):facts = normalize(question) # normalize time and entitiesschema = retrieve_schema(facts) # schema retrieval and pruningdemos = retrieve_examples(facts) # example retrievalsql = generate(facts, schema, demos) # generationsql = validate(sql, schema) # syntax/field/read-only validationrows = execute_readonly(sql, timeout=5) # read-only executionreturn summarize(rows, facts) # result explanation
6. Engineering Practices and Optimization Directions
Evaluation first. Build an evaluation set covering simple queries, multi-table joins, nested aggregations, and time windows, and measure execution accuracy and result consistency separately, instead of only judging whether the output “looks right.”
Context governance. Describe table structures in layers, giving the subject domain first and then the fields; summarize overly long structures and expand them on demand to control noise and cost.
Caching and reuse. Cache results and queries for high-frequency questions with an invalidation policy, which significantly reduces latency and call volume.
Security and permissions. Route everything through a read-only account and a view layer, mask sensitive fields with row- and column-level access control, and keep an audit trail of every statement.
Observability. Record recall hit rate, validation rejection rate, correction success rate, and execution time, configure monitoring and alerts, and form a continuous iteration loop.
For deployment, a container platform can host the workflow service, a message queue can handle asynchronous execution and peak shaving, object storage can hold evaluation sets and archived logs, and a logging service with monitoring and alerts can provide full-chain tracing. If an organization already uses relevant general capabilities from Baidu AI Cloud, the same approach can be applied while keeping interfaces and data boundaries clear.
7. Conclusion
The key to end-to-end reproduction is putting the language capability of a large model inside an engineering pipeline that is constrained, verifiable, and observable. Prompt engineering solves cold start, fine-tuning locks in definitions, retrieval augmentation supplies context, and rules plus evaluation hold the baseline. Following the seven stages above is what allows Text2SQL to become a stable source of productivity in real business scenarios such as credit risk analytics.
