Method for converting natural language to structured query language based on cue word engineering, medium and equipment

By designing a thought chain-based NL2SQL algorithm and combining time-aware and referential disambiguation modules, the shortcomings of existing NL2SQL methods in complex queries and ambiguous data processing are addressed, achieving high-quality SQL generation and data analysis functions.

CN121919237APending Publication Date: 2026-04-24CHINA TELECOM DIGITAL INTELLIGENCE TECH CO LTD
View PDF 0 Cites 0 Cited by

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
CHINA TELECOM DIGITAL INTELLIGENCE TECH CO LTD
Filing Date
2025-12-30
Publication Date
2026-04-24

AI Technical Summary

Technical Problem

Existing Natural Language to Structured Query Language (NL2SQL) methods are not robust enough to handle complex queries and ambiguous data in real-world enterprise databases, and lack effective error correction mechanisms.

Method used

A thought chain-based NL2SQL algorithm was designed, combining coarse-grained and fine-grained thought chains, integrating a time-aware module, a time extraction module, and a referential disambiguation module. The algorithm rewrites user questions into precise expressions through a large model and designs an SQL error correction module when SQL queries fail.

Benefits of technology

It improves the ability of large models to handle complex queries and fuzzy expressions, generates high-quality SQL statements, enhances the ability to retrieve data from real enterprise databases, and provides data analysis and visualization support.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN121919237A_ABST
    Figure CN121919237A_ABST
Patent Text Reader

Abstract

The invention provides a method for converting natural language to structured query language based on cue word engineering, a medium and equipment, and belongs to the field of natural language processing. The NL2SQL algorithm based on the thinking chain is designed, the thinking chain combines the coarse-grained thinking chain and the fine-grained thinking chain, the NL2SQL main body process is provided for the large model, the thinking chain is fused into the dividing and concluding thinking, and the large model is helped to cope with the complex query problem. For ambiguous data possibly occurring in actual enterprise application and fuzzy expression of a user, a time sensing module, a time extraction module and an anaphora disambiguation module are fused in an NL2SQL algorithm, a user problem is rewritten into an accurate problem containing accurate time expression and a target table and field, accurate and comprehensive information is provided for generating SQL by a large model, and the user experience is improved. When SQL query fails, an SQL error correction module is designed, and further guarantee is provided for a large model to correctly answer user questions.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention belongs to the field of natural language processing, specifically relating to a method, medium, and device for converting natural language to structured query language based on prompt word engineering. Background Technology

[0002] With the development of large language models, the performance of Natural Language to SQL (NL2SQL) has been significantly improved. NL2SQL technology greatly lowers the barrier for ordinary people to access and manipulate data. For many workers without programming or SQL knowledge, directly using natural language to make data query requests to the database is more intuitive and convenient. For example, in various scenarios such as business intelligence analysis, customer service support, and scientific research data analysis, NL2SQL can help users quickly obtain the data information they need and improve work efficiency.

[0003] Existing NL2SQL methods include prompt word engineering and supervised fine-tuning. Supervised fine-tuning methods, such as DTS-SQL and SQLfuse, apply fine-tuning to large models in the schema linking and SQL statement generation steps. However, due to their hardware dependence, these methods are mostly used for large models with a small number of parameters, which limits the performance of NL2SQL to some extent. Existing prompt word engineering research mainly focuses on thought chains and context learning. For example, one approach improves context learning by searching for examples similar to user questions in the training set, but this makes the model highly dependent on the selected examples, resulting in poor robustness to unfamiliar questions in real-world applications. Another approach borrows the divide-and-conquer strategy and the steps of SQL execution in database engines, designing two thought chains to generate SQL in parallel, and then designing an algorithm to select one. While both thought chains are beneficial for large models to handle complex query problems, this method does not integrate the two thought chains to work together effectively. Furthermore, existing prompt word methods and fine-tuning methods use open-source datasets as application scenarios, without considering the ambiguous data that may be present in real-world enterprise databases or the vague expressions that may be present in real-world user questions. Summary of the Invention

