Electric power field Text2SQL (Structured Query Language) generation method based on structure control and feedback enhancement

By constructing a multi-perspective driven Prompt module and a structure-driven multi-SQL generation mechanism, combined with power semantics and historical feedback, the problem of automatic generation of natural language to SQL commands in power business scenarios was solved, achieving efficient and stable query generation and execution, and adapting to various power database structures.

CN121833753APending Publication Date: 2026-04-10SOUTHERN POWER GRID DIGITAL GRID RESEARCH INSTITUTE CO LTD +1
View PDF 0 Cites 0 Cited by

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2025-12-19
Publication Date
2026-04-10

AI Technical Summary

Technical Problem

Existing Text2SQL methods face challenges in power business scenarios, such as complex semantics, strong structural differences, unstable query generation quality, and lack of execution feedback, making it difficult to achieve automatic generation and efficient querying of natural language to SQL commands.

Method used

A multi-perspective driven Prompt construction module is constructed, which combines a structure-driven multi-SQL generation mechanism with a structure-semantic fusion reordering method. Through semantic encoding, schema alignment and historical execution feedback records, diverse and highly adaptable SQL candidate statements are generated, and the model adaptability is optimized through feedback loop.

Benefits of technology

It significantly improves the intelligent query capabilities of the power database in multi-task and multi-structure scenarios, achieving query generation with accurate semantic understanding, flexible structure control, and high execution feasibility, and supporting cross-scenario adaptability and stability.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN121833753A_ABST
    Figure CN121833753A_ABST
Patent Text Reader

Abstract

The invention relates to an electric power field Text2SQL (Structured Query Language) generation method based on structure control and feedback enhancement, which focuses on the problems of weak structure adaptability, low semantic matching degree, poor execution stability and the like in an electric power field Text2SQL task. The method comprises the following steps: firstly, constructing a multi-view driven Prompt construction module, and fusing electric power query semantic coding, an electric power database Schema structure and historical execution feedback to generate a Prompt example set with semantic consistency and structure controllability; secondly, designing a structure-driven multi-SQL generation module, generating a plurality of SQL candidates with consistent semantics and various structures in combination with a temperature regulation and structure template guide mechanism, and meanwhile, ensuring the effectiveness of a candidate set in cooperation with structure legality detection and a conflict suppression strategy; and finally, providing a structure-semantic fusion driven SQL reordering method, performing feature extraction and score fusion from three dimensions of structure similarity, semantic consistency and execution feasibility, and selecting an optimal SQL as a final query instruction. An execution result feedback chain mechanism is constructed, an example pool and a Prompt construction strategy are continuously optimized, and a self-adaptive closed-loop generation system is formed.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the fields of natural language processing and database querying, and in particular to a Text2SQL generation method for the power industry based on structure control and feedback enhancement. Background Technology

[0002] With the continuous advancement of digitalization, informatization, and intelligentization in power systems, large-scale structured databases are widely integrated into dispatch control systems, power operation and maintenance platforms, and intelligent management terminals to record massive amounts of business data, including load curves, equipment status, operation logs, and fault alarms. In daily operation and maintenance, dispatch assistance, and operational status analysis, relevant personnel urgently need to query target information using natural language, thereby significantly simplifying the complex SQL command writing process and improving system availability and human-computer interaction efficiency. Therefore, the method of automatically converting natural language queries into structured SQL statements (i.e., Text2SQL) has become a crucial technology supporting intelligent power systems.

[0003] While existing Text2SQL methods have made some progress in tasks such as general question answering and open-domain knowledge bases, their direct application in power business scenarios still faces several key challenges. First, power business semantics are complex and structurally diverse: power natural language queries often involve specific business entities (such as "substation," "photovoltaic field," and "power anomaly"), indicator limitations (such as "maximum load" and "number of consecutive abnormal days"), and dual constraints of time and space, resulting in diverse query semantics and significant structural differences. Second, power database table structures are diverse and frequently change across scenarios: the table names, field names, or primary key organization of the same business may be completely different in the scheduling platform and edge terminals, and traditional Prompt or template mechanisms have poor migration and generalization capabilities under different structural conditions. Third, query generation quality has high requirements for execution stability: in scheduling or operation and maintenance scenarios, if the generated SQL has field errors, logical deviations, or cannot be executed, it will directly affect data correctness and system stability. Existing methods lack an execution feedback loop design, making robust optimization difficult.

[0004] Therefore, there is an urgent need to design a structural diversity adaptation and execution feedback enhancement mechanism for power business, which can realize the automatic generation of natural language to SQL commands, with the characteristics of accurate semantic understanding, flexible structural control and high execution feasibility, adapt to multiple types of power databases and have adaptive learning capabilities, so as to effectively support the intelligent query and interaction needs of power information systems. Summary of the Invention

