End-to-End Text2SQL with LLMs: A Practical Engineering Guide

    This article presents an end-to-end approach to building LLM-driven Text2SQL systems, using credit risk analytics as the business context. It compares five common technical paradigms—prompt engineering, retrieval-augmented generation, semantic layer abstraction, multi-agent collaboration, and hybrid design—and explains how to choose among them. It then breaks down a seven-stage workflow covering intent recognition, semantic binding, table retrieval, query generation, static validation, execution, and explanation, with illustrative pseudocode. Readers will find practical guidance on context construction, retry strategies, security controls, observability, and evaluation, along with Python-side post-processing and visualization techniques for reliable production deployment.

    1. Introduction: Why End-to-End Reproduction Is Worth the Effort

    In enterprise data environments, the path from a business user’s natural language question to an automatically generated executable query and its results is critical for improving data consumption efficiency. Early solutions relied on rule-based templates and fixed reports, which offered limited coverage and high maintenance costs. With the arrival of large language models, semantic understanding and generation capabilities improved significantly. However, a clear gap remains between “working in a demo” and “running in production.” Using credit risk control as the business background, this article focuses on end-to-end reproduction, aiming to turn scattered techniques into reusable engineering methods.

    Note upfront: the workflow platforms mentioned here refer to general capabilities—such as visual orchestration, conditional branching, variable passing, and plugin invocation—and do not point to any specific product. The example code is illustrative pseudocode, meant to explain structure rather than serve as directly runnable interfaces.

    2. Comparison and Selection of Mainstream Technical Paradigms

    Current industry solutions can be grouped into five categories:

    1. Direct generation via prompt engineering: Write table structures into the prompt and ask the model to produce query statements directly. This is the fastest to implement, but accuracy drops noticeably with wide tables and multi-table joins.
    2. Retrieval-augmented generation (RAG): First vectorize tables and fields for retrieval, recall relevant fragments, then generate. Suitable for scenarios with large numbers of tables and broadly distributed questions, at the cost of a longer pipeline.
    3. Semantic layer abstraction: Define metrics, dimensions, and calculation logic on top of physical tables, so the model generates against semantic objects only. This offers the best maintainability but requires higher upfront modeling effort.
    4. Multi-agent collaboration: Split roles such as “understand—plan—generate—validate—explain” to constrain one another. Stability improves, but latency and cost increase.
    5. Hybrid paradigm: The semantic layer handles consistent definitions, retrieval handles table selection, and a validation agent provides a safety net. This usually delivers the best overall results and is the route adopted in this article.

    Selection guidance: when there are few tables and definitions are stable, prioritize prompt engineering; when definitions are complex and the audience is non-technical, a semantic layer is almost mandatory; when the data asset scale is large, a retrieval stage must be introduced to control context length.

    3. Business Requirements Analysis: The Credit Risk Scenario

    Typical risk-control analysis requests include: changes in the overdue rate for a customer segment over the past thirty days, comparison of application approval rates across channels, and the bad-debt contribution within a given score range. Such questions share three common difficulties.

    First, definition ambiguity. “Overdue” may mean the number of overdue days exceeds a threshold, or it may refer to a status field flag; “bad debt” has multiple definitions. Without unification, the model may generate a statement that is syntactically correct but business-incorrect.

    Second, fuzzy time semantics. Terms like “recently,” “in the past week,” and “month-over-month” must be mapped to specific date ranges and comparison methods, involving time zone and statistical period conventions.

    Third, permission and compliance constraints. Risk-control data is sensitive, so row-level and column-level permissions must take effect at the query layer rather than relying on front-end filtering.

    Therefore, what the requirements side must deliver is not a single query statement, but a query-result pipeline that is “explainable, verifiable, and auditable.”

    4. Deep Dive into the End-to-End Workflow

    The overall pipeline can be divided into seven nodes, orchestrated serially with conditional branches:

    1. Intent recognition: Determine whether the question is a query, comparison, trend, or attribution request, and output a structured intent object.
    2. Entity and definition binding: Map business terms in the question to semantic layer metrics and dimensions; trigger a clarification follow-up if anything is missing.
    3. Table and field retrieval: Recall candidate tables based on semantic similarity, limited to a small set of highly relevant objects.
    4. Query statement generation: Combine semantic definitions with a few examples to produce the target query language statement.
    5. Static validation: Parse syntax, check the existence of table and field names, and inject mandatory filter conditions.
    6. Execution and result handling: Call the query capability to fetch data, and retry with error information on failure.
    7. Explanation and visualization: Generate a summary of conclusions, and choose a chart or table based on the data type.

    Illustrative pseudocode (for structural explanation):

    1. def run_pipeline(question, session):
    2. intent = recognize_intent(question)
    3. if intent.type == "clarify":
    4. return ask_back(intent.missing_slots)
    5. entities = bind_semantics(intent, session.semantic_layer)
    6. candidates = retrieve_tables(entities, top_k=5)
    7. sql = generate_sql(intent, entities, candidates, examples=session.examples)
    8. checked = validate(sql, schema=candidates, inject_row_filter=session.acl)
    9. if not checked.ok:
    10. sql = repair(sql, checked.errors, retry=2)
    11. checked = validate(sql, schema=candidates, inject_row_filter=session.acl)
    12. rows = execute(sql, timeout_ms=8000)
    13. return summarize(rows, chart=choose_chart(rows))

    5. Key Engineering Considerations

    Context construction. Do not stuff all table structures into the prompt. Organize it as “semantic metric definitions + recalled fields + three examples” to control length while improving hit rate.

    Failure retry strategy. Distinguish among parse errors, nonexistent fields, and execution timeouts: for the first two, return the specific error so the model can correct it; for the third, degrade directly to sampling or prompt the user to narrow the scope.

    Security protection. Consolidate control at the query side: prohibit multiple statements and dangerous operations, enforce tenant and permission filters, and set upper limits on result rows and scan volume.

    Observability. Record the intent, recalled objects, generated statement, validation conclusion, and elapsed time for each session, forming a traceable sample set for later evaluation and prompt iteration.

    Evaluation system. Build a labeled set covering simple queries, multi-table joins, fuzzy time, and unanswerable questions, and separately track execution success rate and definition correctness rate, rather than only checking “whether it can produce a result.”

    6. Python-Side Implementation and Result Enhancement

    The Python side mainly handles three responsibilities: first, calling orchestration interfaces to chain nodes together; second, performing local validation and result post-processing, such as empty-result detection, unit normalization, and anomaly labeling; third, rendering output by converting table data into conclusion points and chart configurations. Example:

    1. result = pipeline.run(question, session=ctx)
    2. if not result.rows:
    3. return "No data under the current conditions. Consider widening the time range or adjusting the customer segment."
    4. metrics = normalize(result.rows, unit=ctx.preferred_unit)
    5. return build_answer(metrics, chart=auto_chart(metrics))

    Result enhancement noticeably improves usability: providing the data time range, definition notes, and sample size helps business users judge the credibility of conclusions; for comparison questions, automatically adding the difference and rate of change.

    7. Common Pitfalls and Optimization Directions

    First, definition drift: as the business changes, the semantic layer must be updated accordingly, so establishing a change review process is recommended. Second, insufficient long-tail coverage: failed online samples should be fed back into the example library. Third, latency fluctuation: cache results for high-frequency questions and set expiration policies. Fourth, rising costs: track consumption per node and compress redundant context. Fifth, permission bypass risk: always enforce constraints at the query execution layer rather than the prompt layer.

    8. Conclusion

    The core of end-to-end reproduction lies not in getting the model to “write a single query,” but in building a complete pipeline with unified semantics, precise retrieval, closed-loop validation, and observability and evaluation. A hybrid paradigm with the semantic layer as the backbone, retrieval as the entry point, validation as the safety net, and evaluation as the driver—combined with Python-side post-processing and visualization enhancements—is what enables natural language data Q&A to run stably and keep evolving in real business settings.