[0004] This invention addresses the shortcomings of existing technologies by providing a method, medium, and device for converting natural language to structured query language based on prompt word engineering. This invention designs an NL2SQL algorithm based on a thought chain and provides a user-friendly web interface. The thought chain in this invention combines coarse-grained and fine-grained thought chains, providing the main NL2SQL process for large models while incorporating a divide-and-conquer approach to help large models handle complex query problems. For ambiguous data and vague user expressions that may arise in practical enterprise applications, this invention integrates a time-aware module, a time extraction module, and a referential disambiguation module into the NL2SQL algorithm. This rewrites user questions into precise questions containing accurate time descriptions and target tables and fields, providing accurate and comprehensive information for large models to generate SQL. When SQL queries fail, this invention designs an SQL error correction module, further ensuring that large models can correctly answer user questions.

[0005] To achieve the above objectives, the present invention adopts the following technical solution: In a first aspect, the present invention provides a method for converting natural language to structured query language based on prompt word engineering, comprising the following steps: Step 1: Generate a structured database M_schema based on the parameters specified by the user; Step 2: Based on the database and user questions, the large model summarizes the relevant tables and fields and outputs them in a structured format; Step 3: Convert the vague time expression in the user question into an accurate time expression, and extract the entities with specific names and meanings in the user question, and match them with the field values ​​in the database; Step 4: The large model generates SQL statements that meet the query requirements based on the user's question, the database, and the information gathered in Step 3; Step 5: Execute the SQL; if the SQL execution fails, modify the values ​​of fields in the SQL statement that may have ambiguous matches; Step 6: After the SQL is executed successfully, generate a data analysis report based on the query results and visualize it; if the modified SQL still fails to execute, analyze the error message and provide the newly generated SQL statement.

[0006] Optionally, in step 1, the structured database M_schema includes table structure, primary key, foreign key, and field examples.

[0007] Optionally, step 3 specifically includes: The current time and the generated database are provided to the large model. Prompt words are designed, and the large model is instructed to convert all time-related expressions in the user's question into precise time expressions including year, month, and day according to the rules in the prompt words. Entities in the question are extracted, and the tables and fields that the entities may exist in the database are found. Finally, the corresponding entity-table-field information is organized into JSON format and returned.

[0008] Optionally, in step 3, for the entities extracted from the question, BERT is used for semantic encoding, and the cosine similarity between them and the semantic vectors of each entity in the entity database is calculated to obtain the final matching result.

[0009] Optionally, step 4 specifically includes: The user's question, the database, and the information gathered in step 3 are used as inputs, and thought chain prompts are designed to guide the large model to generate SQL that satisfies the query task.

[0010] Optionally, the design of the thought chain includes: First, check if the question contains exclusive conditions, and extract the conditions according to the description in the user's question; During the structure mapping and condition checking process, the primary key and foreign key connection methods are determined according to the database structure; the database fields corresponding to each condition in the user's question are confirmed, and for exclusive conditions, the negation is performed first before field matching; the sample data is compared to verify whether the filtered values ​​are semantically similar. During SQL construction, LIKE is used for fuzzy matching of conditions and judgments; SELECT only includes necessary fields; LIKE and NOT LIKE are preferred for all condition judgments; in the exclusiveness check table, negative conditions are in the form of NOT LIKE plus a positive term, time conditions are in the form of LIKE plus year, and blank fields are wrapped in backticks.

[0011] Optionally, in step 5, a timeout is set when executing the SQL. If the query completes within the timeout period, the result and column names are returned; if the timeout occurs, None is returned and a timeout message is displayed; if other exceptions occur, an error message is returned.

[0012] Optionally, step 6 specifically includes: First, select a prompt word template based on the given language, and set the model as an expert for answering user questions and performing data analysis through system_prompt; then, specify the task for the model in instruction, determine whether the provided SQL statement meets the requirements of the user question and whether the execution is successful. If the execution is successful, generate a data analysis report based on the execution result; if it fails, regenerate the SQL statement based on the error message; finally, provide the user question, the SQL statement to be evaluated, and the execution result in user_prompt.

[0013] In a second aspect, the present invention provides a computer-readable storage medium storing a computer program that causes a computer to execute the natural language to structured query language conversion method based on prompt word engineering as described in the first aspect.

[0014] Thirdly, the present invention provides an electronic device, comprising: a memory, a processor, and a computer program stored in the memory and executable on the processor, wherein when the processor executes the computer program, it implements the natural language to structured query language conversion method based on prompt word engineering as described in the first aspect.

[0015] The beneficial effects of this invention are: 1. It integrates both coarse-grained and fine-grained thinking chains, providing an overall approach and mindset for large models, thereby improving the ability of large models to cope with complex real-world problems and the quality of generated SQL.