[0005] Purpose of the Invention: To address issues such as inconsistent structural expression, insufficient semantic generalization ability, and lack of execution result feedback in natural language queries for power business applications, this invention discloses a Text2SQL generation method for the power sector based on structural control and feedback enhancement. By constructing a multi-perspective driven Prompt constructor module, combined with a structure-driven multi-SQL generation mechanism and a structure-semantic fusion reordering method, this invention achieves diverse adaptation of query structures, efficient coverage of semantic expression, and controllable optimization of execution results, significantly improving the intelligent query capabilities and practical deployment adaptability of power databases in multi-task and multi-structure scenarios.

[0006] Technical Solution: This invention discloses a Text2SQL generation method for the power industry based on structural control and feedback enhancement, comprising the following steps: S1 constructs a multi-dimensional Prompt awareness module for the power industry. By combining semantic encoding of natural language queries for power business, alignment with the power database schema structure, and historical execution feedback records, it establishes a Prompt example library for subsequent generation tasks. This module effectively improves the relevance and execution feasibility of the power business constructed by the Prompt, achieving structure awareness and feedback-driven semantic enhancement, and supporting the generalization ability and stability of downstream SQL generation tasks in the power industry. The specific implementation steps are as follows: S11 first performs natural language query parsing and vector encoding to obtain the natural language query input by the user. The semantic feature vector is obtained by embedding it using the semantic pre-trained model BERT: At the same time, the key entities in the query (such as substations, time, indicators) are linked to the fields in the power database using schemalinking to form a joint representation of the current query. S12 implements semantic-structural-feedback ternary encoding of historical samples, and constructs a sample set of historical query-SQL pairs and their execution feedback; S13 calculates the current query. With all historical samples The matching similarity score is calculated using the following triple matching strategy:

[0007] in, Indicates cosine similarity; For weighted parameters, satisfying If a certain item is missing (such as the structure vector), its corresponding item can be set to 0. All historical samples are then sorted... The scores are sorted, and the top-K highly relevant examples are selected. In S14, the filtered example pairs are organized according to the standard Prompt format. By introducing execution success feedback information, the weight of effective samples is increased in the similarity ranking, thereby constructing a high-quality example set that is semantically relevant, structurally matched, and execution stable, providing precise guidance for the subsequent generation process.

[0008] S2, based on the selected feedback-aware examples, constructs a multi-perspective driven Prompt construction module. Through multiple strategies such as structural perturbation enhancement, sequence reorganization, and connection template normalization, the Prompt is constructed and encoded, effectively improving the diversity, generalization ability, and generation guidance accuracy of the input Prompt, providing controllable and rich conditional inputs for downstream SQL generation tasks. The specific implementation steps are as follows: S21 Example Template Formatting and Schema Embedding Normalization, for the example set obtained in step S1 First, standardize the format template; S22 To improve the generalization ability of Prompt to various input distributions, the following three types of enhanced perturbation strategies are designed to change the construction form of Prompt examples, forming multiple Prompt versions. Specifically: (1) Example order perturbation; (2) Structural statement rewriting perturbation; (3) Schema prefix perspective reconstruction. At the same time, the Schema information is placed before the Prompt to strengthen the structural awareness, and finally multiple Prompt versions are constructed by combining them. Used for diverse generation; S23 for each Prompt version constructed GPT encoding is used; at the same time, control parameters are injected into subsequent generation steps, including: 1) temperature parameters. 1) Controlling the diversity of sampling; 2) Top-k cutoff threshold 3) Prompt version tag: Control the candidate range; This allows the model to distinguish between different input configurations. Ultimately, it forms a set of encoded Prompt control instructions.

[0009] S3, based on the multiple versions of the Prompt constructed by S2, builds a structure-driven multi-SQL generation module. Combining a temperature regulation mechanism, a structure template guidance strategy, and a structure conflict detection mechanism, it generates multiple SQL candidate statements with syntactic validity and semantic consistency. The specific implementation steps are as follows: S31 uses the multi-version Prompt input set obtained in S2. The conditions are sequentially input into GPT to generate a candidate SQL set. S32 generates each SQL statement It is parsed into an Abstract Syntax Tree (AST) structure; at the same time, a structure template analysis function is used. Extract its normalized structural form; then, calculate the coverage frequency of each structural template in the generated result to ensure that the structural templates are evenly distributed. S33 for each candidate SQL Introducing structural legitimacy detection and conflict suppression strategies: 1) Field reference validity check: Ensure that all field names appear in the database schema; 2) Clause combination legality rules: For example, the combination of SELECT-FROM-WHERE-GROUP BY-HAVING statements should satisfy the logical order; 3) Structural conflict detection: Avoid generating logically conflicting SQL statements; For invalid SQL statements, they are removed from the candidate set or handed over to the structure repair module for processing, forming the final executable candidate set; S34 In order to quantify the structural diversity and coverage of the generated SQL set, diversity measurement and structural coverage calculation are performed. First, the following two indicators are introduced: structural coverage (SC) and structural balance (SE). If SC or SE is too low, it can be fed back to S2 to adjust the Prompt construction strategy, forming a structural adjustment closed loop.

