An End-to-End Engineering Guide to LLM Text2SQL Systems

    This article explains why reproducing a complete Text2SQL pipeline matters more than optimizing a single model, and walks through the engineering practices needed to make natural language to structured query systems reliable in production. It covers the six stages of a typical pipeline, trade-offs among prompt engineering, fine-tuning, and retrieval-augmented approaches, a credit risk control use case with strict metric and auditability requirements, detailed workflow steps, semantic layer and context governance, evaluation and observability, and common pitfalls with optimization directions.

    1. Why End-to-End Reproduction Matters More Than a Single Model

    In natural language to structured query tasks, early industry attention focused on “whether the model can write a single correct statement.” In real business deployments, however, failures rarely happen at the generation step. They happen in the surrounding stages: context preparation, semantic ambiguity resolution, execution validation, and result explanation. The core of end-to-end reproduction is therefore not replicating a specific model, but replicating a pipeline that is observable, rollback-capable, and evaluable.

    A complete pipeline typically contains six stages: intent recognition and clarification, semantic retrieval and context assembly, query generation, static and dynamic validation, execution and result post-processing, and natural language conclusion output. If any stage is missing, overall accuracy decays quickly under real data distributions.

    2. Trade-offs Among Three Mainstream Technical Paradigms

    2.1 Prompt Engineering Driven

    Zero-shot, few-shot, chain-of-thought, and self-correction strategies are used to guide the model in producing query statements. The advantage is a short turnaround with no training resources required. The drawback is that prompt length grows with schema size, and stability is insufficient for complex multi-table joins. This approach suits scenarios with a limited number of schemas and moderate query complexity.

    A schematic prompt structure can be abstracted as:

    1. [Role constraint] You are a query generator; output only executable statements
    2. [Semantic layer] Business meaning of tables and fields, enum mappings, metric definitions
    3. [Examples] 2-3 question-answer pairs similar to the current intent
    4. [Reasoning requirement] State filter conditions and aggregation granularity first, then the statement
    5. [Prohibitions] Do not stitch across topics; do not assume fields that do not exist

    2.2 Fine-Tuning Driven

    Instruction fine-tuning or multi-task fine-tuning on domain corpora can significantly improve consistency of terminology and metric definitions. In engineering practice, the more common combination is “lightweight fine-tuning + retrieval augmentation” rather than training from scratch. Note that fine-tuning solidifies the schema understanding of a particular version, so regression evaluation is needed after schema changes.

    2.3 Retrieval-Augmented Driven

    Schema fragments, historical question-answer pairs, business documents, and metric definition documents are indexed for retrieval and injected into context on demand. Its value lies in externalizing “memory,” so schema evolution does not require retraining the model. In practice, it is recommended to build hierarchical indexes at the table level, field level, and example level, and to rerank by intent similarity.

    3. Breaking Down Business Requirements: A Credit Risk Control Example

    Data retrieval needs in credit risk control have distinct characteristics: strict metric definitions, sensitivity to time windows, complex sample and label definitions, and results that must be auditable. Typical questions include the distribution of overdue rates by aging bucket, the proportion of bad samples for a customer segment within an observation window, and comparisons of approval rates before and after a strategy adjustment.

    Such requirements impose four hard constraints on the pipeline. First, a single definition per metric: the same metric must not have two algorithms. Second, explicit time semantics: observation period, performance period, and aging must not be confused. Third, reproducibility: the same question must produce the same result across two executions. Fourth, explainability: the actually executed statement and filter conditions must be echoed back so risk analysts can review them.

    4. Deep Dive into the Workflow

    1. Intent and entity extraction: identify four slot types — metric, dimension, time range, and customer segment restriction. When a key slot is missing, proactively ask for clarification instead of guessing.
    2. Semantic layer retrieval: recall relevant tables, fields, enum dictionaries, and definition notes, and trim irrelevant content to control context size.
    3. Query generation: require the model to first output a structured query plan, then render it into a statement, reducing the error rate of directly generating long statements.
    4. Two-layer validation: the static layer checks field existence, type matching, and aggregation legality; the dynamic layer trial-executes at minimal cost on a read-only replica to catch syntax and performance issues.
    5. Failure feedback: structure error messages and feed them back into the model with a limited number of retries to avoid infinite loops.
    6. Result post-processing: handle edge cases such as empty results, oversized result sets, and division by zero, and generate a business-facing natural language summary.

    5. Semantic Layer and Context Governance

    The semantic layer is the foundation of end-to-end stability. Three types of assets are recommended: a metric dictionary (name, definition, dependent fields), dimension and enum mappings (code values and business meanings), and subject-area divisions (application, credit granting, drawdown, repayment). Context assembly should follow the order “subject first, then metric, then field,” which noticeably reduces cross-topic incorrect stitching.

    6. Evaluation and Observability

    The evaluation set should cover five categories: simple single-table, multi-table joins, nested aggregation, time windows, and ambiguous phrasing, and should distinguish two levels: “statement correct” and “result correct.” On the production side, it is recommended to log recalled content, generated statements, validation conclusions, execution time, and failure reasons, forming a traceable call chain. Combined with general observability and logging capabilities from Baidu AI Cloud, pipeline metrics can be connected to unified monitoring and alerting to support continuous iteration.

    7. Common Pitfalls and Optimization Directions

    First, overly long context dilutes key information, so reranking and trimming are needed. Second, over-reliance on examples is harmful when examples drift from the real distribution. Third, lacking read-only and rate-limiting protection means trial execution may create resource pressure. Fourth, neglecting schema change management requires a versioned semantic layer and regression baselines. The overall direction is: make the semantic layer thick, retrieval accurate, validation strict, and evaluation routine.