[0016] 2. To address the potentially vague questions raised by actual users, this invention incorporates a time-aware and entity-matching module. This transforms vague questions into precisely defined ones, enhancing the large model's understanding of user intent and making the invention more practically applicable.

[0017] 3. To address the potential ambiguity in database data, this invention designs a referential disambiguation module that utilizes both semantic matching and fuzzy matching algorithms to eliminate potential ambiguities in field values, thereby improving the large model's retrieval capabilities for real-world enterprise databases.

[0018] 4. This invention includes a data analysis and visualization chart analysis module to help users understand the distribution, trends, and changes in data. Furthermore, the user interface is simple; users only need to select a database and enter their questions to generate SQL statements, query results, and data analysis, making it easy for people in various industries to use quickly. Attached Figure Description

[0019] Figure 1 This is a flowchart of the natural language to structured query language conversion method based on prompt word engineering according to the present invention.

[0020] Figure 2 This is the user interface for implementing the method of the present invention; Figure 3 These are the pattern linking and entity matching steps of the present invention; Figure 4 It is the thought process and generated SQL of the large model; Figure 5 It is a visual chart analysis of the query results; Figure 6This is an example of a complex query that this invention addresses. Detailed Implementation

[0021] The technical solutions in the embodiments of this application will be clearly and completely described below with reference to the accompanying drawings.

[0022] In one embodiment, this invention proposes a method for converting natural language to structured query language based on prompt word engineering. The specific technical solution and application scenarios are as follows: First, the system generates structured database information M_schema. Based on user-specified parameters, it generates comprehensive metadata descriptions including table structure, primary keys, foreign keys, and field examples, laying the foundation for subsequent steps. Next, the schema linking stage utilizes a large model to analyze M_schema and the user's question, summarizing relevant tables and fields and outputting them in a structured format, providing sufficient information for SQL generation. Subsequently, the time-aware and entity matching steps transform the fuzzy time expression in the user's question into an accurate time range. The system extracts specific entities and matches them with database fields to ensure query accuracy. Then, the large model generates SQL statements that meet the requirements based on the processed information. A timeout mechanism is set during SQL execution: if completed within the time limit, the results and column names are returned; if timeout occurs, None is returned with a prompt; if an exception occurs, an error message is returned. If SQL execution fails, a disambiguation step corrects potentially ambiguous field values ​​in the statement using semantic matching and fuzzy matching algorithms. After successful execution, the system generates a data analysis report based on the query results; if errors persist, the system analyzes the error message and provides a new SQL statement. Finally, visual charts are automatically generated based on successful query results to help users intuitively understand data distribution. This solution is suitable for enterprise data management and business intelligence analysis scenarios, helping users quickly retrieve and understand complex data distributions.

[0023] The method flow of the present invention is as follows: Figure 1 As shown, the user interface is as follows Figure 2 As shown, the specific steps of the method are as follows: Step 1: Generate structured database information M_schema. M_schema provides a method and system for automatically generating database metadata schemas. It can automatically generate comprehensive metadata descriptions, including table structure, primary keys, foreign keys, and field examples, based on user-specified parameters.

[0024] M-Schema is a semi-structured database schema representation method that generates detailed metadata descriptions for selected data tables, including table names, field names, field types, primary keys, default values, whether NULL values ​​are allowed, and sample subdata. Compared to other database schema representations, M-Schema introduces data types and more detailed column descriptions, reducing ambiguity when the model handles similar columns and ensuring that the generated SQL queries are more accurate during execution. Large models using M-Schema show significantly improved accuracy in generating SQL when handling complex queries. The structure of M_schema is shown in Table 1: Table 1 Structure of M_schema

[0025] Step 2: Schema Linking. Based on M_schema and the user's question, the model summarizes the relevant tables and fields and outputs them in a structured format, providing sufficient information for subsequent SQL statement generation.

[0026] like Figure 3 As shown, schema linking is a crucial step in NL2SQL, aiming to associate entities, keywords, or phrases in a natural language query with tables, columns, or values ​​in the M_schema. The core task of schema linking is to extract information related to the database schema from the natural language query and map it to specific database elements to generate correct SQL queries. This invention designs relevant prompts, leverages the understanding capabilities of a large model to generate high-quality schema links, and outputs them in a structured format for subsequent analysis. The schema links of this invention are output in JSON format, as shown in Table 2.

[0027] Table 2 Schema Links