[0010] The S4 design structure – a semantic fusion-driven SQL candidate reordering method – extracts, fuses, scores, and ranks multi-dimensional features from legal executable candidate SQLs from S3 to select the target SQL with the highest score, semantic alignment, and reasonable structure. The specific implementation steps are as follows: S41 for each candidate SQL First, parse its abstract syntax tree. This is converted into a hierarchical structure tensor or graph representation, and then its structure embedding vector is extracted using the Tree-LSTM structure encoder; simultaneously, the target structure vector generated by the Schema linking module in step S1 is called. As a reference standard; S42 uses cosine similarity to calculate the similarity score between the candidate structure and the target structure; simultaneously, it extracts the set of clauses appearing in the SQL. , and the set of target structure clauses The clause overlap ratio (COR) is calculated by comparison; the final structural score is a linearly weighted result. S43 To determine whether candidate SQL faithfully expresses the semantics of user queries in the power sector, a natural language reverse interpretation mechanism is used to generate semantic description text corresponding to the candidate SQL; at the same time, target slots (such as entities, values, time, etc.) are extracted from the query, the slot matching rate is calculated and incorporated into the total score; S44 executes SQL candidates and extracts statistical features for confidence modeling; S45 constructs a ranking score function by integrating the three types of scores for each candidate SQL statement, sorts all candidate SQL statements from highest to lowest total score, and directly selects the one with the highest score as the final SQL output.

[0011] S5 builds an automatic execution interface module to generate the sorted optimal SQL. The data is sent to the target database for execution, and the returned results are retrieved and normalized. The specific implementation steps are as follows: S51 first connects to the target database. Call the unified interface to send SQL statements Perform an actual query; S52 standardizes the returned results, including: (1) Convert the table format to a unified JSON or key-value pair representation; (2) Parse the field name and data type, and construct the type description; (3) If the result is empty or the proportion of NULL is high, record the abnormal execution signal for feedback (see S6).

[0012] S6 constructs a historical feedback chain reinforcement module to dynamically update the example pool and the Prompt construction mechanism, thereby improving the model's long-term adaptability in power industry database scenarios. The specific implementation steps are as follows: S61 Based on the execution results, construct an execution feedback signal flag set: (1) Validity signal : Whether the SQL was executed successfully; (2) Information density index ; (3) User ratings or interaction signals: manual confirmation of semantic alignment (e.g., clicking "Is it correct?"); Write the above signals into the historical feedback table: ; S62 When a query result is marked as high quality (e.g.) and ), then the pair The sample index weight vector is written to the sample pool for sampling during the subsequent Prompt construction phase (S2). The sample index weight vector is also updated. : in, The sorted scores in S4; The memory decay parameter is set to 0.5 in this invention; After S63 aggregates historical execution records, it automatically adjusts the Prompt construction strategy for task types that fail frequently or perform poorly in specific structures. This includes schema masking enhancement, sparse structure templates, and priority example enhancement: increasing the probability of sampling examples that perform well in similar tasks.

[0013] A feedback-guided adaptive Prompt optimization loop is formed.

[0014] The beneficial effects of this invention are as follows: Addressing key issues such as significant differences in structural expression, weak semantic generalization ability, and insufficient execution stability in natural language queries for power business, this invention proposes a Text2SQL generation method with capabilities for adapting to structural diversity, enhancing candidate results, and providing feedback-guided optimization. It constructs a power intelligent query generation system with structural control, semantic generalization, and feedback loop capabilities. Specifically, to address the problems of complex task types and inconsistent structural styles in power natural language queries, this invention first constructs a multi-perspective driven Prompt construction module. This module integrates power semantic categories, field features, and historical interaction feedback information. Through structural perturbation, order rearrangement, and template evolution, it generates diverse and highly adaptable input prompt structures, significantly improving the model's structural generalization ability for multi-task scenarios. Secondly, to address the lack of coverage in candidate generation under complex structures, this invention proposes a structure-driven multi-SQL generation mechanism. This mechanism employs a combination of structure-controlled template guidance and semantic preservation strategies to construct multiple candidate SQLs with differentiated structures but consistent semantics. This supports the coverage and parsing of complex query structures in power databases, such as cross-table queries, nested queries, and hierarchical constraints. Finally, addressing the issues of execution feasibility and semantic robustness of the generated statements, this invention introduces a structure-semantic fusion-driven re-ranking mechanism. Combining semantic matching degree, structural legality, and execution result feedback, a multi-indicator fusion ranking strategy is constructed to evaluate the credibility and select the best candidate SQL set, thereby improving the stability and practical executability of the generated query results. Furthermore, this invention continuously builds a feedback chain mechanism, dynamically integrating the execution results into the example set and the Prompt generation strategy, achieving a closed-loop adaptive optimization of the model. This demonstrates strong deployment and scenario adaptability, providing crucial support for complex business scenarios such as power dispatching, operation and maintenance analysis, and data retrieval. Attached Figure Description

