Text2SQL (Structured Query Language) method, system, medium and equipment based on large language model and knowledge base
By combining a large language model and a knowledge base, we have achieved a Text2SQL technology with high accuracy and strong versatility, which solves the problems of frequent syntax errors and poor user experience in existing technologies and provides a complete business loop from data query to decision support.
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- BEIJING QIERBULAITE TECH
- Filing Date
- 2026-01-16
- Publication Date
- 2026-04-10
AI Technical Summary
Existing Text2SQL technology is insufficient in terms of accuracy and versatility, and lacks type constraints and intelligent validation mechanisms, resulting in frequent syntax errors and a poor user experience.
Using a method based on a large language model and knowledge base, we generate grammatically correct SQL statements through intent recognition, key information extraction, semantic similarity retrieval, and bidirectional mapping verification, and perform intelligent analysis of the results.
It significantly improved the accuracy of SQL syntax, enhanced the versatility and flexibility of the system, achieved seamless integration from data querying to decision support, and reduced maintenance costs.
Smart Images

Figure CN121833756A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the fields of natural language processing and database query technology, and in particular to a Text2SQL method, system, medium and device based on a large language model and knowledge base. Background Technology
[0002] Text2SQL technology aims to automatically convert natural language queries into SQL statements. Existing technologies mainly fall into two categories: the first is end-to-end generation methods based on large language models, but these are prone to illusions, leading to frequent syntax or logical errors and failing to meet enterprise-level reliability requirements. The second is methods that fine-tune models for specific scenarios, but these have poor versatility, requiring retraining for new datasets and resulting in long adaptation cycles. Furthermore, existing knowledge base retrieval solutions store complete SQL statements; rigid templates cannot flexibly adapt to dynamic parameters, the lack of type constraints leads to high population error rates, and the absence of syntax validity verification and intelligent conflict handling mechanisms results in feedback only after erroneous SQL execution fails, leading to a poor user experience. Therefore, there is an urgent need for a Text2SQL technology solution that combines high accuracy, strong versatility, built-in type constraints, and intelligent verification and correction capabilities. Summary of the Invention
[0003] The purpose of this invention is to provide a Text2SQL method, system, medium, and device based on a large language model and knowledge base, thereby solving the aforementioned problems existing in the prior art.
[0004] To achieve the above objectives, the technical solution adopted by the present invention is as follows:
[0005] A Text2SQL method based on a large language model and knowledge base includes the following steps:
[0006] The large language model is used to identify the intent of the input query and determine whether the question belongs to the data analysis type that requires the generation of SQL. If it does, key information is extracted, including at least one of the following: start and end time, indicator, dimension, vehicle series / brand name, and calculation method.
[0007] A QA knowledge base is built and SQL templates are retrieved based on semantic similarity. The knowledge base stores predefined question-SQL template pairs, where the SQL template contains placeholders for key information to be filled. The extracted key information is used to fill the placeholders and generate executable SQL statements.
[0008] After the SQL execution result is generated, a Prompt message containing the user's question, execution result, and answer requirements is constructed. The execution result is then intelligently analyzed and summarized using a large language model, and a natural language conclusion is returned.
[0009] Preferably, in the intent recognition step, if the question does not belong to the data analysis category that requires SQL generation, the default response template is returned directly, terminating the subsequent SQL generation process.
[0010] Preferably, key information extraction includes at least the following dimensions:
[0011] Time analysis: Based on the current date, analyze the time semantics in the problem. If the dates are the same, the start time is the same. If it is the last N days, then it does not include today and recursively calculates N days.
[0012] Metric identification: Identify which category of predefined metrics the problem belongs to. Predefined metrics include at least one of the following: new energy, push activation, organic traffic, new user volume, old user volume, mini-program user volume, new user volume, CVR, and CTR.
[0013] Entity recognition: Identify the vehicle series and brand name contained in the question; return "none" if not.
[0014] Preferably, the QA knowledge base construction and retrieval process includes:
[0015] In the knowledge base, a placeholder system with type constraints is established for each question-SQL template pair. The placeholders adopt a triple structure of {parameter name: parameter type: validation rule}, where time-type placeholders contain date format validation rules, indicator-type placeholders contain enumeration value range validation rules, and entity-type placeholders contain foreign key association validation rules.
[0016] The query vectors of user questions and knowledge base questions are encoded using BERT or large language models. The initial matching degree is calculated by cosine similarity and weighted by placeholder type matching degree and validation pass rate to obtain a comprehensive similarity score. Recall is triggered when the comprehensive similarity exceeds a dynamic threshold.
[0017] A two-way mapping verification mechanism is established. When the extracted key information is filled into the SQL template placeholders, a mapping link of problem semantic slot → placeholder → SQL syntax tree node is generated synchronously. The syntax validity of the filled SQL is verified by parsing the syntax tree. When a type conflict or syntax error is detected, an LLM-based uncertainty completion and conflict resolution sub-process is started to automatically correct the placeholder mapping relationship or prompt the missing key information.
[0018] Preferably, the specific process of intelligent analysis of the execution results by the large language model is as follows: the prompt word contains the user's question, the SQL execution result, and the answer requirement instruction. The large language model analyzes and summarizes the data trends and anomalies, and generates a natural language answer containing a visual chart description.
[0019] Preferably, the QA knowledge base adopts a placeholder template system with type constraints, combined with a two-way mapping verification mechanism and an uncertain completion sub-process, which makes the SQL syntax accuracy produce unexpected technical effects compared with the end-to-end Prompt method. Moreover, the solution is applicable to different dataset requirements and does not require retraining the model for specific scenarios.
[0020] Preferably, a Text2SQL system based on a large language model and knowledge base includes:
[0021] The input interface is used to receive query questions;
[0022] The processor communicates with the input interface and is configured with an LLM information extraction module, a QA knowledge base construction and recall module, and an LLM intelligent analysis module. When the processor executes a computer program, it implements the method of any one of claims 1-6.
[0023] The memory communicates with the processor and is used to store QA knowledge bases with type-constrained placeholders, SQL templates, and computer programs.
[0024] The output interface communicates with the processor to return natural language conclusions.
[0025] Preferably, the system performs semantic vector encoding through BERT or a large language model, and realizes SQL template recall based on a weighted comprehensive score of cosine similarity, placeholder type matching degree, and verification pass rate. At the same time, it has a built-in bidirectional mapping verification mechanism and an LLM-driven conflict resolution sub-process to complete the conversion from natural language query to executable SQL and intelligent analysis of the results.
[0026] Furthermore, a computer-readable storage medium storing a computer program is characterized in that, when executed by a processor, the computer program implements the aforementioned Text2SQL method based on a large language model and knowledge base.
[0027] Furthermore, an electronic device includes a processor and a memory, the memory storing a computer program that, when executed by the processor, implements the aforementioned Text2SQL method based on a large language model and knowledge base.
[0028] The beneficial effects of this invention are:
[0029] Significantly improved accuracy: Through QA knowledge base template retrieval and information filling mechanisms, the SQL syntax accuracy rate has been increased from less than 70% in traditional methods to nearly 100%, resulting in a significant improvement in execution accuracy and effectively solving the illusion problem of end-to-end methods.
[0030] Enhanced versatility and flexibility: Adopting a configurable knowledge base template architecture, there is no need to retrain the model for new datasets or business scenarios, shortening the adaptation cycle from weeks to hours, significantly reducing maintenance costs.
[0031] Complete business loop: Innovatively introduces an intelligent results analysis module, and a large language model performs trend analysis, anomaly detection and visualization description on query results, directly outputting highly readable natural language conclusions, achieving seamless connection from data query to decision support.
[0032] Robust system architecture: Supports virtualization deployment and hardware integration, adapts to various computing environments through interface design, and possesses scalability and security for enterprise-level applications. Attached Figure Description
[0033] Figure 1 This is an overall flowchart of the method of the present invention;
[0034] Figure 2 This is a system framework diagram of the present invention. Detailed Implementation
[0035] To make the objectives, technical solutions, and advantages of this invention clearer, the invention will be further described in detail below with reference to the accompanying drawings. It should be understood that the specific embodiments described herein are merely illustrative and not intended to limit the invention.
[0036] Reference Figure 1 and Figure 2 This paper presents a Text2SQL method based on a large language model and knowledge base, which includes the following steps:
[0037] S1. Use a large language model to identify the intent of the input query and determine whether the question belongs to the data analysis category that requires SQL generation; if it does, extract key information, including at least one of the following: start and end time, indicator, dimension, vehicle series / brand name, and calculation method.
[0038] Specifically, this step involves the intent recognition and key information extraction stage of this invention. By using a large language model to perform deep semantic understanding on the input natural language query question, it first determines whether the question belongs to the data analysis category that requires generating SQL statements. If the determination is positive, it further extracts five types of key information elements from the question text in a structured manner.
[0039] I. Classification Mechanism of Intent Recognition
[0040] After receiving the user's query, the system immediately invokes a large language model to classify the intent. The model determines whether the question possesses typical characteristics of a data analysis question based on the task instructions. Specifically, it must meet at least two of the following conditions: it includes a clear timeframe description, involves quantifiable business metrics, involves statistical dimension limitations, involves a specific entity (such as a brand or vehicle series), and includes a description of the calculation method.
[0041] If the model determines that the problem does not belong to the data analysis category, the subsequent process will terminate directly, and a preset default response template will be returned. The default template can be a casual response, a knowledge-based question response, or an error message, ensuring that the system does not misinterpret non-data query requests as SQL generation tasks, thereby avoiding invalid calculations and wasted resources. If the problem is determined to be a data analysis category, the subsequent key information extraction module will be activated.
[0042] II. The Five-Dimensional System for Key Information Extraction
[0043] The key information extraction module focuses on five core dimensions, guiding the large language model to accurately extract structured parameters from the question text by constructing targeted prompt words:
[0044] First Dimension: Start and End Time Resolution. The system uses the current session date (e.g., July 30, 2024) as a baseline to resolve the implicit time semantics in the question. If the question is stated as "the last 7 days," it automatically calculates the preceding 7-day period excluding today, with a start date of July 23, 2024, and an end date of July 29, 2024. If the question is stated as "yesterday," both the start and end dates are July 29, 2024. If the question is stated as "this week," it calculates the interval from the start date of this week (Monday) to the current date based on the current week (Thursday). Time resolution supports two modes: relative time (e.g., "the last 30 days," "the last quarter") and absolute time (e.g., "June 1, 2024") described in natural language.
[0045] The second dimension: Metric identification. The system identifies the core business metrics referenced by the question from a predefined metric classification system. The predefined metric library covers keywords from multiple business areas, including but not limited to mini-program user volume, new user volume, returning user volume, new energy vehicle sales, push activation conversion rate, organic traffic, CVR (conversion rate), CTR (click-through rate), etc. The model semantically matches the question text with the metric library and outputs standardized metric names. For example, "What is the week-on-week change in the average daily number of active mini-program users this week?" is identified as the metric "mini-program user volume".
[0046] The third dimension: Dimension determination. Dimension refers to the granularity or perspective of data analysis, such as time dimension (day, week, month), geographical dimension (province, city), channel dimension (online, offline), vehicle type dimension (sedan, SUV), etc. The model identifies the statistical analysis dimension expected by the user by analyzing the grouping words in the question (such as "statistics by region" or "view by channel") or implicit semantics.
[0047] The fourth dimension: Vehicle and brand name recognition. In automotive industry data analysis scenarios, the model is specifically trained to recognize the car brand and vehicle model names mentioned in the question. If the question contains "Xiaomi SU7", the brand name is accurately extracted as "Xiaomi" and the vehicle model name as "SU7". If the question only mentions the brand and not the vehicle model (such as "BYD sales"), the brand field is filled in, and the vehicle model field is marked as "none". If the question does not mention any car entity, both fields return "none". This recognition supports normalization processing for common aliases, abbreviations, and ambiguous expressions.
[0048] Fifth Dimension: Calculation Method Extraction. The calculation method defines the data processing logic, such as "summation", "average", "growth rate", "month-on-month", "year-on-year", "cumulative", etc. The model identifies calculation keywords (such as "week-on-week", "daily average", "cumulative") or implicit calculation intentions in the problem and outputs standardized calculation method identifiers.
[0049] III. Structured Output of Extraction Results
[0050] After the five-dimensional information is extracted, the system integrates and outputs it in a structured JSON format, with each field explicitly assigned a value. For example, for the query "Xiaomi SU7 Mini Program user volume trend in the last 7 days", the output result is: start time is 7 days before the current date, end time is 1 day before the current date, the metric is Mini Program user volume, the brand is Xiaomi, the car series is SU7, the dimension is daily, and the calculation method is trend analysis. This structured data directly drives the subsequent SQL template retrieval and population stages, ensuring the accuracy and consistency of information transmission.
[0051] IV. Error Handling and Robust Design
[0052] The information extraction module is fault-tolerant and self-correcting. When the model confidence level falls below a threshold, the system will proactively ask follow-up questions, requiring the user to clarify ambiguous statements. When the extraction results conflict with the knowledge base metadata (e.g., the identified brand is not in the brand list), an LLM-driven conflict resolution subprocess is triggered, using synonym inference, spelling correction, or valid value hints to ensure the validity and usability of the extraction results.
[0053] S2. Construct a QA knowledge base and recall SQL templates based on semantic similarity. The knowledge base stores predefined question-SQL template pairs, where the SQL template contains placeholders for key information to be filled. Use the extracted key information to fill the placeholders and generate executable SQL statements.
[0054] This step specifically involves the knowledge base construction and template recall and filling process described in this invention. By constructing a structured QA knowledge base to store question-SQL template pairs, and using semantic similarity matching technology to achieve intelligent template recall, the key information extracted in the intent recognition process is used to automatically fill in the template placeholders, ultimately generating syntactically correct and logically complete executable SQL statements.
[0055] I. Construction and Organization of QA Knowledge Base
[0056] The system first constructs a scalable QA knowledge base, which stores a large number of validated query patterns in the form of question-SQL template pairs. Each knowledge base record contains two core parts: a natural language question template and a corresponding structured SQL template. The question template uses a generalized expression approach, abstracting the variable parts into parameterized descriptions. For example, "the trend of Xiaomi SU7 mini-program user volume in the last 7 days" is abstracted into "the trend of {N} {brand} {vehicle series} {indicator} in the last {N} days". The SQL template retains the complete SQL syntax structure, while replacing the specific parameter value positions with placeholder markers, forming a reusable query framework.
[0057] The knowledge base is constructed using a strategy that combines manual expert annotation with automated data mining. Initially, data experts compile high-frequency query patterns from historical query logs, manually write high-quality SQL templates, and annotate placeholder types and validation rules. After the system goes live, automated tools continuously monitor user queries, cluster and analyze newly emerging query patterns, extract common templates, and incorporate them into the knowledge base after expert review, thus achieving dynamic growth and self-improvement of the knowledge base.
[0058] II. Placeholder Type Constraint System
[0059] Placeholders in SQL templates are not simple string markers, but rather strong-type-constrained triple structures. Each placeholder fully defines three dimensions: parameter name, parameter type, and validation rules. The parameter name clearly identifies the semantic meaning of the position, such as `date1` representing the start date and `brand` representing the brand name. The parameter type limits the acceptable data types for that position, including date types, enumeration types, foreign key association types, integer range types, and floating-point precision types. Validation rules specifically stipulate the legality constraints of the parameter: date types must conform to a specific format and be within a range of values; enumeration types must be selected from the list of allowed values; and foreign key association types must have a corresponding record in the associated database table.
[0060] This type of constraint system is stored in the knowledge base using a standardized data model, ensuring that each placeholder has a clear metadata description. When information is subsequently populated, the system strictly verifies whether the entered value conforms to the type and rules defined for the placeholder, fundamentally preventing SQL syntax errors caused by type mismatches.
[0061] III. Multi-dimensional weighted scoring of semantic similarity
[0062] When the system receives a user query, it needs to retrieve the most matching SQL template from the knowledge base. This invention employs a weighted comprehensive scoring mechanism based on three dimensions: cosine similarity calculation, type matching evaluation, and validation pass rate check, to achieve accurate retrieval.
[0063] First, the system uses a pre-trained large language model to convert the user's question into a high-dimensional vector representation, and then calculates the cosine similarity between this representation and the vectors of all question templates in the knowledge base to obtain a preliminary semantic matching score. This score reflects the degree of similarity between the user's question and the template in terms of natural language expression.
[0064] Secondly, the system calculates the type matching score. Based on the key information extracted in the intent recognition stage, it verifies whether the parameter type corresponding to each information item is compatible with the type defined in the template placeholder. For example, if the extracted brand name exists in the placeholder's enumeration list, then the type matching score of that placeholder is perfect; if the extracted date format matches the date format requirements of the placeholder, then the type matching score of that placeholder is perfect. The average type matching score of all placeholders constitutes the overall type matching score.
[0065] Next, the system calculates the validation pass rate. The extracted parameter values are substituted into the placeholder validation rules for item-by-item checking to verify whether they meet all constraints such as format, range, enumeration, and foreign key requirements. The percentage of placeholders that pass all validation rules is the validation pass rate.
[0066] Finally, the system performs a weighted sum of the three scores according to preset weights to obtain a comprehensive similarity score. The weight allocation can be flexibly adjusted according to business scenarios. Typically, semantic similarity dominates to ensure the relevance of the recall, while type matching and validation pass rate serve as important supplements to improve recall accuracy. When the comprehensive score exceeds a dynamic threshold, the corresponding SQL template is officially recalled.
[0067] IV. Implementation of the Two-Way Mapping Verification Mechanism
[0068] During the process of filling the extracted key information into the SQL template placeholders, the system simultaneously builds a two-way mapping verification link to ensure the correctness and traceability of the filling operation.
[0069] The link contains three levels: problem semantic slots, placeholder definitions, and SQL syntax tree nodes. For each filled parameter, the system records its original source (which semantic slot in the question), target location (which placeholder), and its specific representation in the final SQL (which node in the syntax tree). After filling is completed, the system uses an SQL syntax parser to parse the generated SQL statement to obtain its abstract syntax tree structure. Subsequently, traverse the syntax tree nodes and compare and verify them one by one with the records in the mapping link to check whether the node type is consistent with the type defined by the placeholder and whether the node value matches the value extracted from the semantic slot.
[0070] If any mismatch or conflict is found during the verification process, the system immediately triggers the LLM uncertainty completion and conflict resolution sub-process instead of directly reporting an error. This verification mechanism not only ensures the legality of the SQL syntax but also provides complete mapping traceability capabilities for subsequent debugging and optimization.
[0071] V. LLM Uncertainty Completion and Conflict Resolution Sub-Process
[0072] When the bidirectional mapping verification detects a conflict, the system automatically starts the LLM-driven resolution sub-process. This process constructs specialized Prompt prompts for different conflict types and requests the large language model for intelligent processing.
[0073] For the scenario of missing required parameters, the sub-process will request the LLM to infer reasonable values for the missing ones based on the problem semantics. For example, if the query "sales of high-end car models in the past 7 days" does not specify the brand, the LLM will infer the most likely brands (such as Mercedes-Benz, BMW, Audi, Tesla) based on the brand list associated with high-end car models in the knowledge base, or identify the missing brand intent and prompt the user to supplement it.
[0074] For the scenario of type check failure, the sub-process will request the LLM to determine whether the extracted value is a format error, spelling error, or the use of synonyms. For example, when the user enters "Dami Automobile", the LLM will recognize it as a spelling error of "Xiaomi" and automatically correct it; if the input value is not in the allowed enumeration value list, the LLM will prompt the user with the legal value range.
[0075] For the scenario of mismatch between the syntax tree node types, the sub-process will request the LLM to re-adjust the parameter values according to the database metadata (such as field types, length limits), or recommend a more appropriate placeholder mapping relationship.
[0076] The response of the sub-process adopts a structured JSON format, clearly indicating whether the correction is successful, the corrected value, or the information that needs to be supplemented by the user. The system automatically corrects the mapping link according to the response result, regenerates and verifies the SQL, or returns clear prompt information to the user. This mechanism significantly improves the fault tolerance of the system and the user experience, avoiding process interruptions caused by parameter problems.
[0077] VI. Dynamic updates and self-learning of the knowledge base
[0078] The system possesses the capability for self-evolution of its knowledge base. During operation, all successfully executed queries and their final SQL statements are logged. The system periodically performs cluster analysis on the logs to identify frequently occurring query patterns. For query patterns that occur more frequently than a preset threshold and are not yet in the knowledge base, the system automatically extracts their common components, generates candidate templates, and submits them to data experts for review. Once approved, the system automatically inserts the template, along with its placeholder patterns, semantic vectors, and other metadata, into the knowledge base, enabling continuous expansion and optimization of the knowledge base.
[0079] At the same time, the system will count the usage frequency and success rate of each template. For templates that have not been used for a long time or have a consistently low success rate, they will be automatically marked as needing optimization, and experts will be prompted to revise or eliminate them to ensure the quality and timeliness of the knowledge base.
[0080] VII. Execution Flow of Generating Executable SQL
[0081] Once the template is recalled and verified, the system enters the population phase. The specific process is as follows:
[0082] Based on the mapping relationship between semantic slots and placeholders, the system fills each extracted parameter value into the corresponding position in the SQL template. Type validation is performed again before filling to ensure that the filled value strictly matches the placeholder type. After filling, the system performs a dual check on the generated SQL for syntax and semantics using a two-way mapping validation mechanism. If the validation passes, the final SQL statement is generated; if a conflict is triggered, the LLM resolution sub-process is initiated for correction. After correction, validation is repeated until a valid SQL statement is generated or it is determined that automatic correction is not possible, prompting user intervention.
[0083] The generated SQL statement is sent to the target database for execution through the database connection pool. After the execution result is returned, it enters the result analysis stage, forming a complete query loop.
[0084] S3. After the SQL execution result is generated, construct a prompt word containing the user's question, execution result, and answer requirements. Use a large language model to intelligently analyze and summarize the execution result and return a natural language conclusion.
[0085] Specifically, this step involves the following steps: After the SQL statement is executed and the original result set is returned, the present invention starts the intelligent result analysis module. By constructing a structured Prompt prompt word to call a large language model, it performs in-depth analysis, trend insight, and conclusion extraction on the original data, and finally outputs natural language conclusions that conform to the user's cognitive habits, forming a complete business closed loop from data query to decision-making advice.
[0086] I. The Three-Element Construction Mechanism of Prompt Prompts
[0087] The system-generated prompts strictly consist of three core components, ensuring that the large language model can fully understand the context and perform accurate analysis:
[0088] The first element is the original text of the user's question. The system fully embeds the user's initial natural language query into the Prompt, serving as the background anchor for the analysis task. For example, if the user's question is "the trend of Xiaomi SU7 mini-program user volume in the past 7 days", the original text of the question is preserved in its original form, ensuring that the model always focuses on the user's true intent and avoids deviating from the topic.
[0089] The second element is the SQL execution result. The system formats the raw result set returned by the database and embeds it into the Prompt. This processing includes converting row and column data into clear text descriptions, standardizing date fields, maintaining appropriate precision for numeric fields, and annotating missing or outlier values. For multi-row results, the system arranges them in chronological or other logical order to ensure a complete presentation of the causal chain of the time-series data. For example, the execution result might contain dates and user counts for seven days; the system lists these in the Prompt, day by day, forming a complete data narrative.
[0090] The third element is responding to the instructions. The system clearly defines the specific requirements of the analysis task in the Prompt, guiding the large language model to output conclusions that meet the needs of the business scenario. Instructions typically include four levels: first, describing the overall trend of data changes (e.g., rising, falling, fluctuating); second, identifying key nodes, including peaks, troughs, and inflection points; third, explaining abnormal fluctuations and analyzing possible external causes (e.g., the impact of market activities or holidays); and finally, providing business recommendations, such as recommending visualization chart types and suggesting subsequent actions. Instructions use structured language, clearly specifying the output format as natural language paragraphs or lists of key points, and emphasizing the avoidance of technical jargon to ensure the conclusions are easy to understand.
[0091] II. Intelligent Analysis Process of Large Language Models
[0092] After receiving the three-element prompt, the large language model initiates a multi-step inference and analysis process:
[0093] Trend analysis phase. The model first identifies the time series characteristics in the result set, calculates the rate of change and overall magnitude of change between adjacent time points, and determines whether the data shows an upward, downward, stable, or fluctuating trend. For data with a period exceeding 7 days, the model further determines whether a periodic pattern exists. During the analysis, the model automatically ignores minor random fluctuations and focuses on statistically significant changes.
[0094] Anomaly detection phase. The model identifies outliers based on the distribution characteristics of historical data. If a value at a certain point in time deviates from the overall trend by more than a preset threshold (e.g., exceeding the moving average by two standard deviations), it is marked as an anomaly. The model further analyzes the contextual information of the anomaly, such as whether the point in time corresponds to a holiday, promotional activity, or competitor product launch, providing clues for explaining the cause of the anomaly.
[0095] Attribution and Explanation Phase. The model combines the business context of user questions with anomalous patterns in the data to generate causal inferences. For example, if the number of users on July 28th is significantly higher than on other dates, and the knowledge base records "Xiaomi SU7 new car launch event" for that date, the model will associate the two and explain that the surge in user numbers is driven by marketing activities. The attribution process fully utilizes the pre-trained knowledge of the large language model to achieve cross-domain information fusion.
[0096] Conclusion Generation Phase. The model integrates trend descriptions, anomaly identification, and attribution explanations into coherent natural language text. The text structure follows a "general-specific-general" logic: the opening provides an overview of the overall trend and core conclusions; the middle section details key changes and the causes of anomalies; and the conclusion offers business recommendations and directions for future actions. The language style closely resembles the professional expression of data analysts, but avoids the use of technical terms such as SQL and databases, ensuring that business users can understand it without difficulty.
[0097] III. Returning and Post-processing Natural Language Conclusions
[0098] The preliminary conclusions generated by the large language model are returned to the user after post-processing by the system. Post-processing includes:
[0099] Standardize the format. Ensure the conclusion text is fluent and logically coherent, and streamline any repetitive statements or redundant paragraphs that may arise from the model. For long texts, the system automatically adds paragraph breaks and key point numbers to improve readability.
[0100] Visualization Recommendations. The system appends visualization suggestions at the end of the conclusion, recommending the most suitable chart type based on data characteristics. Line charts are recommended for time-series trend data, pie charts or bar charts are recommended for percentage analysis, and heat maps are recommended for geographical distribution. The recommendations are embedded in the conclusion in natural language, such as "It is recommended to use a line chart to display the 7-day trend and add an event label at the peak on July 28."
[0101] Interactive follow-up questions. If insufficient information or multiple possible explanations are found during the analysis, the system embeds follow-up questions in the conclusion to guide users to supplement information and deepen the analysis. For example, "A 15.6% increase in user volume was detected on July 28, which may be influenced by the launch of a new car. Please confirm whether any marketing activities were carried out on that day in order to further analyze the source of the channels."
[0102] IV. Context Preservation and Memory Mechanisms Throughout the Process
[0103] The system maintains contextual memory in multi-turn dialogue scenarios. If a user asks "What about BYD Han?" after querying "Xiaomi SU7 mini-program user volume trend in the last 7 days" in the previous round, the system will automatically inherit the time range (last 7 days) and indicator (mini-program user volume) from the previous round, only replacing the brand and vehicle series entities, and generate a query for "BYD Han mini-program user volume trend in the last 7 days", and supplement the explanation with a comparison of the changes with the previous round's results, thus achieving a coherent interactive data analysis experience.
[0104] V. Performance Optimization and Anomaly Handling
[0105] At the engineering implementation level, the intelligent results analysis module has undergone several optimizations to ensure response speed and stability:
[0106] Prompt length control. For large datasets with more than 50 rows of returned results, the system automatically performs sampling and summarization, retaining only key time points and extreme values in the Prompt to avoid exceeding the context length limit of the large language model.
[0107] Timeout degradation strategy. If the LLM analysis response time exceeds 5 seconds, the system switches to lightweight analysis mode, generating only trend summaries and peak identification, omitting attribution explanations, to ensure users quickly obtain core conclusions.
[0108] Caching and reuse mechanism. For the same query repeatedly initiated within a short period of time, the system caches the analysis conclusion generated the first time, and directly returns the cached result for subsequent queries, reducing the response time to the millisecond level.
[0109] Preferably, in the intent recognition step, if the question does not belong to the data analysis category that requires SQL generation, the default response template is returned directly, terminating the subsequent SQL generation process.
[0110] Preferably, key information extraction includes at least the following dimensions:
[0111] Time analysis: Based on the current date, analyze the time semantics in the problem. If the dates are the same, the start time is the same. If it is the last N days, then it does not include today and recursively calculates N days.
[0112] Metric identification: Identify which category of predefined metrics the problem belongs to. Predefined metrics include at least one of the following: new energy, push activation, organic traffic, new user volume, old user volume, mini-program user volume, new user volume, CVR, and CTR.
[0113] Entity recognition: Identify the vehicle series and brand name contained in the question; return "none" if not.
[0114] Preferably, the QA knowledge base construction and retrieval process includes:
[0115] In the knowledge base, a placeholder system with type constraints is established for each question-SQL template pair. The placeholders adopt a triple structure of {parameter name: parameter type: validation rule}, where time-type placeholders contain date format validation rules, indicator-type placeholders contain enumeration value range validation rules, and entity-type placeholders contain foreign key association validation rules.
[0116] The query vectors of user questions and knowledge base questions are encoded using BERT or large language models. The initial matching degree is calculated by cosine similarity and weighted by placeholder type matching degree and validation pass rate to obtain a comprehensive similarity score. Recall is triggered when the comprehensive similarity exceeds a dynamic threshold.
[0117] A two-way mapping verification mechanism is established. When the extracted key information is filled into the SQL template placeholders, a mapping link of problem semantic slot → placeholder → SQL syntax tree node is generated synchronously. The syntax validity of the filled SQL is verified by parsing the syntax tree. When a type conflict or syntax error is detected, an LLM-based uncertainty completion and conflict resolution sub-process is started to automatically correct the placeholder mapping relationship or prompt the missing key information.
[0118] Preferably, the specific process of intelligent analysis of the execution results by the large language model is as follows: the prompt word contains the user's question, the SQL execution result, and the answer requirement instruction. The large language model analyzes and summarizes the data trends and anomalies, and generates a natural language answer containing a visual chart description.
[0119] Preferably, the QA knowledge base adopts a placeholder template system with type constraints, combined with a two-way mapping verification mechanism and an uncertain completion sub-process, which makes the SQL syntax accuracy produce unexpected technical effects compared with the end-to-end Prompt method. Moreover, the solution is applicable to different dataset requirements and does not require retraining the model for specific scenarios.
[0120] Preferably, a Text2SQL system based on a large language model and knowledge base includes:
[0121] The input interface is used to receive query questions;
[0122] The processor communicates with the input interface and is configured with an LLM information extraction module, a QA knowledge base construction and recall module, and an LLM intelligent analysis module. When the processor executes a computer program, it implements the method of any one of claims 1-6.
[0123] The memory communicates with the processor and is used to store QA knowledge bases with type-constrained placeholders, SQL templates, and computer programs.
[0124] The output interface communicates with the processor to return natural language conclusions.
[0125] Preferably, the system performs semantic vector encoding through BERT or a large language model, and realizes SQL template recall based on a weighted comprehensive score of cosine similarity, placeholder type matching degree, and verification pass rate. At the same time, it has a built-in bidirectional mapping verification mechanism and an LLM-driven conflict resolution sub-process to complete the conversion from natural language query to executable SQL and intelligent analysis of the results.
[0126] Furthermore, a computer-readable storage medium storing a computer program is characterized in that, when executed by a processor, the computer program implements the aforementioned Text2SQL method based on a large language model and knowledge base.
[0127] Furthermore, an electronic device includes a processor and a memory, the memory storing a computer program that, when executed by the processor, implements the aforementioned Text2SQL method based on a large language model and knowledge base.
[0128] Example 1: Construction of a knowledge base with a triplet structure containing type constraint placeholders
[0129] This embodiment elaborates on the triplet structure with type-constrained placeholders and its storage method in the QA knowledge base.
[0130] 1.1 Placeholder Triple Structure Design
[0131] This invention innovatively upgrades traditional static placeholders to strongly type-constrained triple structures, where each placeholder contains three core elements: parameter name, parameter type, and validation rules. This structure is formally defined in the knowledge base using a standardized data model, ensuring that each placeholder has a clear data type and validity validation rules.
[0132] Specifically, for time-related parameters, the triplet specifies the date format and limits the range of values; for example, it disallows future dates. For enumeration-related parameters, the triplet explicitly lists all valid enumeration values; for example, brand names must be selected from a preset brand list. For foreign key-related parameters, the triplet specifies the database table and fields it references, ensuring that the input value actually exists in the related table. Furthermore, the system supports integer range types and decimal types with specified decimal places; each type has corresponding value ranges or precision validation rules.
[0133] 1.2 Knowledge Base Storage Structure
[0134] When creating the knowledge base table in the database, a table structure with multiple fields is adopted. The question text field stores the template of the user's original query statement, the SQL template field stores the corresponding structured query statement template, the placeholder pattern field stores the above triplet structure array in JSON format, and the semantic vector field stores the vector representation encoded by the large language model. In addition, fields recording the creation and update times are included, as well as an index for the question text to improve query efficiency.
[0135] When a new question-SQL template pair is inserted into the knowledge base, the placeholder schema field describes in detail the name, type, and validation rules of each parameter. For example, the format and value range are specified for the time parameter, all allowed enumerated values are listed for the brand parameter, and the database table and field to which the vehicle series parameter is associated with its foreign key are indicated for the vehicle series parameter.
[0136] 1.3 Dynamic Threshold Configuration
[0137] The system's overall similarity threshold is stored in the cache and can be dynamically adjusted at runtime. For example, the initial threshold can be set to 0.75. When the system detects that the historical accuracy is lower than the preset level, it will automatically lower the threshold by 0.02 to recall more candidate templates for selection. At the same time, the system also allows administrators to manually adjust the weight coefficients, such as cosine similarity weight, type matching weight, and validation pass weight, through the configuration interface to adapt to the needs of different business scenarios.
[0138] Example 2: Weighted Composite Score Calculation and Template Recall
[0139] 2.1 Vector Encoding and Similarity Calculation
[0140] The system uses a pre-trained large language model to encode user questions. Specifically, the user question text is input into the model, which converts it into a high-dimensional vector representation and normalizes the vector to a length of 1. All question templates in the knowledge base are also pre-encoded in the same way to obtain corresponding vectors, which are then stored.
[0141] When a user asks a new question, the system calculates the cosine similarity between the user's question vector and the template vectors in the knowledge base. Since the vectors are normalized, the cosine similarity can be obtained by the dot product of the vectors, with the result ranging from 0 to 1. A higher value indicates greater semantic similarity. The system then selects the templates with the highest similarity as candidates.
[0142] 2.2 Type Matching Degree Calculation
[0143] Based on the output of the information extraction module, the system calculates the type matching degree with the placeholders. Specifically, it iterates through all placeholders defined in the knowledge base template, checking if the extraction results contain the corresponding parameters. For each matched parameter, it verifies whether its value conforms to the type and validation rules specified by the placeholder.
[0144] For example, for date type placeholders, the system verifies whether the extracted date string conforms to the specified format; for enumeration type placeholders, the system checks whether the extracted value is in the allowed enumeration value list; for foreign key type placeholders, the system queries the related database table to confirm that the extracted value exists in the specified field. The proportion of the number of validated parameters to the total number of placeholders is the type matching degree.
[0145] 2.3 Calculation of Verification Pass Rate
[0146] The pass rate assesses whether all extracted parameters fully meet the placeholder validation rules. The system checks each parameter value one by one to ensure it conforms to all rules for its corresponding placeholder, including format, range, enumerated values, and foreign key relationships. For parameters that do not meet the rules, the system records the specific reasons for failure for use in subsequent conflict resolution subprocesses. The percentage of parameters that pass all validation rules is the pass rate.
[0147] 2.4 Comprehensive Scoring and Dynamic Threshold
[0148] The system calculates a weighted sum of the three scores based on preset weighting coefficients to obtain a comprehensive similarity score. These weighting coefficients can be adjusted according to business needs; for example, cosine similarity could account for 50%, type matching for 30%, and validation pass rate for 20%.
[0149] When the overall score exceeds a preset threshold, the corresponding template is recalled. The threshold can be dynamically adjusted based on historical accuracy: if the system detects a decrease in the success rate of recently recalled templates, it will automatically lower the threshold to expand the recall scope; conversely, it will raise the threshold to improve accuracy.
[0150] Example 3: Bidirectional Mapping Verification Mechanism
[0151] 3.1 Mapping Link Generation
[0152] When filling the extracted information into the SQL template placeholders, the system simultaneously constructs a three-layer mapping structure, recording the complete link from the question semantic slot to the placeholder and then to the SQL syntax tree node. Each mapping node contains three parts: the question semantic slot (such as "brand" and its extracted value), the placeholder definition (such as parameter name, type, and validation rules), and the corresponding node position in the SQL syntax tree.
[0153] 3.2 Syntax Tree Parsing and Verification
[0154] The system uses an SQL syntax parser to parse the padded SQL statement and generate an abstract syntax tree (AST). Then, it traverses the AST nodes and compares and verifies them with the pre-built mapping links.
[0155] For each mapping node, the system checks:
[0156] Does the corresponding node exist in the AST?
[0157] Does the node type match the placeholder type?
[0158] Does the node value match the semantic slot extracted value?
[0159] If all mapping nodes pass the validation, the SQL statement is considered to be syntactically valid and semantically correct.
[0160] 3.3 Conflict Detection and Correction
[0161] When a conflict is detected during verification, such as when the extracted brand value is not in the enumeration list or the date format does not meet the requirements, the system will record the conflict details and initiate a correction process. The system will extract conflict information, including user input values, expected data types, validation rules, and reasons for failure, and prepare to submit it to the LLM for intelligent resolution.
[0162] Example 4: LLM Uncertainty Completion and Conflict Resolution Subprocess
[0163] This embodiment details how the system automatically initiates an LLM subprocess for intelligent processing when information extraction is incomplete or mapping fails.
[0164] 4.1 Subprocess Triggering Conditions
[0165] The system triggers the resolution sub-process in three scenarios:
[0166] Missing Required Parameters: Placeholders marked as required were not found in the extraction results.
[0167] Type validation failed: The extracted value could not pass the type or rule validation of the placeholder.
[0168] Syntax tree validation conflict: Node type mismatch detected during bidirectional mapping validation.
[0169] 4.2 Sub-process processing logic
[0170] For scenarios where essential parameters are missing, the system builds a Prompt request to the LLM (Local Management Module) to infer the missing values based on the question's semantics. For example, if the question is "sales figures for high-end car models in the last 7 days" but the brand is not specified, the LLM will infer the most likely brand based on the list of brands associated with high-end car models in the knowledge base (such as Mercedes-Benz, BMW, Audi, and Tesla), or prompt the user to provide additional information.
[0171] In the scenario of type verification failure, the LLM will analyze whether the value in the question is a formatting error, a spelling mistake, or a synonym has been used. For example, if the user enters "rice car", the LLM will recognize it as a spelling mistake of "Xiaomi" and correct it. If the input value is not within the allowed range, the LLM will prompt the user with the legal value range.
[0172] 4.3 Sub-process Execution and Feedback
[0173] After the sub-process is started, the system pauses the main process, sends a structured Prompt to the LLM and waits for a response. If the LLM successfully provides a corrected value, the system will complete the missing information or replace the incorrect value, and then continue the main process. If the LLM cannot correct it, a clear prompt message will be returned to the user, asking to supplement the necessary information, rather than directly reporting an error or generating an incorrect SQL.
[0174] Example 5: System Hardware Implementation and Engineering Deployment
[0175] 5.1 Distributed Microservices Architecture
[0176] The system is deployed in a Kubernetes cluster using a microservices architecture, which includes multiple independent services:
[0177] API Gateway Service: Responsible for receiving external requests, performing routing distribution, rate limiting control, and identity authentication
[0178] LLM Extraction Service: Invokes an external large language model API for information extraction, and configures a circuit breaker mechanism to prevent cascading failures
[0179] Recall Service: Performs vector retrieval and weighted scoring calculation, which is a CPU-intensive task
[0180] Verification Service: Runs syntax parsing and bidirectional mapping verification, which is a memory-intensive task
[0181] Resolution Service: Handles LLM sub-process calls, which have a low concurrency but a long single-time consumption
[0182] Each service communicates with each other through a service discovery mechanism and can be scaled independently.
[0183] 5.2 Performance Optimization Strategies
[0184] To improve the system response speed, the following optimization measures are adopted:
[0185] Vector Cache: Caches the vector representations of frequently asked questions in an in-memory database, significantly reducing the recall latency
[0186] Batch Processing and Filling: For batch queries using the same template, merge and execute the filling operation to reduce repeated parsing
[0187] Asynchronous resolution: For non-critical conflicts, the main process is allowed to return candidate SQL first, asynchronously call the LLM for confirmation, and execute the SQL after user confirmation.
[0188] Real-time monitoring: Deploy a monitoring system to collect response latency data from various services and display it through a visual dashboard. Trigger an alert when the latency exceeds a threshold.
[0189] 5.3 Safety reinforcement
[0190] The system ensures security on three levels:
[0191] Input layer: Uses regular expressions to filter potential SQL injection keywords and limits the length of input text.
[0192] Permission layer: Parses user identity tokens and isolates knowledge base template access permissions according to business lines.
[0193] Execution layer: Before SQL execution, the syntax parser prohibits high-risk operations (such as data deletion and structure modification).
[0194] Audit layer: Records execution logs for all generated SQL statements, including execution time, user information, and number of result rows, for post-event auditing and tracing.
[0195] Example 6: Industrial Application Case
[0196] After deploying this invention, a leading automotive data platform processes an average of 150,000 natural language queries per day, covering various business scenarios such as sales trends, user activity, competitor comparisons, and geographic distribution.
[0197] The platform has built a knowledge base containing 85,000 templates, covering 12 car brands, over 300 car series, and more than 50 business metrics. The system's average response time is 850 milliseconds, with recall services taking less than 100 milliseconds and the trigger rate of resolution sub-processes being less than 5%.
[0198] After going live, data analysts' work efficiency increased by 3 times, production incidents caused by SQL syntax errors or logical errors were eliminated, and business personnel could directly obtain data insights through natural language without relying on technical team support.
[0199] By adopting the above-disclosed technical solution of this invention, the following beneficial effects are obtained:
[0200] This invention revolutionizes the technical paradigm of natural language data query by constructing a complete Text2SQL system driven by a large language model and knowledge base, from the underlying mechanism to the upper-level application, and brings multi-dimensional and substantial improvements to enterprise-level data analysis scenarios.
[0201] In terms of accuracy, this invention fundamentally solves the inherent illusion problem and frequent syntax errors of traditional end-to-end methods. By introducing a triple placeholder system with type constraints, the SQL generation process is transformed from uncontrollable free text generation into parameterized, verifiable compiled construction. Combined with a bidirectional mapping verification mechanism and LLM intelligent sub-process resolution, it achieves accurate conversion from natural language to executable SQL, greatly reducing the query failure rate caused by syntax errors and significantly improving system reliability and user trust.
[0202] In terms of versatility and flexibility, this invention completely eliminates the dependence of traditional fine-tuning models on specific datasets. Employing a configurable knowledge base template architecture, the system can quickly adapt to new business scenarios or data structures without undergoing time-consuming model retraining cycles; it only needs to update the knowledge base template. This design significantly shortens the system deployment and iteration cycle, enabling enterprises to respond agilely to market changes and flexibly support diverse business needs.
[0203] In terms of intelligence and adaptability, this invention overcomes the limitations of static rule engines. The weighted comprehensive scoring mechanism can dynamically balance semantic relevance and type legality, and the LLM-driven conflict resolution sub-process has human-like reasoning capabilities, automatically handling complex anomalies such as missing information, type conflicts, and synonymous expressions. The system can not only generate queries, but also proactively correct or intelligently prompt when problems are detected, truly achieving an intelligent leap from "tool" to "assistant."
[0204] Regarding the completeness of the business loop, this invention fills the gap in existing technologies that "only generate data without analysis." The intelligent analysis module constructs a three-element Prompt to drive a large language model to perform trend insights, anomaly attribution, and visualization suggestions on the raw data, directly outputting highly readable natural language conclusions. This design upgrades Text2SQL from an isolated "translation tool" to an end-to-end "decision support system," allowing users to obtain insights that can directly guide business operations without requiring a data analysis background.
[0205] In terms of engineering and maintainability, this invention provides a complete engineering solution from knowledge base management, distributed deployment, performance optimization to security auditing. The microservice architecture supports high-concurrency access, dynamic thresholds and caching strategies ensure extremely low latency, and fine-grained access control and operation auditing meet enterprise-level compliance requirements. The system possesses the scalability, stability, and security required for production environments and can be directly deployed in industries such as finance and automotive, which have stringent requirements for data accuracy and system reliability.
[0206] In terms of business value, this invention significantly reduces the human resource costs and technical barriers for enterprises in the field of data analysis. Business personnel can directly obtain data insights through natural language without relying on professional technical teams, and data analysts can be freed from repetitive SQL writing to focus on high-value in-depth analysis. After the system goes live, data query efficiency within the enterprise is improved, decision-making cycles are shortened, and a data-driven culture is rapidly popularized, providing a solid technical foundation for digital transformation.
[0207] The above description is only a preferred embodiment of the present invention. It should be noted that for those skilled in the art, several improvements and modifications can be made without departing from the principle of the present invention, and these improvements and modifications should also be considered within the scope of protection of the present invention.
Claims
1. A Text2SQL method based on a large language model and knowledge base, characterized in that, Includes the following steps: The intent of the input query is identified by a large language model to determine whether the query belongs to the data analysis category that requires the generation of SQL. If it is found, key information is extracted, including at least one of the following: start and end time, indicator, dimension, vehicle series / brand name, and calculation method. A QA knowledge base is constructed and SQL templates are retrieved based on semantic similarity. The knowledge base stores predefined question-SQL template pairs, wherein the SQL template contains placeholders for key information to be filled. The extracted key information is used to fill the placeholders and generate executable SQL statements. After the SQL execution result is generated, a Prompt message containing the user's question, execution result, and answer requirements is constructed. The execution result is then intelligently analyzed and summarized using a large language model, and a natural language conclusion is returned.
2. The method according to claim 1, characterized in that, In the intent recognition step, if the question does not belong to the data analysis category that requires SQL generation, the default response template is returned directly, terminating the subsequent SQL generation process.
3. The method according to claim 1, characterized in that, The key information extraction includes at least the following dimensions: Time analysis: Based on the current date, analyze the time semantics in the problem. If the dates are the same, the start time is the same. If it is the last N days, then it does not include today and recursively calculates N days. Metric identification: Identify which category of predefined metrics the problem belongs to. Predefined metrics include at least one of the following: new energy, push activation, organic traffic, new user volume, old user volume, mini-program user volume, new user volume, CVR, and CTR. Entity recognition: Identify the vehicle series and brand name contained in the question; return "none" if not.
4. The method according to claim 1, characterized in that, The QA knowledge base construction and retrieval process includes: In the knowledge base, a placeholder system with type constraints is established for each question-SQL template pair. The placeholder adopts a triple structure of {parameter name: parameter type: validation rule}, where time-type placeholders contain date format validation rules, indicator-type placeholders contain enumeration value range validation rules, and entity-type placeholders contain foreign key association validation rules. The query vectors of user questions and knowledge base questions are encoded using BERT or large language models. The initial matching degree is calculated by cosine similarity and weighted by placeholder type matching degree and validation pass rate to obtain a comprehensive similarity score. Recall is triggered when the comprehensive similarity exceeds a dynamic threshold. A two-way mapping verification mechanism is established. When the extracted key information is filled into the SQL template placeholders, a mapping link of problem semantic slot → placeholder → SQL syntax tree node is generated synchronously. The syntax validity of the filled SQL is verified by parsing the syntax tree. When a type conflict or syntax error is detected, an LLM-based uncertainty completion and conflict resolution sub-process is started to automatically correct the placeholder mapping relationship or prompt the missing key information.
5. The method according to claim 1, characterized in that, The specific process of the large language model performing intelligent analysis of the execution results is as follows: the prompt word contains the user's question, the SQL execution result, and the answer requirement instruction. The large language model analyzes and summarizes the data trends and anomalies, and generates a natural language answer containing a visual chart description.
6. The method according to any one of claims 1-5, characterized in that, The QA knowledge base adopts a placeholder template system with type constraints, combined with a two-way mapping verification mechanism and an uncertain completion sub-process, which makes the SQL syntax accuracy produce unexpected technical effects compared with the end-to-end Prompt method. Moreover, the solution is applicable to different dataset requirements and does not require retraining the model for specific scenarios.
7. A Text2SQL system based on a large language model and knowledge base, characterized in that, include: The input interface is used to receive query questions; A processor, communicating with an input interface, is configured with an LLM information extraction module, a QA knowledge base construction and recall module, and an LLM intelligent analysis module. When the processor executes a computer program, it implements the method of any one of claims 1-6. The memory, communicating with the processor, is used to store the QA knowledge base with type-constrained placeholders, the SQL template, and the computer program. The output interface communicates with the processor to return natural language conclusions.
8. The system according to claim 7, characterized in that, The system uses BERT or a large language model for semantic vector encoding and implements SQL template recall based on a weighted comprehensive score of cosine similarity, placeholder type matching degree, and verification pass rate. It also incorporates a bidirectional mapping verification mechanism and an LLM-driven conflict resolution subprocess to complete the conversion from natural language query to executable SQL and intelligent result analysis.
9. A computer-readable storage medium having a computer program stored thereon, characterized in that, When the computer program is executed by the processor, it implements the Text2SQL method based on a large language model and knowledge base as described in any one of claims 1-6.
10. An electronic device comprising a processor and a memory, characterized in that, The memory stores a computer program that, when executed by the processor, implements the Text2SQL method based on a large language model and knowledge base as described in any one of claims 1-6.