[0028] Step 3: Time Awareness and Entity Matching. This step transforms the vague time expressions in the user's question into accurate time expressions and extracts entities with specific names and meanings from the user's question to match them with field values ​​in the database.

[0029] The current time and the compiled database M_schema are provided to the large model. Hint words are designed, and the large model is instructed to convert all time-related expressions in the user's question into precise time expressions (year-month-day-year-month-day) according to the rules in the hint words. Entities in the question are extracted individually, and the table and field in M_schema are identified where each entity might exist. Finally, all the compiled "entity-table-field" information is formatted into JSON and returned. For the extracted entity information, BERT is used for semantic encoding, and the cosine similarity between the extracted entity information and the semantic vectors of each entity in the entity database is calculated to obtain the final matching result. After this step, a new question containing a specific time range and the specific table, field, and field value to be searched is obtained. This new question serves as additional hint information to assist in SQL generation. The information compiled in the time-aware and entity matching steps is also output in JSON format, as shown in Table 3.

[0030] Table 3 Time Awareness and Entity Matching

[0031] Further field value matching was performed on the compiled information, as shown in Table 4.

[0032] Table 4 Entity Matching Algorithm

[0033] Step 4: SQL Statement Generation. The large model generates an SQL statement that meets the query requirements based on the user's question and the information gathered in the previous steps.

[0034] This invention uses user questions, M_schema, and information from time-aware entity matching steps as input, and designs thought chain prompts to guide the large model in generating SQL that satisfies the query task. The thought chain designed in this invention combines coarse-grained and fine-grained guidance for the large model. The coarse-grained thought chain aims to provide the main ideas for the large model to generate SQL, including identifying user requirements, selecting relevant tables and fields, constructing SQL, and verification and correction steps. Guided by the coarse-grained thought chain, the large model can solve most simple query problems. The fine-grained thought chain is designed to improve the model's ability to handle multi-condition queries, multi-table queries, and complex problems involving mathematical calculations. The fine-grained thought chain mainly applies the divide-and-conquer approach, guiding the large model to break down complex problems step by step into several simple problems and generate corresponding simple SQL. Finally, the various simple SQLs are integrated and redundancy is removed to obtain the SQL that can solve the complex problem. The integration of the two thought chains improves the large model's ability to solve query problems of various real-world difficulty.

[0035] like Figure 4 As shown, the design of the thought chain in this invention is as follows: 1. First, check if the question contains exclusive conditions such as not / no / does not contain / exclude. Strictly extract the relevant information from the question and do not replace words. Even if there are the same state descriptions in the table structure, the NOT statement must be used to resolve the issue.

[0036] 2. Structure Mapping and Condition Check Analyze table relationships: Determine the primary key / foreign key join method based on the database structure {schema_link}; Field matching: Confirm the database fields corresponding to each condition in the problem, and be as comprehensive as possible while ensuring accuracy. For exclusive conditions, negate them first before performing field matching, so that a match can still be found even if negation is not performed. Value range check: Compare the filtered values ​​with the example data to verify whether they are semantically similar (it is not necessary to select values ​​entirely from the instance, as the instance does not represent all possible values), and the selected column name must exist in the selected table.

[0037] 3. SQL Construction When using LIKE for fuzzy matching or conditional judgment, if the filtering conditions involve names, all prefixes and suffixes must be removed, retaining only the middle keyword. The format can be referenced as LIKE%name%. For example, "Apple Inc." should be LIKE%Apple%, and "water conservancy project" should be LIKE%waterconservancy%. The principle of simplicity: SELECT statements should only include the necessary fields; Fuzzy logic priority: LIKE / NOT LIKE is preferred for all conditional judgments; Exclusivity checklist: Negative conditions use NOT LIKE% positive term; time conditions use LIKE% year% form; blank fields must be enclosed in backticks.

[0038] Here's an example of solving a problem using the divide-and-conquer approach: Example 1: Calculate the percentage of supervisors in each department who failed to submit papers on time, and identify the three departments with the highest percentages. The total student-to-faculty ratio in these departments must not exceed 1:15.

[0039] (1) Main problem: Calculate the proportion of supervisors in each department who did not submit papers on time, and find the three departments with the highest proportions, while requiring that the total student-to-faculty ratio of these departments does not exceed 1:15.

[0040] Analysis: It requires handling three core elements: ratio calculation, conditional filtering, and sorting.

[0041] Sub-problem 1: Calculate the proportion of supervisors who did not submit papers on time in departments with a student-to-faculty ratio of ≤1:15.