[0015] Figure 1 This is a flowchart of the method of the present invention; Figure 2 This is a schematic diagram of the structure-driven multi-SQL generation module designed in this invention; Figure 3 This is a schematic diagram of the fusion sorting and scoring structure designed in this invention. Detailed Implementation

[0016] The specific embodiments of the present invention will now be described in conjunction with the accompanying drawings to enable those skilled in the art to better understand the present invention.

[0017] like Figure 1 As shown, the specific process of the present invention includes the following steps: S1 constructs a multi-dimensional Prompt awareness module for the power industry. By combining semantic encoding of natural language queries for power business, alignment with the power database schema structure, and historical execution feedback records, it establishes a Prompt example library for subsequent generation tasks. This module effectively improves the relevance and execution feasibility of the power business constructed by the Prompt, achieving structure awareness and feedback-driven semantic enhancement, and supporting the generalization ability and stability of downstream SQL generation tasks in the power industry. The specific implementation steps are as follows: S11 first performs natural language query parsing and vector encoding to obtain the natural language query input by the user. The semantic feature vector is obtained by embedding it using the semantic pre-trained model BERT: Simultaneously, schema-linking operations are performed on key entities in the query (such as substations, time, and indicators) and fields in the power database. Assume the power database structure is as follows:

[0018] in, For the first A power business table, For the first Each field. The BM25 model is used to calculate the matching score between the natural language and schema fields. Encode the matching fields as structured embeddings:

[0019] Finally, the combined representation of the current query is formed: ; S12 implements semantic-structural-feedback ternary encoding of historical samples to construct a sample set of historical query-SQL pairs and their execution feedback:

[0020] in, Indicates the first One natural language query, For its corresponding SQL statement, This indicates the feedback of the execution result. The following processing steps are performed respectively: 1) Natural Language Encoded as 2) SQL statements It is converted into an Abstract Syntax Tree (AST) and encoded into vectors using a structure-aware model. 3) Execution feedback It is directly used as a scalar input. Ultimately, each historical sample is uniformly represented as: ; S13 calculates the current query. With all historical samples The matching similarity score is calculated using the following triple matching strategy: in, Indicates cosine similarity; For weighted parameters, satisfying If a certain item is missing (such as the structure vector), its corresponding item can be set to 0. All historical samples are then sorted... Sort by score and select the Top-K highly relevant examples; S14 Organizes the filtered sample pairs according to the standard Prompt format: Database structure: Table: load_curve(time, station_id, power) Table: transformer_status(station_id, temp, state) Q: How can I find the maximum load of a substation in July? A: SELECT MAX(power) FROM load_curve WHERE station_id = 'A' AND timeBETWEEN ... Q: How to find the number of transformers that were malfunctioning in 2023? A: SELECT COUNT(*) FROM transformer_status WHERE state = 'abnormal'AND time BETWEEN ... This example sequence is fed into a large language model for SQL generation. Successful execution feedback is introduced. The information enhances the weight of effective samples in similarity ranking, thereby constructing a high-quality set of examples that are semantically relevant, structurally matched, and execution-stable, providing precise guidance for the subsequent generation process.

[0021] S2, based on the selected feedback-aware examples, constructs a multi-perspective driven Prompt construction module. Through multiple strategies such as structural perturbation enhancement, sequence reorganization, and connection template normalization, the Prompt is constructed and encoded, effectively improving the diversity, generalization ability, and generation guidance accuracy of the input Prompt, providing controllable and rich conditional inputs for downstream SQL generation tasks. The specific implementation steps are as follows: S21 Example Template Formatting and Schema Embedding Normalization, for the example set obtained in step S1 First, standardize the format template: 1) For all questions The text describes how to label and instruct inputs according to a unified structure, creating a template input.

