Self-adaptive database query method and device, electronic equipment and storage medium
By constructing an intelligent database agent with environmental awareness and autonomous exploration capabilities, the problems of context overflow and error recovery in Text-to-SQL technology under large-scale database scenarios are solved, and high accuracy and robust SQL generation for complex queries are achieved.
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- SHENZHEN INST OF ADVANCED TECH CHINESE ACAD OF SCI
- Filing Date
- 2025-12-30
- Publication Date
- 2026-04-10
AI Technical Summary
Existing Text-to-SQL technology is prone to triggering model context window overflow in large-scale database scenarios, lacks an environment feedback mechanism, has weak error recovery capabilities, and has a high risk of generating logical errors during multi-table join queries, resulting in insufficient robustness.
We construct an intelligent database agent with environmental awareness and autonomous exploration capabilities. Through the SQL dynamic action space and execution feedback closed-loop mechanism, we realize table structure verification, logic correction and intermediate data verification, thereby improving the accuracy of SQL generation and system robustness.
Through multiple rounds of iterative optimization, high accuracy and robust SQL generation in complex query scenarios have been achieved. It has the ability to explore autonomously and dynamically correct itself, thereby improving the stability and response efficiency of the system.
Smart Images

Figure 083A7A21-ECE5-4BD7-9693-99C9DF5B65FD 
Figure 41C458A3-C61C-4C33-AE1B-DC0ABB055EF3 
Figure 55450F5D-2FA5-4B21-B298-EF65D1A9C5AF
Abstract
Description
Technical Field
[0001] This application relates to the field of data querying, and more specifically, to an adaptive database querying method, apparatus, electronic device, and storage medium. Background Technology
[0002] With the iterative evolution of Large Language Learning Machine (LLM) technology, Text-to-SQL (TTL) interaction has become a research hotspot in the field of intelligent data processing. The core of this technology aims to achieve accurate conversion from the natural language (NL) requests of non-technical users to executable Structured Query Language (SQL). From a technological evolution perspective, the mainstream paradigm of Text-to-SQL has gradually shifted from an early sequence-to-sequence (Seq2Seq) supervised learning model to a context-based learning and fine-tuning strategy based on large language models, significantly improving the generalization ability of semantic parsing.
[0003] However, existing Text-to-SQL technologies require the pre-injection of full database schema information in large-scale database scenarios, which can easily trigger model context window overflow when dealing with large-scale databases. When encountering SQL execution exceptions, they rely on static rule replacement or direct process blocking, resulting in weak error recovery capabilities and a lack of procedural grounding verification mechanisms. When handling complex queries such as multi-table joins, they adopt a "blind write" mode, which does not simulate the process of human experts verifying logic through intermediate results, leading to a high risk of illusion generation and insufficient robustness.
[0004] As can be seen from the above, there is an urgent need for an adaptive database query method to solve the above problems. Summary of the Invention
[0005] This application provides an adaptive database query method, apparatus, electronic device, and storage medium, which can construct an intelligent database agent with environmental awareness and autonomous exploration capabilities, endowing the system with decision-making and reasoning abilities, and realizing closed-loop operations of table structure verification, logic correction, and intermediate data verification; thereby improving the accuracy of SQL generation and system robustness in complex query scenarios. The technical solutions are as follows: According to one aspect of this application, an adaptive database query method is proposed, the method comprising: receiving a user's natural language query; performing initialization processing based on the user's natural language query to obtain an initialization state and a dynamic candidate pattern subset; performing a decision reasoning operation based on the initialization state and the dynamic candidate pattern subset to generate a structured query language (SQL) action, wherein the decision reasoning operation is based on the system state to generate an adapted SQL action to address information gaps or directly respond to user needs; executing the SQL action and structurally capturing the execution result of the database; controlling the iteration process based on the execution result and a termination condition until the iteration stops and the final SQL statement and query result are output.
[0006] According to one aspect of this application, an adaptive database query apparatus is proposed, the apparatus comprising a receiving unit, a processing unit, a decision reasoning unit, an execution unit, and an output unit, wherein: the receiving unit is configured to receive a user's natural language query; the processing unit is configured to perform initialization processing based on the user's natural language query to obtain an initialization state and a dynamic candidate pattern subset; the decision reasoning unit is configured to perform decision reasoning operations based on the initialization state and the dynamic candidate pattern subset to generate a structured query language (SQL) action, wherein the decision reasoning operation is based on the system state to generate an adapted SQL action to address information gaps or directly respond to user needs; the execution unit is configured to execute the SQL action and structurally capture the execution result of the database; the output unit is configured to control the iteration process based on the execution result and a termination condition until the iteration stops and then output the final SQL statement and query result.
[0007] According to one aspect of this application, an electronic device includes at least one processor and at least one memory, wherein program instructions or code are stored in the memory; the program instructions or code are loaded and executed by the processor, causing the electronic device to implement the adaptive database query method as described above.
[0008] According to one aspect of this application, a storage medium stores program instructions or code thereon, which are loaded and executed by a processor to implement the adaptive database query method as described above.
[0009] According to one aspect of this application, a computer program product includes program instructions or code stored in a storage medium. The processor of an electronic device reads the program instructions or code from the storage medium, loads and executes the program instructions or code, causing the electronic device to implement the adaptive database query method as described above.
[0010] The beneficial effects of the technical solution provided in this application are: In the above technical solutions, this application provides an adaptive database query method, apparatus, electronic device, and storage medium, relating to the field of data processing. The method includes: first, receiving a user's natural language query; then, performing initialization processing based on the user's natural language query to obtain an initialization state and a dynamic candidate pattern subset; further, performing decision-making reasoning operations based on the initialization state and the dynamic candidate pattern subset to generate a structured query language (SQL) action; further, executing the SQL action and structurally capturing the database execution results; finally, controlling the iteration process based on the execution results and termination conditions until iteration stops and the final SQL statement and query results are output. Thus, by constructing an intelligent database agent with environmental awareness and autonomous exploration capabilities, the system is endowed with decision-making reasoning abilities, achieving a closed-loop operation of table structure verification, logical correction, and intermediate data verification; thereby improving the accuracy of SQL generation and the robustness of the system in complex query scenarios. Attached Figure Description
[0011] To more clearly illustrate the technical solutions in the embodiments of this application, the accompanying drawings used in the description of the embodiments of this application will be briefly introduced below.
[0012] Figure 1 This is a schematic diagram illustrating the overall topology and functional module coupling relationship of an SQLAct database management system according to an exemplary embodiment; Figure 2 This is a flowchart illustrating an adaptive database query method according to an exemplary embodiment; Figure 3 This is a schematic diagram illustrating the principle of a two-stage dynamic pruning algorithm based on semantic relevance, according to an exemplary embodiment. Figure 4 This is a dynamic job flow logic diagram based on an execution feedback closed loop, as illustrated in an exemplary embodiment. Figure 5 This is a temporal interaction diagram illustrating the dynamic action space and state evolution according to an exemplary embodiment; Figure 6 This is a structural block diagram illustrating an adaptive database query device according to an exemplary embodiment; Figure 7 This is a structural block diagram of an electronic device according to an exemplary embodiment. Detailed Implementation
[0013] The embodiments of this application are described in detail below. Examples of these embodiments are shown in the accompanying drawings, wherein the same or similar reference numerals denote the same or similar elements or elements having the same or similar functions throughout. The embodiments described below with reference to the accompanying drawings are exemplary and are only used to explain this application, and should not be construed as limiting this application.
[0014] Those skilled in the art will understand that, unless specifically stated otherwise, the singular forms “a,” “an,” “the,” and “the” used herein may also include the plural forms. It should be further understood that the term “comprising” as used in this application means the presence of the stated features, integers, steps, operations, elements, and / or components, but does not exclude the presence or addition of one or more other features, integers, steps, operations, elements, components, and / or groups thereof. It should be understood that when we say an element is “connected” or “coupled” to another element, it can be directly connected or coupled to the other element, or there may be intermediate elements. Furthermore, “connected” or “coupled” as used herein can include wireless connections or wireless coupling. The term “and / or” as used herein includes all or any units and all combinations of one or more associated listed items.
[0015] The following is an introduction and explanation of the relevant academic background involved in this application: Current mainstream Text-to-SQL enhancement solutions can be mainly categorized into the following three types, but they still have significant limitations in terms of intelligent interaction and dynamic feedback mechanisms: 1. The Retrieval Enhancement Generation (RAG) approach retrieves historical queries, metadata, and business metrics from a vector database and injects the search results into prompts to assist SQL generation. However, this method essentially involves static knowledge injection, and the accuracy of the generated SQL is highly dependent on the timeliness and completeness of the database schema. When faced with schema changes or retrieval biases, the model lacks a mechanism to proactively initiate a "query schema" action to verify hypotheses, which can easily lead to errors in the generation logic.
[0016] 2. The pipeline-based verification solution constructs a pipeline architecture encompassing a planner, retrieval unit, generator, and validator. While it introduces syntax and permission verification, its error correction mechanism primarily relies on predefined static rules or error classifications, lacking large-scale model-level reasoning-action (ReAct) capabilities. Specifically, the system cannot simulate the dynamic thought process of a human database administrator (DBA) when encountering execution errors—"error attribution—actively probing table structure—logical correction"—leading to insufficient robustness in complex scenarios.
[0017] 3. Chain-of-Thought-based solutions, exemplified by the DIN-SQL model in academia, guide the model through step-by-step logical reasoning (such as table identification, column identification, and SQL construction) using multi-step prompting strategies. Their core limitation lies in the fact that this is a purely open-loop reasoning mode; the model is in a "blind writing" state lacking interaction and feedback from the actual database environment, and cannot correct its reasoning biases based on the execution results.
[0018] In summary, existing technologies mainly consist of open-loop generation systems or closed-loop systems based on static rules, lacking an agent mechanism with autonomous exploration capabilities and the ability to dynamically iterate and optimize based on environmental feedback. Although Text-to-SQL technology has made some progress, limited by the static generation paradigm, existing solutions still suffer from the following significant drawbacks in practical applications: 1. Existing solutions suffer from limitations due to their dependence on the context length of the database schema and their passive response mechanisms. Most existing solutions require pre-injecting database schema information into prompts. When dealing with large-scale databases containing numerous tables, this can easily lead to context overflow as the model's context window is exceeded. Furthermore, the model is in a passive state of receiving environmental information, lacking the ability to actively retrieve and acquire information about unknown or ambiguous table structures.
[0019] 2. Insufficient error recovery and logic correction capabilities. When encountering SQL execution exceptions (such as missing fields or syntax errors), existing systems mostly adopt direct process blocking or static replacement strategies based on simple rules. Due to the lack of deep semantic analysis capabilities for error logs, the system cannot dynamically reconstruct and re-plan the query logic based on the feedback information, resulting in a limited task execution success rate.
[0020] 3. Lack of a process-oriented grounding verification mechanism. Existing models tend to adopt a one-step "blind write" generation mode when handling complex queries such as multi-table joins, failing to simulate the operational process of human experts verifying the logical correctness through intermediate results. This generation method, lacking empirical support from intermediate data, significantly increases the risk of generating illusions under complex logic.
[0021] To address the aforementioned technical bottlenecks, this application provides an adaptive database query method. This method is implemented based on the mechanism of SQL dynamic action space and execution feedback loop, and for ease of description, it is named SQLAct in this application.
[0022] The core objective of this solution is to build an intelligent database agent with environmental awareness and autonomous exploration capabilities. By introducing the Reason-Act (ReAct) paradigm, the SQL generation process is transformed from a "single static translation task" to a "multi-round dynamic interactive task." In this solution, the system is given the initiative to dynamically adjust its decision path based on execution feedback, enabling it to autonomously perform actions such as table structure verification, statement logic correction, and intermediate data validation. This closed-loop interactive mechanism aims to solve the problems of information gaps and logical discontinuities in the static generation mode, thereby significantly improving the generation accuracy and system robustness in complex query scenarios.
[0023] Accordingly, the adaptive database query method is applicable to an adaptive database query device, which can be deployed on an electronic device. The electronic device can be a computer device configured with a von Neumann architecture, such as a desktop computer, a laptop computer, or a server; the electronic device can be an electronic device with central control function, such as a gateway; or the electronic device can be a portable mobile electronic device, such as a smartphone or tablet computer.
[0024] To make the objectives, technical solutions, and advantages of this application clearer, the embodiments of this application will be described in further detail below with reference to the accompanying drawings.
[0025] like Figure 1 The diagram shown illustrates the overall topology and functional module coupling relationships of the SQLAct database management system proposed in this solution. Figure 1 As shown: The architecture is primarily composed of four core functional domains: the user interaction domain, consisting of the user terminal, which serves as the input source for natural language query commands Q; the agent core domain, which acts as the logical hub of the system, further decoupled internally into a memory management layer responsible for maintaining short-term memory and sliding window context states, a dynamic pruning and planning layer that connects to the vector library to filter tasks by execution mode, and a reasoning and execution layer (LLM) that carries the ReAct reasoning logic; the environment interface domain, which encapsulates the sandbox executor and feedback catcher, forming a secure isolation boundary for the agent's interaction with the external environment; and the external resource domain, which includes the target database for storing business data and metadata, and the vector index for storing pattern vector embedding features. Figure 1 It demonstrates the data flow processing logic through "pruning - inference - sandbox execution - feedback loop".
[0026] Specifically, the user interaction layer (i.e., the user interaction domain) serves as the system's input interface, responsible for receiving user query requests Q expressed in natural language. This layer preprocesses the input text, including removing redundant whitespace characters and standardizing punctuation marks, and then passes the processed query request to the agent computing core layer.
[0027] Specifically, the agent computing core layer (i.e., the agent computing core domain) serves as the logical control center of this system. The agent computing core layer achieves deep decoupling of its internal functional architecture, specifically encompassing three collaborative sub-modules: memory management, dynamic pruning and planning, and reasoning and execution. The memory management module (i.e., the environment interaction boundary domain) is primarily responsible for the structured storage and maintenance of the current session context state St. It constructs a configurable sliding window memory stack (default window size W=10) and employs a first-in, first-out (FIFO) strategy to iteratively update the overcapacity memory units. Its memory units are persistently encapsulated using a sequence of triplets containing "Thought," "Action," and "Observation." The "Observation" element, in addition to covering the data entities returned by the database, further aggregates automatically added metadata descriptions such as the number of rows returned, execution time, and field missing alerts, thus ensuring the integrity and multidimensionality of the context information.
[0028] The Dynamic Pruning & Planning module, relying on a connection to an external vector index library, is primarily responsible for accurately filtering table structure information relevant to the current query from massive database metadata. By executing a two-stage pruning algorithm based on semantic relevance, this module outputs a dynamic candidate pattern subset Msub, effectively reducing the computational load on the Large Language Model (LLM) context and avoiding the risk of model attention distraction caused by information overload.
[0029] The Reasoning & Execution LLM, as the core decision-making unit of the system, carries the ReAct (Reasoning and Acting) reasoning logic framework. By comprehensively processing the context state provided by the memory management module, the subset of candidate patterns output by the dynamic pruning module, and user query requests, this module drives the large language model to complete the construction of deep thinking trajectories and the generation of precise action instructions, realizing closed-loop control from information input to decision execution.
[0030] The environment interaction layer (i.e., the external resource domain) serves as the sole channel for interaction between the agent and the database instance. Through its two core components—the internally encapsulated sandbox executor and the feedback catcher—the environment interaction layer enables the secure execution of instructions and the standardized feedback of execution results.
[0031] Specifically, the Sandbox Executor primarily handles SQL statement execution tasks in an isolated environment and deeply integrates a dual circuit breaker mechanism encompassing both time and capacity dimensions. Specifically, for query commands whose execution time exceeds the preset time threshold Ttimeout (default 5 seconds), the system will automatically terminate the program and return a timeout alarm; for cases where the number of returned data rows exceeds the capacity threshold Nmax (default 1000 rows), data truncation is automatically implemented, and only partial results are returned. This circuit breaker mechanism effectively avoids the risk of malicious or inefficient queries exhausting computing resources, thereby significantly improving system stability and response timeliness.
[0032] The Feedback Catcher is dedicated to the accurate capture and unified structural processing of comprehensive feedback signals from the database. Its processing scope covers normal result sets returned after a successful query, error stack information when SQL statements have syntax problems, and runtime logical errors generated during execution, such as missing table entities or column fields. By transforming these diverse and heterogeneous signals into a standardized feedback format, this component provides reliable data support for the inference and decision-making of upper-level agents.
[0033] The external resource layer constitutes the system's underlying data support environment, specifically encompassing two core foundational resources: the target database and the vector index library. First, the target database. Serving as the physical storage carrier for business data and its metadata, and as the interactive object for intelligent agents to perform query operations, this resource achieves broad compatibility and underlying support for mainstream relational database systems such as MySQL, PostgreSQL, and SQLite. Second, the vector index library. This component is primarily used for the persistent storage of vector embedding features of database table structure information. By transforming the table structure information in the full metadata set M into serialized text descriptions during the preprocessing stage, and relying on pre-trained embedding models such as BGE and OpenAI-Ada to complete its mapping to a high-dimensional vector space, the system implements the construction of a dedicated index library designed to support subsequent efficient semantic retrieval operations.
[0034] Please see Figure 2 This application provides a flowchart of an adaptive database query method. This method is applicable to electronic devices, which can be servers or other devices with data analysis and processing capabilities, without specific limitations.
[0035] In the following method embodiments, for ease of description, the execution subject of each step of the method is an electronic device, but this does not constitute a specific limitation.
[0036] like Figure 2 As shown, the method may include the following steps: Step S210: Receive a user's natural language query.
[0037] Step S220: Perform initialization processing based on the user's natural language query to obtain the initialization state and a dynamic candidate pattern subset.
[0038] For example, after the system receives a user's natural language query Q, it first performs preprocessing on the user's natural language query Q (e.g., removing redundant spaces and standardizing punctuation).
[0039] Furthermore, inputting the pre-trained embedding model (such as BGE, OpenAI-Ada) generates query vectors. The dimension d of the query vector is determined by the selected embedding model, with typical values of 768 or 1536 dimensions.
[0040] Further, calculate the query vector. The initial candidate set is formed by selecting the K tables with the highest cosine similarity to all table vectors in the vector index. The formula for calculating cosine similarity is: Where V_T is the table structure vector.
[0041] Furthermore, the user's natural language query Q is compared with the initial candidate set. The combination forms the initial state S_0, which is then passed to the inference and execution module.
[0042] Furthermore, calling the large language model to... Perform semantic reordering (remove irrelevant tables) and output a dynamic subset of candidate patterns. Simultaneously, the initial system state is constructed. .
[0043] Step S230: Execute decision reasoning operations based on the initialization state and the dynamic candidate pattern subset to generate a Structured Query Language (SQL) action.
[0044] The decision reasoning operation is based on the system state and generates an appropriate SQL action to address information gaps or directly respond to user needs.
[0045] For example, by integrating system state (User natural language query Q, historical reasoning trajectory) Results of the previous round of execution Candidate Table This involves constructing input prompts for a large language model. During the first round of processing, the system state is... Based on this, the historical reasoning trajectory is empty, and the result of the previous execution is also empty.
[0046] For example, the decision reasoning operation includes two parts: context building and model reasoning. The context building stage aims to construct input prompts for a large language model by integrating information from multiple sources. The components of these prompts specifically include system instructions defining the agent's role and behavioral norms, and user natural language queries. A collection reflecting the structure information of the candidate table at the current moment. Historical triplet sequences extracted based on sliding window mechanism and the execution result after the most recent execution operation. .
[0047] For example, the model inference stage uses a large language model to perform deep reasoning based on the input context constructed above, and outputs a result containing two parts: one is the "Thought" part, which is the analysis of the current task state, specifically involving the identification of information gaps, logical reasoning process and explanation of decision basis; the other is the "Action" part, which is the specific SQL statement or system operation instruction (i.e. SQL action) generated by the model.
[0048] Step S260: Execute the SQL action and capture the execution result of the database in a structured manner.
[0049] Further, the SQL action generated in step S230 is executed and the execution result is captured in a structured manner.
[0050] Specifically, the generated SQL actions are transmitted to the sandbox executor within the environment interaction layer architecture. The sandbox executor executes the SQL actions in a strictly isolated runtime environment, and simultaneously introduces a circuit breaker mechanism to effectively control and protect the system's computing resources.
[0051] Furthermore, after execution, the feedback catcher is responsible for extracting the runtime artifacts and generating standardized execution results. The data structure of the execution result specifically covers the following seven dimensions of information elements: first, the execution status (status) that identifies the final result of the operation; second, the structured result dataset (data) that carries the query return value; third, the error message text (error_message) and error type classification (error_type) used for fault diagnosis; fourth, the execution time that quantifies performance metrics (execution_time); fifth, the number of rows returned that represents the statistical data scale (row_count); and sixth, the list of column names that describe the characteristics of the data pattern (column_names).
[0052] Furthermore, to optimize the efficiency of subsequent inference modules in parsing the execution status, the system will automatically perform metadata appending operations on the execution results. This mechanism enhances the semantics of the execution results by generating a summary description in natural language: for successful execution cases, the description summarizes the number of rows and field composition of the returned data; for failed execution cases, it clearly indicates the error type and the specific object name that caused the exception (such as a non-existent table name), thus providing precise guidance for subsequent error correction.
[0053] Step S270: Control the iteration process according to the execution result and termination condition until the iteration stops and the final SQL statement and query result are output.
[0054] Furthermore, based on the execution results The iterative process is executed based on the attribute characteristics and termination conditions. The iterative process is designed to make dynamic decisions based on the results of each round of execution. Specifically, the iterative process is divided into two paths: error correction and success determination. Branch A: Error correction path pin: to In cases marked "error", the error correction path will be activated. The execution logic of this path encompasses the following four consecutive stages: S1, from Error types With detailed information Extraction; S2, will change the current action With error message Merge into the state set of the next time step State update operation (i.e.) ); S3, triplet Writes to the memory management module and iteration counting Incrementing processing; S4, the process backtracks to step S2 to trigger a new round of reasoning, where the large language model performs attribution analysis based on error feedback and constructs a correction strategy.
[0055] Branch B: Successfully stopped path: targeting When the result is marked as "success", the system will enter the success check path, which means stopping the current iteration and outputting the final SQL statement and query results.
[0056] This stage first calls the confidence scoring function. The system performs a quantitative assessment of the reliability of the current results, followed by logical verification of the termination conditions. If the confidence score exceeds a preset threshold... (i.e., the second threshold, default 0.8) and the result Verified valid response issue Success conditions, or number of iterations Reaching the preset limit If the mandatory condition of (i.e., the first threshold, default 10) is met, the process will immediately terminate and output the final SQL statement and query results; otherwise, if none of the above conditions are met, the system will include the current result in the state set and return to step S2 to continue iterative optimization until the iteration stops and the final SQL statement and query results are output.
[0057] It should be noted that the first and second thresholds set in this application can be adjusted according to actual needs in practical applications, and no specific limitations are made here.
[0058] Under the above embodiments, the method proposed in this application firstly advocates a dynamic reasoning-action (ReAct) agent mechanism based on the interactive environment of the structured query language SQL. By constructing a method that progressively approximates the precise query logic through a multi-round iterative loop of "SQL generation - execution verification - feedback parsing", the functional attributes of SQL statements are redefined in this technical architecture: it is not only the final output product in response to user requests, but also the interactive medium for intelligent agents to actively explore the database topology, verify logical assumptions and obtain environmental feedback, realizing a paradigm shift from static translation to dynamic exploration.
[0059] Second, it proposes a decision-making reasoning method based on execution anomaly feedback, which constructs a feedback loop centered on the error stack information (Error Message) returned by the database execution engine. The system transforms runtime errors into contextual input signals for a large language model, thereby driving the model to perform targeted logical attribution, parameter adjustment, and statement reconstruction for execution bottlenecks. This endows the system with robust capabilities to automatically recover from syntax errors or logical conflicts without human intervention.
[0060] Third, this paper proposes an autonomous schema exploration method that integrates a two-stage pruning strategy and a dynamic expansion mechanism. This method aims to solve the context overflow problem in large-scale database scenarios, and its protection scope covers the entire technical chain from "vector retrieval initial screening—large model semantic reranking—on-demand dynamic loading." This strategy abandons the static limitation of traditional full schema pre-input, authorizing the agent to dynamically obtain unknown table structure information during task execution by generating specific metadata query instructions (such as querying information_schema), thus achieving "on-demand allocation" and "instant loading" of database schema information.
[0061] Fourth, a dynamic action space construction and state-adaptive scheduling strategy is proposed. This strategy abstracts and encapsulates complex database interaction operations into three types of discretized action vectors: metadata exploration, data sampling verification, and target execution. Based on the current interaction state matrix (covering historical execution trajectories, intermediate data features, and environmental feedback results), the system calculates the optimal decision path in real time, realizing the evolution of action selection from predefined rules to real-time dynamic programming.
[0062] In an exemplary embodiment, the method of performing initialization processing based on the natural language query includes the following steps: standardizing the user's natural language query to obtain the initialization state, wherein the initialization state includes: standardized user query, initial inference trajectory, and initial environment execution result; inputting the standardized user query into a pre-trained embedding model to generate a query vector; and generating the dynamic candidate pattern subset based on the standardized user query and the query vector, wherein the dynamic candidate pattern subset contains at least one table structure information most relevant to the query semantics.
[0063] For example, after receiving and preprocessing a natural language query Q, the database filters table structures related to the user's query from massive database metadata based on the preprocessed query request, avoiding model context overflow and providing an accurate schema foundation for subsequent inference.
[0064] For example, a user inputs a natural language query Q (e.g., "query the average monthly sales of each product in 2024") through the user interaction layer. The system performs preprocessing on Q: removing redundant whitespace characters, standardizing punctuation marks, extracting core entities (such as "2024", "product", "sales"), and generating standardized query text.
[0065] Furthermore, standardized query text is input into a pre-trained embedding model (such as BGE or OpenAI-Ada) to generate query vectors. ; Further calculation Compared with all table structure vectors in the vector index library The cosine similarity is calculated using the following formula: Furthermore, the top K tables with the highest similarity are selected to form the initial candidate set. (e.g., products, sales tables).
[0066] Furthermore, cosine similarity is used to perform preliminary screening of table structures, eliminating irrelevant tables. Then, the user query and the initial candidate set table information are input into the large language model, which determines the relevance between the table and the query based on semantics and outputs a dynamic subset of candidate patterns. .
[0067] Finally, the initial system state is constructed. (H represents the historical trajectory, O represents the execution result, both initially empty), and is passed to the core layer of intelligent agent computation.
[0068] For example, please refer to Figure 3 , Figure 3This is a schematic diagram illustrating the principle of the two-stage dynamic pruning algorithm based on semantic relevance in this application. Figure 3 The funnel-shaped data flow structure shown illustrates how the system extracts the core table structure from massive metadata through the convergence process of coarse-grained vector retrieval in the first stage and fine-grained LLM reordering in the second stage. At the same time, the dashed loop in the figure reveals the dynamic expansion mechanism, that is, the feedback path that triggers secondary retrieval as needed during the inference process.
[0069] Under the influence of the above embodiments, the solution of this application is successful.
[0070] In an exemplary embodiment, the method for performing decision reasoning operations based on the initialization state and the dynamic candidate pattern subset includes the following steps: performing structured parsing based on the initialization state and the dynamic candidate pattern subset to obtain a parsing result; performing information gap judgment based on the parsing result to obtain a judgment result; performing legality pre-verification based on the judgment result to generate the SQL action, wherein the SQL action includes: action type, statement body of the SQL, and execution control parameters.
[0071] For example, the database generates appropriate SQL actions based on the current system state and in accordance with the ReAct paradigm to address information gaps or directly respond to user needs.
[0072] Specifically, this includes building integrated system state through context. The complete information is used to construct input prompts for a large language model, which includes five core elements: System instructions: Define the role of the intelligent agent (such as "a database agent with autonomous exploration capabilities") and the behavioral rules ("think before acting, and correct based on feedback"). User Natural Language Query Q: Standardized Natural Language Requirements; Candidate table structure : Information from the currently filtered relevant tables; Historical reasoning trajectory The "think-action-observation" triplet in the first (t-1) rounds; Execution results of the previous round : The execution result of the previous SQL action.
[0073] Furthermore, the large language model's deep reasoning model performs a reasoning process of "information analysis → gap identification → decision planning" based on prompt words, specifically including: Information analysis: Analyze the core user needs, the table structure information already obtained, and historical interaction experience; Gap identification: Compare "information required to meet the needs" with "information currently available" to identify gap types (such as missing schema, unknown data features, or complete information); Decision planning: Plan actions based on gap type (Schema missing → exploratory actions, unknown data characteristics → confirmatory actions, complete information → target actions).
[0074] Finally, the SQL actions are dynamically generated. The model generates specific SQL actions. (Right now The system automatically determines the action type through rule matching and semantic parsing, providing a basis for subsequent execution.
[0075] Under the above embodiments, the present application defines the SQL operation itself as the action space of the agent and endows it with dynamic evolution characteristics. At time... The system state is defined as follows: It covers users' natural language queries Historical reasoning trajectory and the results of the previous round of environmental implementation Actions of the intelligent agent It is not selected from a pre-defined static set, but rather by the large language model based on the current state. Dynamic generation is performed, and its logical mapping relationship can be expressed as follows: This indicates that the agent's decision-making in this scheme is based on the result of dynamic calculation of all information, rather than static generation.
[0076] In an exemplary embodiment, the method of executing the SQL action and structurally capturing the execution result of the database includes the following steps: submitting the SQL action to the database for execution, obtaining the execution result, wherein the execution result includes a result set of successful execution or error information of execution failure; if the execution result contains error characteristics, then incorporating the error information into the state set of the next time step to drive the model to correct the SQL action according to the error information.
[0077] Specifically, the database executes SQL actions through the following steps: First, the sandbox securely executes SQL actions. Specifically, the generated SQL statements are transmitted to the sandbox executor in the environment interaction layer for execution in an isolated environment. This component is primarily responsible for executing SQL statements in an isolated environment and deeply integrates a dual circuit breaker mechanism that includes both time and capacity dimensions.
[0078] Specifically, this applies to cases where the execution time exceeds a preset time threshold. For query commands with a default timeout of 5 seconds, the system will automatically terminate the program and return a timeout alarm; for queries that return more rows of data than the capacity threshold, the system will also automatically terminate the program and return a timeout alarm. In cases where the default number of rows is 1000, data truncation will be automatically performed, and only a portion of the results will be returned. This circuit breaker mechanism effectively mitigates the risk of malicious or inefficient queries exhausting computing resources, thereby significantly improving system stability and response time. Furthermore, the execution results are captured by a feedback catcher, and standardized execution results are generated. The execution results comprise seven core dimensions, as shown in Table 1 below: Table 1 Dimension illustrate status Execution status (success / error) data Result dataset when execution is successful error_message Error details when execution fails error_type Error type (e.g., table does not exist, field is missing) execution time Execution time (milliseconds) row_count Return the number of rows of data column_names List of column names in the result set Furthermore, to optimize the efficiency of subsequent execution status parsing, the system will automatically perform metadata appending operations on the execution results. This mechanism enhances the semantics of the execution results by generating a natural language summary description: for successful execution cases, the description summarizes the number of rows and field composition of the returned data; for failed execution cases, it clearly indicates the error type and the specific object name that caused the exception (such as a non-existent table name), thus providing precise guidance for subsequent error correction.
[0079] In one possible example, the feedback signal source of this application's scheme can support multi-dimensional expansion. The aforementioned feedback mechanism is primarily based on execution results or error stacks. As a technical extension, the database execution plan (Explain Plan) can be incorporated into the feedback loop. The agent automatically generates performance optimization suggestions by analyzing query costs and index usage, achieving a functional evolution from "correctness-oriented" to "performance-oriented."
[0080] Therefore, this solution, based on the method described in the above embodiments, proposes an adaptive logic correction method based on execution exception feedback. The technical essence of this method lies in constructing a feedback loop centered on the error stack information (Error Message) returned by the database execution engine. The system transforms runtime errors into contextual input signals for a large language model, thereby driving the model to perform targeted logical attribution, parameter adjustment, and statement reconstruction for execution bottlenecks. This endows the system with robust capabilities to automatically recover from syntax errors or logical conflicts without manual intervention.
[0081] In an exemplary embodiment, the method for controlling the iteration process based on the execution result and termination condition includes the following steps: obtaining the execution result; determining whether to continue iteration based on the execution result; if the execution result indicates that the SQL action failed, correcting the SQL action based on the error information and continuing iteration; if the execution result indicates that the SQL action succeeded, controlling the iteration process based on the termination condition.
[0082] For example, as described in step S270, based on the attribute characteristics of the execution result, the system will make dynamic decisions regarding the divergence logic, specifically divided into two paths: error correction and success determination. Branch A: Error Correction Path Needle: For cases marked "error", the error correction path will be activated.
[0083] In an exemplary embodiment, the termination condition includes a first threshold for iteration and a second threshold corresponding to the confidence score. The method for controlling the iteration process according to the termination condition includes the following steps: quantifying and evaluating the contribution of the execution result to the user query using the confidence score function; if the confidence score is less than the second threshold, stopping the iteration and outputting the final SQL statement and the query result; if the confidence score is not less than the second threshold, or the number of iterations is greater than the first threshold, stopping the iteration and outputting the final SQL statement and the query result.
[0084] Branch B: Successfully stopped path: targeting If the condition is marked as "success", the system will proceed to the success-based stopping path. This stage first calls the confidence scoring function. Complete the quantitative assessment of the credibility of the current result, and then perform logical verification of the termination condition.
[0085] Specifically, the confidence scoring function Used to quantify the contribution of execution results to problem-solving, its calculation integrates three dimensions: first, the execution status score. ,in accordance with Assign the value 1.0 or 0.0 to "success" or "error" respectively; secondly, score the result content. By non-empty identifier The proportion of non-empty values The weighted summation calculation; and the semantic matching score. The set of column names calculated using Jaccard coefficients With user query entity set The degree of overlap. The final score is calculated by weighting the above three indicators. The weighted sum is obtained.
[0086] Specifically, if the confidence score exceeds a preset threshold And the result Verified valid response issue Success conditions, or number of iterations Reaching the preset limit If the mandatory condition is met, the process will immediately terminate and output the final SQL statement and query results; otherwise, if none of the above conditions are met, the system will include the current result in the state set and return to step S2 to continue iterative optimization.
[0087] Therefore, in this solution, based on the method described in the above embodiments, the system uses two types of loop termination conditions: successful termination and forced termination based on termination conditions. Successful termination conditions require the following criteria to be met: the generated SQL executes successfully, and the confidence score is [not specified]. Reaching the preset threshold Simultaneously, the result is determined to be "YES" through the stop prompt. The forced termination condition is based on the number of iterations. Has the preset limit been reached? A judgment is made to ensure the system's response timeliness and resource controllability.
[0088] In an exemplary embodiment, the SQL action includes an exploratory action, a verification action, and a target action; the system state includes the initialization state; the exploratory action is used to retrieve metadata of the database; the verification action is used to perform data sampling and format validation; and the target action is used to generate the final SQL statement in response to the user query.
[0089] This application defines SQL operations as the action space of an intelligent agent and endows it with the characteristic of dynamic evolution with the interaction state. Unlike the traditional tool calling mode that relies on a fixed set of APIs, the action space of this system adaptively adjusts according to the cognitive state of the environment.
[0090] Specifically, the action space includes three core action paradigms: Schema exploration is designed to retrieve database metadata and is suitable for scenarios where table structure information is missing. It covers SQL patterns such as querying table name lists, field definitions, and foreign key relationships. Verification actions (Data Inspection) are designed to perform data sampling and format verification. They are suitable for scenarios where the characteristics of the data content are uncertain and cover SQL patterns such as sampling queries, field distribution checks, and date format verification. Target execution is designed to generate the final SQL statement that responds to a user query. Its structure is determined by the specific query requirements and involves complex operations such as multi-table joins, aggregation statistics, and nested subqueries.
[0091] The agent's action selection exhibits three typical evolutionary stages over time: Phase T1 (Pattern Confusion Period): The agent mainly performs exploratory actions to build an understanding of the database structure, including obtaining table names, field definitions, and relationships; Phase T2 (Data Exploration Period): After mastering the basic pattern information, the agent turns to verification actions, using sampling queries to confirm the data format, enumeration value range, and field distribution characteristics; Phase T3 (Target Execution Period): Based on a full understanding of the environment, the agent directly generates the target action and constructs a complete business query SQL to respond to user needs.
[0092] In one possible example, the action space involved in this application can support hybrid expansion. The existing action space is mainly based on SQL statements and can be further expanded into a hybrid code execution environment of "SQL + Python". When dealing with complex data cleaning or statistical analysis tasks, the agent can call the Python interpreter to perform secondary processing on the intermediate data obtained from SQL, so as to make up for the shortcomings of SQL in procedural computation capabilities.
[0093] Therefore, this solution, based on the method described in the above embodiments, proposes a dynamic action space construction and state adaptive scheduling strategy. This strategy abstracts and encapsulates complex database interaction operations into three types of discretized action vectors: metadata exploration, data sampling verification, and target execution. Based on the current interaction state matrix (covering historical execution trajectories, intermediate data features, and environmental feedback results), the system calculates the optimal decision path in real time, realizing the evolution of action selection from predefined rules to real-time dynamic planning.
[0094] To better understand the above processing flow, the following will combine... Figure 4 Provide an explanation of the overall processing flow. Figure 4 It is a dynamic job workflow logic diagram based on the execution-feedback loop. For example... Figure 4 The "observation-thinking-action" iterative mechanism for intelligent agents to process complex queries, as shown, specifically includes the following key steps: The first stage is the initialization phase, where the system receives queries. And perform dynamic pattern pruning to obtain a candidate table set; The next stage is the reasoning and decision-making phase, where the Large Language Model (LLM) generates thought processes and action instructions (SQL) based on the current state. Next comes the execution and divergence determination phase. The system executes the SQL in the sandbox based on the action type (Schema exploration / data preview / target query) and enters different branches according to the execution status: If an execution error occurs (path A), the system captures the error stack information and sends it back to the memory module, triggering the next round of logical correction and regeneration, forming an adaptive repair loop; if execution succeeds (path B), the system obtains the result summary and evaluates whether it meets the termination conditions. Finally, in the termination phase, when the result is sufficient to answer the question or the number of iterations reaches a threshold, the process terminates and outputs the final SQL and query results.
[0095] Further, please refer to Figure 5 , Figure 5 This is a temporal interaction diagram illustrating the dynamic action space and state evolution in the scheme of this application. Specifically, as shown... Figure 5 As shown: This graph, with time as its dimension, illustrates the agent's... Pattern confusion period (performing metadata retrieval) Data exploration phase (performing data sampling and validation) and The process of adaptive evolution in action selection as the state of environmental awareness improves during the three stages of the target execution period (generating the final business query).
[0096] It should be noted that the above Figure 4 and Figure 5 The entire processing flow can be mapped to steps S210-S250 and their corresponding sub-explanations, which will not be elaborated here.
[0097] It should be noted that the feasibility and superiority of the proposed solution have been confirmed through empirical simulation experiments on recognized standard benchmark sets in the Text-to-SQL field (such as Spider and BIRD-SQL).
[0098] This experiment constructed a comparative test environment based on GPT-4. The experiment aimed to compare and analyze the performance differences between standard few-shot prompting methods, the mainstream academic method of DIN-SQL (Dual Instructions for SQL), and the SQLAct method proposed in this invention under different complexity scenarios. The test samples covered a full range of scenarios, from basic single-table queries to highly complex multi-table nested queries (Extra Hard).
[0099] The experimental results are shown in Table 2 below: Table 2 Data shows that in scenarios involving complex logical reasoning and schema linking interference, SQLAct's execution accuracy significantly outperforms the baseline model. This is attributed to the dynamic pruning strategy effectively reducing the interference of irrelevant contextual noise on the model.
[0100] Process analysis shows that approximately 30% of initial generation errors (mainly due to column name spelling errors or foreign key relationship logic errors) were successfully corrected through one to two rounds of "execution-error-correction" adaptive feedback loops. This confirms that introducing an environmental feedback mechanism plays a decisive role in improving the first-pass rate (Pass@1).
[0101] It should be noted that the method proposed in this application can be applied to various application scenarios, including but not limited to: applications in the field of database operation and maintenance and diagnosis (DBA Agent). By granting the agent permissions to query system views and performance metrics, this invention can be transformed into an automated operation and maintenance agent to perform operation and maintenance tasks such as slow query diagnosis, index optimization suggestion generation, and lock conflict analysis. Applications in the field of data cleaning and migration (ETL Agent). Utilizing the agent's exploratory query capabilities, this invention can be applied to data quality assessment scenarios, automatically identifying abnormal data distributions and generating corresponding data cleaning and migration (ETL) logic code.
[0102] In summary, the technical solution provided by this invention has been proven through experiments to have the characteristics of high precision, strong robustness, and good scalability, which fully demonstrates the feasibility and practical value of the method, device, and system of this invention in the field of data query.
[0103] The following are embodiments of the apparatus described in this application, which can be used to execute the adaptive database query method involved in this application. For details not disclosed in the apparatus embodiments of this application, please refer to the method embodiments of the adaptive database query method involved in this application.
[0104] Please see Figure 6 This application provides an adaptive database query device 600, comprising a receiving unit 601, a processing unit 602, a decision reasoning unit 603, an execution unit 604, and an output unit 605, wherein: The receiving unit 601 is used to receive user natural language queries; The processing unit 602 is used to perform initialization processing based on the user's natural language query to obtain an initialization state and a dynamic candidate pattern subset. The decision reasoning unit 603 is used to perform decision reasoning operations based on the initialization state and the dynamic candidate pattern subset to generate structured query language (SQL) actions. The decision reasoning operations are based on the system state to generate adapted SQL actions to address information gaps or directly respond to user needs. The execution unit 604 is used to execute the SQL action and capture the execution results of the database in a structured manner; The output unit 605 is used to control the iteration process according to the execution result and termination condition, until the iteration stops and the final SQL statement and query result are output.
[0105] Therefore, in this scheme, based on the aforementioned adaptive database query device, firstly, the receiving unit receives the user's natural language query; then, the processing unit performs initialization processing based on the user's natural language query to obtain the initialization state and a dynamic candidate pattern subset; further, the reasoning and decision-making unit performs decision-making reasoning operations based on the initialization state and the dynamic candidate pattern subset to generate structured query language (SQL) actions; further, the execution unit executes the SQL actions and structurally captures the execution results from the database; finally, the output unit controls the iteration process based on the execution results and termination conditions until the iteration stops and the final SQL statement and query results are output. In this way, by constructing an intelligent database agent with environmental awareness and autonomous exploration capabilities, the system is endowed with decision-making reasoning capabilities, realizing a closed-loop operation of table structure verification, logical correction, and intermediate data verification; thereby improving the accuracy of SQL generation and the robustness of the system in complex query scenarios.
[0106] In an exemplary embodiment, the initialization process performed based on the natural language query is further comprised of the following: The user's natural language query is standardized to obtain the initialization state, which includes: standardized user query, initial inference trajectory, and initial environment execution result; The standardized user query is input into the pre-trained embedding model, and a query vector is generated. Based on the standardized user query and the query vector, a dynamic candidate pattern subset is generated, wherein the dynamic candidate pattern subset contains at least one table structure information that is most relevant to the query semantics.
[0107] In an exemplary embodiment, the processing unit 602, which performs the decision reasoning operation based on the initialization state and the subset of dynamic candidate patterns, is further configured to include: The initialization state and the subset of dynamic candidate patterns are used for structured parsing to obtain the parsing results; Based on the analysis results, an information gap assessment is performed to obtain the assessment result; Based on the judgment result, a legality pre-verification is performed to generate the SQL action, wherein the SQL action includes: action type, the statement body of the SQL, and execution control parameters.
[0108] In an exemplary embodiment, the decision reasoning unit 603, which executes the SQL action and structurally captures the execution results of the database, is further configured to include: The SQL action is submitted to the database for execution, and the execution result is obtained, wherein the execution result includes a result set of successful execution or error information of execution failure; If the execution result contains error characteristics, the error information is included in the state set of the next time step to drive the model to correct the SQL action based on the error information.
[0109] In an exemplary embodiment, the execution unit 604, which controls the iteration process based on the execution result and termination condition, is further configured to include: Obtain the execution result, and determine whether to continue iteration based on the execution result; If the execution result indicates that the SQL action failed, then the SQL action is corrected according to the error information and the iteration continues; If the execution result indicates that the SQL action was successful, then the iteration process is controlled according to the termination condition.
[0110] In an exemplary embodiment, the termination condition includes a first threshold for iteration and a second threshold corresponding to the confidence score. The execution unit 604, which controls the iteration process according to the termination condition, is further configured to include: The contribution of the execution result to the user query is quantitatively evaluated using the confidence scoring function. If the confidence score is less than the second threshold, the iteration stops, and the final SQL statement and the query result are output. If the confidence score is not less than the second threshold, or the number of iterations is greater than the first threshold, then the iteration stops, and the final SQL statement and the query result are output.
[0111] In an exemplary embodiment, the SQL action includes an exploratory action, a verification action, and a target action; the system state includes the initialization state; the exploratory action is used to retrieve metadata of the database; the verification action is used to perform data sampling and format validation; and the target action is used to generate the final SQL statement in response to the user query.
[0112] It should be noted that the adaptive database query device provided in the above embodiments is only illustrated by the division of the above functional modules when querying data. In actual applications, the above functions can be assigned to different functional modules as needed. That is, the internal structure of the adaptive database query device will be divided into different functional modules to complete all or part of the functions described above.
[0113] Furthermore, the adaptive database query device and the adaptive database query method provided in the above embodiments belong to the same concept, and the specific way in which each module performs its operation has been described in detail in the method embodiments, and will not be repeated here.
[0114] It should be noted that the description of the above device embodiments is similar to the description of the above method embodiments, and has similar beneficial effects. For technical details not disclosed in the device embodiments of this application, please refer to the description of the method embodiments of this application for understanding.
[0115] This application also provides an electronic device. Figure 7 This is a schematic diagram of an optional structure of an electronic device provided in an embodiment of this application. For example... Figure 7 As shown, the electronic device 7000 includes at least one processor 7001 and at least one memory 7003.
[0116] The data interaction between the processor 7001 and the memory 7003 can be achieved through at least one communication bus 7002. This communication bus 7002 may include a path for transmitting data between the processor 7001 and the memory 7003. The communication bus 7002 may be a PCI (Peripheral Component Interconnect) bus or an EISA (Extended Industry Standard Architecture) bus, etc. The communication bus 7002 can be divided into an address bus, a data bus, a control bus, etc. For ease of representation, Figure 5 The bus is represented by a single thick line, but this does not mean that there is only one bus or one type of bus.
[0117] Optionally, the electronic device 7000 may further include a transceiver 7004, which can be used for data interaction between the electronic device and other electronic devices, such as sending and / or receiving data. It should be noted that in practical applications, the transceiver 7004 is not limited to one type, and the structure of the electronic device 7000 does not constitute a limitation on the embodiments of this application.
[0118] Processor 7001 may be a CPU (Central Processing Unit), a general-purpose processor, a DSP (Digital Signal Processor), an ASIC (Application Specific Integrated Circuit), an FPGA (Field Programmable Gate Array), or other programmable logic devices, transistor logic devices, hardware components, or any combination thereof. It can implement or execute the various exemplary logic blocks, modules, and circuits described in conjunction with the disclosure of this application. Processor 7001 may also be a combination that implements computing functions, such as including one or more microprocessor combinations, a combination of a DSP and a microprocessor, etc.
[0119] The memory 7003 may be a ROM (Read Only Memory) or other type of static storage device capable of storing static information and instructions, RAM (Random Access Memory) or other type of dynamic storage device capable of storing information and instructions, or an EEPROM (Electrically Erasable Programmable Read Only Memory), CD-ROM (Compact Disc Read Only Memory) or other optical disc storage, optical disc storage (including compressed optical discs, laser discs, optical discs, digital universal optical discs, Blu-ray discs, etc.), magnetic disk storage media or other magnetic storage devices, or any other medium capable of carrying or storing desired program instructions or code in the form of instructions or data structures and accessible by the electronic device 700, but not limited thereto.
[0120] The memory 7003 stores program instructions or code, and the processor 7001 can read the program instructions or code stored in the memory 7003 through the communication bus 7002.
[0121] When the program instructions or code are executed by the processor 7001, the adaptive database query method in the above embodiments is implemented.
[0122] This application provides a computer-readable storage medium storing executable instructions. When the executable instructions are executed by the processor, the processor will execute the adaptive database query method provided in this application.
[0123] In some embodiments, the computer-readable storage medium may be a memory such as FRAM, ROM, PROM, EPROM, EEPROM, flash memory, magnetic surface memory, optical disk, or CD-ROM; or it may be a variety of devices including one or any combination of the above-mentioned memories.
[0124] In some embodiments, executable instructions may take the form of a program, software, software module, script, or code, written in any form of programming language (including compiled or interpreted languages, or declarative or procedural languages), and may be deployed in any form, including as a standalone program or as a module, component, subroutine, or other unit suitable for use in a computing environment.
[0125] As an example, executable instructions may, but do not necessarily, correspond to files in a file system. They may be stored as part of a file that holds other programs or data, for example, in one or more scripts within a HyperText Markup Language (HTML) document, in a single file dedicated to the program in question, or in multiple co-located files (e.g., files storing one or more modules, subroutines, or code sections). As an example, executable instructions may be deployed to execute on a single computing device, or on multiple computing devices located in one location, or on multiple computing devices distributed across multiple locations and interconnected via a communication network.
[0126] Those skilled in the art will understand that embodiments of this application can be provided as methods, systems, or computer program products. Therefore, this application can take the form of hardware embodiments, software embodiments, or embodiments combining software and hardware aspects. Furthermore, this application can take the form of a computer program product implemented on one or more computer-usable storage media (including, but not limited to, disk storage and optical storage) containing computer-usable program code.
[0127] This application is described with reference to flowchart illustrations and / or block diagrams of methods, apparatus (systems), and computer program products according to embodiments of this application. It will be understood that each block of the flowchart illustrations and / or block diagrams, and combinations of blocks in the flowchart illustrations and / or block diagrams, can be implemented by computer program instructions. These computer program instructions can be provided to a processor of a general-purpose computer, special-purpose computer, embedded processor, or other programmable data processing apparatus to produce a machine, such that the instructions, which execute via the processor of the computer or other programmable data processing apparatus, generate instructions for implementing the flowchart... Figure 1 One or more processes and / or boxes Figure 1 A device that provides the functions specified in one or more boxes.
[0128] These computer program instructions may also be stored in a computer-readable storage medium that can direct a computer or other programmable data processing device to function in a particular manner, such that the instructions stored in the computer-readable storage medium produce an article of manufacture including instruction means, which are implemented in a process Figure 1 One or more processes and / or boxes Figure 1 The function specified in one or more boxes.
[0129] These computer program instructions may also be loaded onto a computer or other programmable data processing equipment to cause a series of operational steps to be performed on the computer or other programmable equipment to produce a computer-implemented process, thereby providing instructions that execute on the computer or other programmable equipment for implementing the process. Figure 1 One or more processes and / or boxes Figure 1 The steps of the function specified in one or more boxes.
[0130] The above description is merely a preferred embodiment of this application and is not intended to limit the scope of protection of this application. Any modifications, equivalent substitutions, and improvements made within the spirit and scope of this application are included within the scope of protection of this application.
[0131] Compared with related technologies, the adaptive database query method proposed in this application generates multiple equivalent samples through systematic code transformation operations, making the change in the model's confidence in perturbed samples the core basis for determining whether a sample has been memorized. Compared with traditional methods based on overlap rate or time inference, this invention can effectively reduce the false positive rate and false negative rate, and is especially suitable for code samples with different syntaxes and similar inheritance structures, achieving high-precision identification of complex code patterns. Through semantically preserved perturbation generation, model confidence comparison, differential analysis judgment, and automated system implementation, it has significant advantages over existing technologies in terms of not relying on training data, not requiring threshold settings, wide applicability, and high detection accuracy, effectively solving the core technical problem in large code model data leakage detection.
[0132] It should be understood that although the steps in the flowcharts of the accompanying figures are shown sequentially as indicated by the arrows, these steps are not necessarily executed in the order indicated by the arrows. Unless explicitly stated herein, there is no strict order restriction on the execution of these steps, and they can be executed in other orders. Moreover, at least some steps in the flowcharts of the accompanying figures may include multiple sub-steps or multiple stages. These sub-steps or stages are not necessarily completed at the same time, but can be executed at different times, and their execution order is not necessarily sequential, but can be performed alternately or in turn with other steps or at least some of the sub-steps or stages of other steps.
[0133] The above description is only a partial embodiment of this application. It should be noted that for those skilled in the art, several improvements and modifications can be made without departing from the principle of this application, and these improvements and modifications should also be considered within the scope of protection of this application.
Claims
1. An adaptive database query method, characterized in that, include: Receive user queries in natural language; Based on the user's natural language query, an initialization process is performed to obtain the initialization state and a dynamic candidate pattern subset; Decision reasoning operations are performed based on the initialization state and the subset of dynamic candidate patterns to generate structured query language (SQL) actions. The decision reasoning operations are based on the system state to generate adapted SQL actions to address information gaps or directly respond to user needs. Execute the SQL action and capture the execution results in the database in a structured manner; The iteration process is controlled based on the execution results and termination conditions until the iteration stops, at which point the final SQL statement and query results are output.
2. The method as described in claim 1, characterized in that, The method for performing initialization processing based on the natural language query includes: The user's natural language query is standardized to obtain the initialization state, which includes: standardized user query, initial inference trajectory, and initial environment execution result; The standardized user query is input into the pre-trained embedding model, and a query vector is generated. Based on the standardized user query and the query vector, a dynamic candidate pattern subset is generated, wherein the dynamic candidate pattern subset contains at least one table structure information that is most relevant to the query semantics.
3. The method as described in claim 2, characterized in that, The method of performing decision reasoning operations based on the initialization state and the subset of dynamic candidate patterns includes: The initialization state and the subset of dynamic candidate patterns are used for structured parsing to obtain the parsing results; Based on the analysis results, an information gap assessment is performed to obtain the assessment result; Based on the judgment result, a legality pre-verification is performed to generate the SQL action, wherein the SQL action includes: action type, the statement body of the SQL, and execution control parameters.
4. The method as described in claim 3, characterized in that, The method for executing the SQL action and capturing the execution results in a structured manner in the database includes: The SQL action is submitted to the database for execution, and the execution result is obtained, wherein the execution result includes a result set of successful execution or error information of execution failure; If the execution result contains error characteristics, the error information is included in the state set of the next time step to drive the model to correct the SQL action based on the error information.
5. The method as described in claim 4, characterized in that, The method for controlling the iteration process based on the execution result and termination condition includes: Obtain the execution result, and determine whether to continue iteration based on the execution result; If the execution result indicates that the SQL action failed, then the SQL action is corrected according to the error information and the iteration continues; If the execution result indicates that the SQL action was successful, then the iteration process is controlled according to the termination condition.
6. The method as described in claim 5, characterized in that, The termination condition includes a first threshold for the iteration and a second threshold corresponding to the confidence score. The method for controlling the iteration process based on the termination condition includes: The contribution of the execution result to the user query is quantitatively evaluated using the confidence scoring function. If the confidence score is less than the second threshold, the iteration stops, and the final SQL statement and the query result are output. If the confidence score is not less than the second threshold, or the number of iterations is greater than the first threshold, then the iteration stops, and the final SQL statement and the query result are output.
7. The method as described in claim 1, characterized in that, The SQL actions include exploratory actions, verification actions, and target actions. The system state includes the initialization state. The exploratory actions are used to retrieve the metadata of the database. The verification actions are used to perform data sampling and format validation. The target actions are used to generate the final SQL statement in response to the user query.
8. An adaptive database query device, characterized in that, The device includes a receiving unit, a processing unit, a decision-making and reasoning unit, an execution unit, and an output unit, wherein: The receiving unit is used to receive user natural language queries; The processing unit is used to perform initialization processing based on the user's natural language query to obtain an initialization state and a dynamic candidate pattern subset; The decision reasoning unit is used to perform decision reasoning operations based on the initialization state and the dynamic candidate pattern subset to generate structured query language (SQL) actions. The decision reasoning operations are based on the system state to generate adapted SQL actions to address information gaps or directly respond to user needs. The execution unit is used to execute the SQL action and capture the execution results of the database in a structured manner; The output unit is used to control the iteration process based on the execution result and termination condition, until the iteration stops and the final SQL statement and query result are output.
9. An electronic device, characterized in that, include: At least one processor and at least one memory, wherein, The memory stores program instructions or code; The program instructions or code are loaded and executed by the processor, causing the electronic device to implement the adaptive database query method as described in any one of claims 1 to 7.
10. A storage medium storing program instructions or code thereon, characterized in that, The program instructions or code are loaded and executed by the processor to implement the adaptive database query method as described in any one of claims 1 to 7.
11. A computer program product comprising a computer program that is read and executed by a processor of a computer device, causing the computer device to perform the adaptive database query method according to any one of claims 1 to 7.