[0042] Sub-problem 1.1: Selecting departments that meet the student-to-faculty ratio standard (student-to-faculty ratio ≤ 1:15).

[0043] Sub-problem 1.2: Identify personnel who fail to submit on time.

[0044] Analysis: This issue involves an exclusive condition. The paper submission status may have multiple statuses such as "submitted on time", "submitted late", and "not submitted". The "submission status NOT LIKE%submitted on time%" should be used to cover all non-compliance situations.

[0045] Sub-problem 1.3: Calculate the percentage of students who did not submit on time by department.

[0046] Sub-problem 2: Select the top three in descending order of proportion.

[0047] (2) Integrate the SQL of each sub-question to form a complete SQL that answers the main question.

[0048] Example 2: What is the gender of the youngest customer who opened an account at the branch with the lowest average salary? (1) Main question: What is the gender of the youngest customer who opened an account at the branch with the lowest average salary? Analysis: The question asks for "gender," which appears in the "client" table. This will be used as the output column to select the youngest client from the row with the lowest average salary.

[0049] Sub-question 1: The youngest customer in the branch with the lowest average salary? Analysis: As indicated, salary information can be obtained using "A11" from the "district" table, and the youngest customer can be retrieved using the "birth_date" column from the "client" table. The entries between these two tables can be joined using an INNER JOIN with the district_id column.

[0050] Sub-question 1.1: Which branch has the lowest average salary? Analysis: The rows with the lowest average wages can be obtained by sorting by "A11" in ascending order and selecting the first one. Column "A11" cannot be empty, so there is no need to add an "IS NOT NULL" filter.

[0051] (2) The SQL of each sub-problem is gradually integrated and simplified into the SQL of the whole problem.

[0052] 4. Verification and Correction Field Existence Check: Confirm that all used fields exist in the table following the FROM statement; Wildcard check: Chinese conditions must contain two wildcards; Backticks check: Check if special field names are correctly escaped.

[0053] 5. Finally, output the SQL statement.

[0054] Step 5: Execute the SQL. To prevent the query from running for a long time and ensure program responsiveness, this invention includes an additional timeout period. If the query completes within the timeout period, the results and column names are returned; if it times out, None is returned along with a timeout message; if other exceptions occur, an error message is returned.

[0055] Step Six: Disambiguation. In Step Four, if an SQL execution error occurs, this invention designs two algorithms, semantic matching and fuzzy matching, as shown in Tables 5 and 6, to modify the field values ​​in the SQL statement that may have ambiguous matches.

[0056] Table 5 Semantic Matching Algorithms

[0057] Table 6 Fuzzy Matching Algorithm

[0058] Step Seven: Result Analysis and SQL Error Correction. After the generated SQL is executed successfully, this invention will generate a data analysis report based on the query results. If the generated SQL still fails after the referencing and disambiguation step, this invention will analyze the error message and provide a newly generated SQL statement accordingly.

[0059] First, a prompt word template is selected based on the given language. The model's role is then defined using `system_prompt`; in this module, the model is configured as a data analysis expert skilled in answering user questions and performing data analysis. Next, the `instruction` specifies the model's task: determining whether the provided SQL statement meets the requirements of the user-specified question and whether the execution was successful. If successful, an analysis is generated based on the execution result; otherwise, the SQL query is regenerated based on the error message. Finally, `user_prompt` provides the user's question, the SQL statement to be evaluated, and the execution result.

[0060] Step 8: Visual Chart Analysis. Based on the successfully executed SQL query results, corresponding chart analyses are automatically generated to help users quickly understand the data distribution.

[0061] like Figure 5As shown, this module uses Pandas for data parsing and combines Matplotlib and NumPy for visualization. This module can automatically identify data types (numerical, categorical, and time series) and generate the most suitable data visualization charts to help users quickly understand data distribution. For numerical data, this invention uses histograms and line charts for visualization; for categorical data, this invention provides bar charts and pie charts; if the dataset contains time series fields (such as timestamps and dates), this module will automatically select a numerical field and draw a time series line chart; when the dataset contains two or more numerical fields, this module can generate a scatter plot.