[0022] 2) SQL statements Standardized line breaks and indentation, field name cleanup, and other unified processing were added; 3) Import the current database schema structure Encoded as a structural context vector Attached before the Prompt input via a connection: ; S22 To improve the generalization ability of Prompt to various input distributions, the following three types of enhanced perturbation strategies are designed to change the construction form of the Prompt example, resulting in multiple Prompt versions. Details are as follows: (1) Example sequence perturbation For example collection Perform random order rearrangement to generate multiple permutations, forming Prompt sequences under different orders:

[0023] (2) Structural statement rewriting disturbance right Perform structural equivalence rewriting (such as changing the JOIN method or replacing subqueries with GROUP BY) to generate a replacement version. Enhance structural diversity: SELECT A FROM T1, T2 WHERE T1.a = T2.b⇒SELECT A FROM T1 JOIN T2 ONT1.a = T2.b Rewriting is achieved through rule matching, ensuring that the semantics remain unchanged while the structure is different.

[0024] (3) Schema prefix perspective reconstruction By placing the schema information before the prompt, we can enhance our understanding of the structure and ultimately combine and construct multiple prompt versions. Used for diverse generation; S23 for each Prompt version constructed GPT encoding is used: Simultaneously, control parameters are injected into subsequent generation steps, including: 1) Temperature parameters 1) Controlling the diversity of sampling; 2) Top-k cutoff threshold 3) Prompt version tag: Control the candidate range; This allows the model to distinguish between different input configurations. Ultimately, this results in a set of encoded Prompt control instructions.

[0025] Each item serves as an input entry point for the subsequent SQL generation module (S3).

[0026] S3, based on the multiple versions of the Prompt constructed by S2, builds a structure-driven multi-SQL generation module. Combining a temperature regulation mechanism, a structure template guidance strategy, and a structure conflict detection mechanism, it generates multiple SQL candidate statements with syntactic validity and semantic consistency, such as... Figure 2 As shown. The specific implementation steps are as follows: S31 uses the multi-version Prompt input set obtained in S2. The conditions are sequentially input into GPT to generate a candidate SQL set:

[0027] in, For the first One Prompt encoding; Temperature parameters are used to adjust the flatness of the sampling distribution and improve diversity. Set a top-k truncation threshold to avoid low-probability token pollution; The maximum number of SQL candidates generated is [number]. ; S32 generates each SQL statement It is parsed into an Abstract Syntax Tree (AST) structure:

[0028] Simultaneously using structural template analysis functions Extract its normalized structural form:

[0029] in This indicates a structure template tag. This is a predefined set of structure templates. Next, we will calculate the coverage frequency of each structure template in the generated results:

[0030] Ensure that the structural templates are evenly distributed; S33 for each candidate SQL Introducing structural legitimacy detection and conflict suppression strategies: 1) Field reference validity check: Ensure that all field names appear in the database schema; 2) Clause combination legality rules: For example, the combination of SELECT-FROM-WHERE-GROUP BY-HAVING statements should satisfy the logical order; 3) Structural conflict detection: Avoid generating logically conflicting SQL statements, such as: The SELECT statement uses an aggregate function, and the GROUP BY statement is missing a field. The HAVING statement uses a non-aggregate field; The SELECT field in the subquery is not accessed by the main query.

[0031] For invalid SQL statements, they are either removed from the candidate set or handed over to the structure repair module for processing, forming the final executable candidate set:

[0032] S34 To quantify the structural diversity and coverage of the generated SQL sets, and to perform diversity measurement and structural coverage calculation, the following two metrics are first introduced: Structural Coverage (SC): Represents the ratio of the actual number of structural templates to the total size of the template set;

[0033] Structural balance (SE): The balance of the distribution of structural templates is measured using information entropy.

[0034] If SC or SE is too low, it can be fed back to S2 to adjust the Prompt construction strategy, forming a closed loop of structural adjustment.

[0035] The S4 design structure – a semantic fusion-driven SQL candidate re-ranking method – extracts, fuses, scores, and ranks multi-dimensional features from legal executable candidate SQLs from S3 to select the target SQL with the highest score, semantic alignment, and reasonable structure. Figure 3 As shown. The specific implementation steps are as follows: S41 for each candidate SQL First, parse its abstract syntax tree. It is then converted into a hierarchical structure tensor or graph representation, and its structure embedding vector is extracted using the Tree-LSTM structure encoder:

[0036] Simultaneously, the target structure vector generated by the Schema linking module in step S1 is invoked. As a reference standard; S42 uses cosine similarity to calculate the similarity score between the candidate structure and the target structure:

[0037] Simultaneously extract the set of clauses appearing in the SQL. , and the set of target structure clauses Compare and calculate the clause overlap ratio (COR):

