Text2SQL with LLMs: End-to-End Engineering for Credit Risk Analytics

    Large language models make natural-language data querying feasible, but production-grade Text2SQL requires more than a single prompt. This article presents a platform-agnostic, end-to-end engineering approach for credit risk analytics. It reviews the main paradigms—single-prompt SQL generation, schema retrieval augmentation, multi-step agent workflows, and fine-tuning with retrieval—and analyzes requirements such as strict metric definitions, complex joins, permissions, and post-query calculations. It then breaks down a seven-stage workflow: intent normalization, schema retrieval, SQL generation, validation and repair, sandboxed Python computation, result explanation, and conversational memory. It also covers evaluation datasets, fallbacks, caching, observability, permission isolation, and practical optimization directions, providing a reusable blueprint for building reliable Text2SQL systems beyond a simple demo.

    1. Background: Why Text2SQL Deserves End-to-End Reproduction

    Before large language models matured, converting natural language into structured query language mainly relied on rule templates and semantic parsers. Such approaches had limited coverage and high maintenance costs. LLMs have made it possible to query data directly in natural language, but deploying this capability in real business scenarios—such as banking credit risk control—requires far more than a single prompt call.

    Real query requests often involve multi-table joins, complex filters, validation of metric definitions, and secondary calculations on results. A production-ready Text2SQL solution must therefore combine SQL generation with code execution, result validation, and other steps in a complete workflow.

    This article uses an agent orchestration platform as a demonstration context. The platform itself is not important, and the design can be transferred to any system that supports workflow orchestration. Using credit risk control as a representative scenario, it explains the design of a complete Text2SQL plus Python solution.

    2. Mainstream Text2SQL Paradigms

    2.1 Single-Turn Prompt Generation

    This approach places the database schema and the user question directly into a prompt and asks the model to output SQL. It is simple to implement and has low latency, but it can easily miss table relationships when schemas are complex, and it cannot self-correct. It is suitable for lightweight scenarios with a small number of tables and clearly defined business metrics.

    2.2 Schema Retrieval Augmentation

    This approach first uses vector retrieval or keyword matching to select the tables and fields most relevant to the question from the full database, then injects the selected schema into the prompt for SQL generation. It addresses context pollution caused by overly long schemas and is a mainstream industry practice for large-scale, multi-table environments.

    2.3 Multi-Agent or Multi-Step Workflow

    This approach divides the task into nodes such as intent recognition, schema routing, SQL generation, syntax and execution validation, and result explanation. LLM nodes and Python nodes collaborate to complete the workflow. The result is observable and debuggable, making this a leading best practice for enterprise deployment and the focus of this reproduction.

    2.4 Hybrid Fine-Tuning and Retrieval

    This approach fine-tunes a model on annotated question-SQL pairs and combines it with retrieval augmentation. It is suitable for scenarios with highly concentrated query patterns and strict accuracy requirements, but data annotation and iteration costs are relatively high.

    3. Requirements Analysis for Credit Risk Control

    Typical data query requests in bank risk control include analyzing the distribution of overdue customers within a time window, calculating credit limit utilization by customer segment, and identifying transaction behavior characteristics of customers with specific risk tags. These requests have several important characteristics:

    • Strict metric definitions: Metrics such as overdue rate and migration rate have precise definitions. If generated SQL uses an incorrect definition, the result can mislead risk decisions.
    • Complex multi-table joins: There are many relationships among the customer master table, credit facility table, repayment schedule table, and transaction ledger table.
    • Sensitivity to latency and permissions: Queries involve sensitive customer fields and require field-level permission filtering.
    • Need for secondary calculations: Many metrics cannot be expressed directly in a single SQL query and require Python processing such as ratio calculation, bucketing, or aggregation on the query results.

    A complete solution must therefore include a schema knowledge base, SQL generation and validation, sandboxed Python execution, and result explanation and chart presentation.

    4. Workflow Deep Dive

    An engineered end-to-end process can be designed with the following nodes.

    4.1 Intent Understanding and Preprocessing

    Rewrite and complete the user input, normalizing colloquial expressions into an executable query intent. For example, “Were there many overdue people last month?” can be normalized to “Count the number and percentage of overdue customers in month X of 2024.” At the same time, identify slots such as time range, customer segment, and metrics.

    4.2 Schema Retrieval

    Chunk and vector-index table structures, field descriptions, foreign-key relationships, and documentation for common metric definitions. Retrieve the top-K relevant tables and fields for the question and assemble them into a restricted schema. An example prompt structure is:

    1. You are a senior credit risk data analyst. The relevant table schemas are:
    2. {schema}
    3. Metric definitions:
    4. {metric_docs}
    5. Generate valid SQL only based on the tables above. Do not assume fields that do not exist.

    4.3 SQL Generation

    Require the model to output only SQL, with a brief explanation of the metric definition. Set a relatively low temperature to improve stability. Apply regular-expression extraction to the output so explanatory text is not accidentally executed as SQL.

    4.4 Validation and Error Correction

    • Static validation: Use a SQL parsing library to check syntax and verify that referenced tables and columns exist in the schema.
    • Trial execution validation: Execute the SQL against a read-only replica or with a row limit such as LIMIT. If an error occurs, pass the error message back to the model for one round of self-repair.
    • Safety validation: Prohibit write operations such as DROP, DELETE, and UPDATE, and block sensitive fields that exceed the user’s permissions.

    4.5 Python Computation

    For metrics that SQL cannot express directly, pass the query results—typically JSON or CSV—to a Python sandbox for execution. For example:

    1. def compute(df):
    2. total = df["customer_cnt"].sum()
    3. overdue = df[df["overdue_days"] > 0]["customer_cnt"].sum()
    4. return {
    5. "overdue_rate": round(overdue / total, 4) if total else 0,
    6. "total": int(total),
    7. "overdue": int(overdue),
    8. }

    The sandbox should restrict network access, execution time, and memory to reduce code injection risks.

    4.6 Result Explanation and Presentation

    Convert calculation results into natural-language conclusions and provide chart configurations, such as a bar chart showing overdue rates by customer segment. The explanation node should state the metric definition and time range so business users can review the result.

    4.7 Memory and Multi-Turn Follow-Ups

    Save the query context from the previous turn to support follow-up questions such as “break this down by province.” Conversation memory supplies omitted conditions, and the completed request re-enters the workflow.

    5. Engineering Practices

    • Evaluation dataset construction: Derive question-SQL-expected result triples from historical data request tickets, and run periodic regression tests on accuracy and execution success rate.
    • Failure fallback: When SQL generation fails or result confidence is low, clearly inform the user and route the request to a human reviewer so incorrect data does not enter the decision chain.
    • Caching and cost control: Cache query results for identical questions, and use the retrieval node to reduce unnecessary token consumption.
    • Observability: Log the input, output, and latency of each node to determine whether an issue comes from inaccurate retrieval or generation drift.
    • Permission isolation: Filter the visible schema according to user roles so generated SQL is inherently within permission boundaries.

    6. Optimization Directions

    1. Continuously operate the metric knowledge base: Capture corrections made by business users as metric definition documentation, forming a data flywheel.
    2. Use execution feedback for improvement: Leverage signals such as whether execution fails or result row counts are abnormal to optimize prompting strategies.
    3. Decompose complex queries: Split long, difficult questions into sub-questions, query them separately, and merge the results to improve stability in multi-table scenarios.
    4. Expand toward NL2API: In addition to Text2SQL, route high-frequency fixed reports to predefined APIs to reduce LLM uncertainty.

    7. Conclusion

    The value of Text2SQL is not the demo effect of “generating SQL from a single prompt.” It lies in connecting intent understanding, schema retrieval, generation validation, sandboxed computation, and result explanation into a controlled, observable, and evaluable pipeline. Using a scenario with strict metric definitions and strict permissions, such as credit risk control, as a testbed for end-to-end reproduction provides a methodology that can be transferred to operations analysis, financial reporting, operational data retrieval, and other domains. Start with a minimal closed loop: first make single-table queries and execution validation work, then gradually introduce retrieval augmentation and Python computation, and finally build an evaluation system and metric knowledge base tailored to your own business.