[0062] Examples of complex queries solved by this invention include: Figure 6 As shown, the key technical points are: 1. A mind chain prompt design that combines coarse-grained and fine-grained approaches. This invention guides large-scale models to convert natural language to structured query language (NL2SQL) by designing a coarse-grained and fine-grained prompting word engineering approach. The coarse-grained thinking chain provides an overall query strategy, while the fine-grained thinking chain employs a "divide and conquer" strategy to break down and reassemble complex queries. Compared to existing methods such as CHASE-SQL, which only use parallel thinking chains without integration, this invention, through the synergistic effect of two-level thinking chains, retains the clarity of the overall process while enhancing the ability to handle details. This method significantly improves the ability of large-scale models to handle complex query tasks, generating SQL statements with clear logic and high accuracy, solving the problem that existing prompting word methods cannot effectively handle multi-condition, cross-table, or computational queries.

[0063] 2. Introduce a time-aware and entity-matching module to handle fuzzy user expressions. This invention utilizes a large model to transform ambiguous time expressions in user questions into precise time ranges, extracts entity information, and matches it to database fields. By combining this with a BERT model to calculate entity semantic similarity, it achieves high-accuracy field value localization. This significantly improves the system's ability to understand and convert ambiguous or vague expressions in natural language, making the NL2SQL system more suitable for unstructured or ambiguous user queries in real-world enterprise environments.

[0064] 3. A structured suggestion mechanism for pattern links was designed. This invention designs the M_schema structured metadata representation, automatically generating a comprehensive database description including table structure, primary keys, foreign keys, field types, and sample data, providing clear and parsable input for large models. Compared to traditional methods that only provide the basic table structure, this invention introduces detailed metadata (such as field default values ​​and sample data) through M_schema, reducing ambiguity when the model handles similar columns. The structured schema linking output provides higher-quality contextual information, providing strong support for subsequent SQL generation steps and improving the correctness and stability of generated SQL statements.

[0065] 4. A post-processing mechanism for disambiguation of pronouns was introduced. This invention designs a referencing disambiguation module that combines a semantic matching algorithm (based on semantic vector similarity) and a fuzzy matching algorithm (based on string matching) to automatically correct errors in SQL statements caused by ambiguity in field values. When SQL execution fails, the system automatically invokes both semantic matching and fuzzy matching algorithms to re-identify and replace potentially ambiguous field values. This mechanism significantly enhances the system's robustness to non-standard and ambiguous field values ​​in real-world databases, improves the success rate of SQL statement execution in various database environments, and is an important supplement to traditional static SQL generation techniques. Compared to traditional NL2SQL methods that lack error correction mechanisms, this invention, through the combination of two algorithms, can automatically repair SQL execution failures. For example, when the field value entered by the user does not completely match the actual value in the database, this module can find the correct corresponding item through semantic similarity, which is superior to systems that rely solely on predefined rules.

[0066] In summary, this invention takes into account the user's ambiguous expression and the ambiguity of field values ​​in the database that may be encountered in the practical application of NL2SQL, and combines coarse-grained and fine-grained thinking chains to ensure the generation of high-quality SQL query statements for large models.

[0067] In another embodiment, the present invention provides a computer-readable storage medium storing a computer program that causes a computer to execute the prompt word engineering-based natural language to structured query language conversion method of the foregoing embodiments.

[0068] In another embodiment, the present invention proposes an electronic device, including: a memory, a processor, and a computer program stored in the memory and executable on the processor. When the processor executes the computer program, it implements the natural language to structured query language conversion method based on prompt word engineering of the foregoing embodiment.

[0069] In the embodiments disclosed in this application, a computer storage medium may be a tangible medium that may contain or store programs for use by or in conjunction with an instruction execution system, apparatus, or device. The computer storage medium may include, but is not limited to, electronic, magnetic, optical, electromagnetic, infrared, or semiconductor systems, apparatus, or devices, or any suitable combination of the foregoing. More specific examples of computer storage media include electrical connections based on one or more wires, portable computer disks, hard disks, random access memory (RAM), read-only memory (ROM), erasable programmable read-only memory (EPROM or flash memory), optical fibers, portable compact disk read-only memory (CDROM), optical storage devices, magnetic storage devices, or any suitable combination of the foregoing.

[0070] Those skilled in the art will recognize that the units and algorithm steps of the various examples described in conjunction with the embodiments disclosed in this application can be implemented in electronic hardware or a combination of computer software and electronic hardware. Whether these functions are implemented in hardware or software depends on the specific application and design constraints of the technical solution. Those skilled in the art can use different methods to implement the described functions for each specific application, but such implementation should not be considered beyond the scope of this application.