[0038] The final structural score is a linearly weighted result:

[0039] The weighting factor is set to 0.7 in this invention; S43 To determine whether the candidate SQL faithfully expresses the semantics of user queries in the power sector, a natural language reverse interpretation mechanism is used to generate semantic description text corresponding to the candidate SQL. The specific process is as follows: 1) SQL → NL Reverse Interpretation Generation: Generating natural language descriptions of candidate SQL statements using the GPT model:

[0040] 2) Semantic embedding matching: matching the original query With Explanatory Text Separate encodings:

[0041] Calculate the semantic consistency score:

[0042] Simultaneously, target slots (such as entities, values, and times) are extracted from the query, the slot matching rate is calculated, and incorporated into the total score.

[0043] The weighting factor is set to 0.8 in this invention; S44 executes SQL candidates and extracts statistical features for confidence modeling. For each candidate SQL... Perform the query directly on the real database D and record the following metrics: Was the execution successful? (Indicates success) Query returned rows , number of columns ; Execution time Null value ratio .

[0044] Standardized scoring model Based on all features, the execution confidence score is output:

[0045] in The query intent type tags (such as count, aggregation, filtering, etc.) are provided by the system's front-end intent recognition module. S45 constructs a ranking score function by combining three types of scores for each candidate SQL statement:

[0046] The weighting coefficient is set to 0.4 in this invention; all candidate SQL statements are sorted from highest to lowest total score, and the one with the highest score is directly selected as the final SQL output: This SQL statement will be passed to the S5 execution phase as the final query result.

[0047] Symbol explanation:

[0048] S5 builds an automatic execution interface module to generate the sorted optimal SQL. The data is sent to the target database for execution, and the returned results are retrieved and normalized. The specific implementation steps are as follows: S51 first connects to the target database. Call the unified interface to send SQL statements Perform the actual query. To adapt to various database systems (such as MySQL, PostgreSQL, SQLite), the interface is uniformly encapsulated as follows:

[0049] in, This represents a unified, encapsulated database execution function interface; the call returns the raw execution results, including data tables, execution time, warning messages, etc. S52 standardizes the returned results, including: (1) Convert the table format to a unified JSON or key-value pair representation; (2) Parse the field names and data types, and construct the type description; (3) If the result is empty or the proportion of NULL is high, record the abnormal execution signal for feedback (see S6). The final result is in the following format: { "query_id": q, SQL: "SELECT ...", "result": { "columns": ["station_id", "max_power"], "rows": [["A001", 1350.5], ["B207", 1278.2]], "meta": {"exec_time": 0.12, "null_ratio": 0.0} } }

[0050] S6 constructs a historical feedback chain reinforcement module to dynamically update the example pool and the Prompt construction mechanism, thereby improving the model's long-term adaptability in power industry database scenarios. The specific implementation steps are as follows: S61 Based on the execution results, construct an execution feedback signal flag set: (1) Validity signal : Whether the SQL was executed successfully; (2) Information density index ; (3) User ratings or interaction signals: manual confirmation of semantic alignment (e.g., clicking "Is it correct?"); Write the above signals into the historical feedback table: ; S62 When a query result is marked as high quality (e.g.) and ), then the pair The sample index weight vector is written to the sample pool for sampling during the subsequent Prompt construction phase (S2). The sample index weight vector is also updated. :

[0051] in, The sorted scores in S4; The memory decay parameter is set to 0.5 in this invention; After S63 aggregates historical execution records, it automatically adjusts the Prompt construction strategy for task types that fail frequently or have poor performance in specific structures. (1) Enhanced Schema Masking: Add redundant hints to specific schema fields; (2) Structural template dilution: Reduce the use of Prompt templates corresponding to failed structures; (3) Priority example boosting: Increase the probability of sampling examples that perform well in similar tasks.

[0052] A feedback-guided adaptive Prompt optimization loop is formed.

[0053] Further explanation is needed: Those skilled in the art should understand that, for the purpose of more clearly and concisely describing the technical solution of the present invention, the above embodiments employ a logical division of functional modules or units. However, in practical applications, it is not limited to strictly adhering to this division method for deployment and implementation. Depending on the specific system requirements, hardware resource configuration, or control strategy, related modules can be flexibly combined, split, replaced, or reconstructed to achieve some or all of the functions of the method described in the present invention. Therefore, the division of functional modules does not constitute a substantial technical limitation of the present invention.