[0071] The above are merely preferred embodiments of the present invention. The scope of protection of the present invention is not limited to the above embodiments. All technical solutions falling within the scope of the present invention's concept are within the scope of protection of the present invention. It should be noted that for those skilled in the art, any improvements and modifications made without departing from the principle of the present invention should be considered within the scope of protection of the present invention.

Claims

1. A method for converting natural language to structured query language based on prompt word engineering, characterized in that, Includes the following steps: Step 1: Generate a structured database M_schema based on the parameters specified by the user; Step 2: Based on the database and user questions, the large model summarizes the relevant tables and fields and outputs them in a structured format; Step 3: Convert the vague time expression in the user question into an accurate time expression, and extract the entities with specific names and meanings in the user question, and match them with the field values ​​in the database; Step 4: The large model generates SQL statements that meet the query requirements based on the user's question, the database, and the information gathered in Step 3; Step 5: Execute SQL; If an SQL execution error occurs, modify the field values ​​in the SQL statement that may have ambiguous matches; Step 6: After the SQL is executed successfully, generate a data analysis report based on the query results and visualize it; if the modified SQL still fails to execute, analyze the error message and provide the newly generated SQL statement.

2. The method for converting natural language to structured query language based on prompt word engineering as described in claim 1, characterized in that: In step 1, the structured database M_schema includes table structure, primary key, foreign key, and field examples.

3. The method for converting natural language to structured query language based on prompt word engineering as described in claim 1, characterized in that: Step 3 specifically includes: The current time and the generated database are provided to the large model. Prompt words are designed, and the large model is instructed to convert all time-related expressions in the user's question into precise time expressions including year, month, and day according to the rules in the prompt words. Entities in the question are extracted, and the tables and fields that the entities may exist in the database are found. Finally, the corresponding entity-table-field information is organized into JSON format and returned.

4. The method for converting natural language to structured query language based on prompt word engineering as described in claim 3, characterized in that: In step 3, for the entities extracted from the question, BERT is used for semantic encoding, and the cosine similarity between them and the semantic vectors of each entity in the entity database is calculated to obtain the final matching result.

5. The method for converting natural language to structured query language based on prompt word engineering as described in claim 1, characterized in that: Step 4 specifically includes: The user's question, the database, and the information gathered in step 3 are used as inputs, and thought chain prompts are designed to guide the large model to generate SQL that satisfies the query task.

6. The method for converting natural language to structured query language based on prompt word engineering as described in claim 5, characterized in that: The design of the thought chain includes: First, check if the question contains exclusive conditions, and extract the conditions according to the description in the user's question; During the structure mapping and condition checking process, the primary key and foreign key connection methods are determined according to the database structure; the database fields corresponding to each condition in the user's question are confirmed, and for exclusive conditions, the negation is performed first before field matching; the sample data is compared to verify whether the filtered values ​​are semantically similar. During SQL construction, LIKE is used for fuzzy matching of conditions and judgments; SELECT only includes necessary fields; LIKE and NOT LIKE are preferred for all condition judgments; in the exclusiveness check table, negative conditions are in the form of NOT LIKE plus a positive term, time conditions are in the form of LIKE plus year, and blank fields are wrapped in backticks.

7. The method for converting natural language to structured query language based on prompt word engineering as described in claim 1, characterized in that: In step 5, a timeout is set when executing the SQL. If the query completes within the timeout period, the result and column names are returned; if the timeout occurs, None is returned along with a timeout message; if other exceptions occur, an error message is returned.

8. The method for converting natural language to structured query language based on prompt word engineering as described in claim 1, characterized in that: Step 6 specifically includes: First, select a prompt word template based on the given language, and set the model as an expert for answering user questions and performing data analysis through system_prompt; then, specify the task for the model in instruction, determine whether the provided SQL statement meets the requirements of the user question and whether the execution is successful. If the execution is successful, generate a data analysis report based on the execution result; if it fails, regenerate the SQL statement based on the error message; finally, provide the user question, the SQL statement to be evaluated, and the execution result in user_prompt.

9. A computer-readable storage medium storing a computer program, characterized in that, The computer program causes the computer to execute the natural language to structured query language conversion method based on prompt word engineering as described in any one of claims 1-8.

10. An electronic device, characterized in that, include: The memory, the processor, and the computer program stored in the memory and executable on the processor, wherein when the processor executes the computer program, it implements the natural language to structured query language conversion method based on prompt word engineering as described in any one of claims 1-8.