[0054] It should be noted that the above embodiments are only used to illustrate the technical principles and application methods of the present invention, and are intended to provide examples rather than limit the scope of protection of the present invention. Although several preferred embodiments have been described in detail in this specification, those skilled in the art can still make various modifications, variations, or equivalent substitutions to the above technical solutions without departing from the core idea of ​​the present invention. For example, the internal control logic of the module can be adjusted, different communication mechanisms can be replaced, or the interface structure can be optimized, etc., and these adjustments all fall within the reasonable scope of extension of the present invention. Therefore, all technical changes made within the scope of the essential spirit and basic principles of the present invention should be considered to fall within the protection scope of the present invention.

Claims

1. A method for generating Text2SQL in the power sector based on structural control and feedback enhancement, characterized in that, Includes the following steps: S1: Construct a multi-dimensional perception module for the power scenario, and establish a Prompt sample library for subsequent generation tasks by combining semantic encoding of natural language queries for power business, alignment of power database schema structure and historical execution feedback records. S2: Based on S1, the Prompt is constructed and encoded through multiple strategies such as structural perturbation enhancement, sequence reorganization, and connection template normalization. A multi-perspective driven Prompt construction module is built to effectively improve the diversity, generalization ability, and generation guidance accuracy of the input Prompt, providing controllable and rich conditional inputs for downstream SQL generation tasks. S3: For the multiple versions of Prompt constructed by S2, a structure-driven multi-SQL generation module is built. Combining temperature regulation mechanism, structure template guidance strategy and structure conflict detection mechanism, multiple SQL candidate statements with syntactic validity and semantic consistency are generated. S4: Design a structure-semantic fusion-driven SQL candidate reordering method, which performs multi-dimensional feature extraction, fusion scoring and sorting on the legal executable candidate SQL from S3, in order to select the target SQL with the highest score, semantic alignment and reasonable structure. S5: Build an automatic execution interface module to send the sorted optimal SQL to the target database for execution, obtain the returned results, and perform normalization processing; S6: Construct a historical feedback chain reinforcement module to dynamically update the example pool and the Prompt construction mechanism, thereby improving the long-term adaptability of the model in the power sector database scenario.

2. The method for generating Text2SQL in the power sector based on structural control and feedback enhancement according to claim 1, characterized in that, Step S1 includes the following steps: S11 first performs natural language query parsing and vector encoding to obtain the natural language query input by the user. The semantic feature vector is obtained by embedding it using the semantic pre-trained model BERT: Simultaneously, schema linking is performed between the key entities in the query and the fields in the power database. Assume the power database structure is as follows: ;in, For the first A power business table, For the first The matching score between the natural language and schema fields is calculated using the BM25 model. Encode the matching fields as structured embeddings: Finally, the combined representation of the current query is formed: S12 implements semantic-structural-feedback ternary encoding of historical samples to construct a sample set of historical query-SQL pairs and their execution feedback. And perform the following processing respectively: 1) Natural language Encoded as 2) SQL statements It is converted into an Abstract Syntax Tree (AST) and encoded into vectors using a structure-aware model. 3) Execution feedback Directly used as a scalar input, each historical sample is ultimately represented uniformly as: S13 calculates the current query. With all historical samples The matching similarity score is calculated using the following triple matching strategy: At the same time, all historical samples were sorted according to... Sort by score and select the Top-K highly relevant examples; S14 organizes the filtered example pairs according to the standard Prompt format. By introducing information from successful execution feedback, the weight of effective samples is increased in the similarity ranking, thereby constructing a high-quality example set that is semantically relevant, structurally matched, and execution-stable, providing precise guidance for the subsequent generation process.

3. The method for generating Text2SQL in the power sector based on structural control and feedback enhancement according to claim 1, characterized in that, Step S2 includes the following steps: S21 Example Template Formatting and Schema Embedding Normalization, for the example set obtained in step S1 First, standardize the format template; S22 To improve the generalization ability of Prompt to various input distributions, the following three types of enhanced perturbation strategies are designed to change the construction form of the Prompt example, resulting in multiple Prompt versions; as follows: (1) Example sequence perturbation For example collection Perform random order rearrangement: (2) Structural statement rewriting disturbance right Perform structural equivalent rewriting: SELECT A FROM T1, T2 WHERE T1.a = T2.b⇒SELECT A FROM T1 JOIN T2 ON T1.a= T2.b; (3) Schema prefix perspective reconstruction By placing the schema information before the prompt, we can enhance our understanding of the structure and ultimately combine and construct multiple prompt versions. Used for diverse generation; S23 for each Prompt version constructed GPT encoding is used: Simultaneously, control parameters are injected into subsequent generation steps, including: 1) Temperature parameters 1) Controlling the diversity of sampling; 2) Top-k cutoff threshold 3) Prompt version tag: Control the candidate range; This allows the model to distinguish between different input configurations. Ultimately, this results in a set of encoded Prompt control instructions. .

4. The method for generating Text2SQL in the power sector based on structural control and feedback enhancement according to claim 1, characterized in that, Step S3 includes the following steps: S31 will use the multi-version Prompt input set obtained in S2. The conditions are sequentially input into GPT for condition generation: S32 processes each generated SQL statement. It is parsed into an Abstract Syntax Tree (AST) structure: Simultaneously using structural template analysis functions Extract its normalized structural form: Next, we will calculate the coverage frequency of each structural template in the generated results: Ensure that the structural templates are evenly distributed; S33 for each candidate SQL The system introduces structural validity detection and conflict suppression strategies: 1) field reference validity check; 2) clause combination validity rules; 3) structural conflict detection. For invalid SQL statements, they are removed from the candidate set or passed to the structural repair module for processing, forming the final executable candidate set. S34 To quantify the structural diversity and coverage of the generated SQL sets, and to perform diversity measurement and structural coverage calculation, the following two metrics are first introduced: Structural Coverage (SC): Represents the ratio of the actual number of structural templates to the total size of the template set; Structural balance (SE): The balance of the structural template distribution is measured using information entropy. If SC or SE is too low, it can be fed back to S2 to adjust the Prompt construction strategy, forming a closed loop of structural adjustment.

5. A method for generating Text2SQL in the power sector based on structural control and feedback enhancement according to claim 1, characterized in that, Step S4 includes the following steps: S41 for each candidate SQL First, parse its abstract syntax tree. This is then converted into a hierarchical structure tensor or graph representation, and its structure embedding vector is extracted using the Tree-LSTM structure encoder. Simultaneously, the target structure vector generated by the Schema linking module in step S1 is invoked. As a reference standard; S42 uses cosine similarity to calculate the similarity score between the candidate structure and the target structure: Simultaneously extract the set of clauses appearing in the SQL. , and the set of target structure clauses Compare and calculate the clause overlap rate (COR): The final structural score is a linearly weighted result. ; S43 is the weighting coefficient; S43 is used to determine whether the candidate SQL faithfully expresses the semantics of user queries in the power sector. A natural language reverse interpretation mechanism is used to generate the semantic description text corresponding to the candidate SQL. The specific process is as follows: 1) SQL → NL Reverse Interpretation Generation: Generating natural language descriptions of candidate SQL statements using the GPT model: 2) Semantic embedding matching: matching the original query With Explanatory Text Separate encodings: ; Calculate the semantic consistency score: Simultaneously, target slots are extracted from the query, the slot matching rate is calculated, and incorporated into the total score. ; For weighting coefficients; S44 executes SQL candidate queries and extracts statistical features for each candidate SQL query. Perform the query directly on the real database D and record the following metrics: whether the execution was successful. This indicates success; the query returned the number of rows. , number of columns Execution time Null value ratio A standardized scoring model was adopted. Based on all features, the execution confidence score is output: ; S45 constructs a ranking score function by combining three types of scores for each candidate SQL statement: Sort all candidate SQL statements from highest to lowest total score, and directly select the one with the highest score as the final SQL output: .

6. The method for generating Text2SQL in the power sector based on structural control and feedback enhancement according to claim 1, characterized in that, Step S5 includes the following steps: S51 first connects to the target database. Call the unified interface to send SQL statements For actual queries, the interface is uniformly encapsulated as follows: S52 standardizes the returned results, including: (1) converting the table format into a unified JSON or key-value pair representation; (2) parsing the field names and data types and constructing type descriptions; (3) if the result is empty or the proportion of NULL is high, recording the abnormal execution signal for feedback.

7. The method for generating Text2SQL in the power sector based on structural control and feedback enhancement according to claim 1, characterized in that, Step S6 includes the following steps: S61 Based on the execution results, construct the execution feedback signal flag set: (1) Validity signal : Whether the SQL was executed successfully; (2) Information density index (3) User ratings or interaction signals: manual confirmation of semantic alignment; Write the above signals into the historical feedback table: ; S62 When a query result is marked as high quality, that is... and Then the pair The sample data is written to the sample pool for sampling during the subsequent Prompt construction phase, i.e., step S2, and the sample index weight vector is updated accordingly. : ; After S63 historical execution records are aggregated, the Prompt construction strategy is automatically adjusted for task types that fail frequently or have poor performance in specific structures: (1) Schema masking enhancement: add redundant hints to specific schema fields; (2) Structure template dilution: reduce the use of Prompt templates corresponding to failed structures; (3) Priority example enhancement: increase the sampling probability of examples that perform well in similar tasks, forming a feedback-guided adaptive Prompt optimization loop.