A multi-agent cooperation SQL generation and correction method and system for financial data analysis
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-07-01
- Publication Date
- 2026-08-11
AI Technical Summary
[0003]传统Text-to-SQL方法在处理复杂财务查询场景时,普遍存在两大关键局限:(1)意图与结构理解不足:难以同时精准捕捉用户自然语言中的多层次模糊意图(如包含时间、区域、主体、指标、计算方式等多维度意图的查询语句),且无法充分适配财务数据库的复杂模式结构(如多表关联的科目表、凭证表、报表表等),导致生成的SQL语句与用户实际需求偏差较大;(2)缺乏有效自我修正机制:生成的SQL语句常存在语法错误(如关键字拼写错误、表连接逻辑错误、聚合函数使用不当)和语义错误(如字段匹配错误、条件筛选与用户意图不符、数据范围偏差)两类问题,而传统方法未构建针对性的错误检测与修正流程,无法对上述错误进行自动化修正,最终导致财务数据查询失败,影响分析效率
[0035] The beneficial effects of the present invention are as follows: The present invention provides a multi-agent collaborative SQL generation and correction method for financial data analysis. By integrating the complex query parsing capabilities and error correction capabilities of previous methods, a multi-agent collaborative system is constructed to achieve accurate understanding of financial query intent, SQL statement generation, and dual error correction of syntax and semantics. Specifically: (1) High accuracy of intent and structure understanding: Through the collaboration of the selector and decomposer of the statement generation module, it can accurately filter the core information in the database, reduce irrelevant interference, and decompose complex financial queries into simple sub-problems, achieving synchronous adaptation to multi-level fuzzy intents and complex database structures, and solving the problem of "understanding deviation" in traditional methods; (2) Strong comprehensiveness of error correction: Through the "detection-reconstruction-verification" process of the error correction module, it can simultaneously correct the syntax errors (such as keyword spelling errors, table join logic errors, improper use of aggregate functions) and semantic errors (such as keyword spelling errors, table join logic errors, improper use of aggregate functions) of SQL statements. For example, there are two types of problems: field matching errors, condition filtering that does not match the user's intent, and data range deviation. Traditional methods do not have a targeted error detection and correction process, and cannot automatically correct the above errors. The earliest traditional methods would lead to financial data query failure, affecting the analysis efficiency. This invention overcomes the problems of low efficiency and query difficulty; (3) Excellent financial scenario adaptability: By constructing a financial domain thesaurus and financial business logic verification rules, customized design is carried out for the professionalism of financial data (such as indicator calculation and accounting period). The generated SQL statement conforms to the financial business specifications, avoiding the problem of "technically correct but business wrong", and adapting to various complex financial query needs; (4) Outstanding self-evolution capability: Through the failure memory bank and error pattern analysis mechanism, historical error correction experience can be recorded and reused. As the number of uses increases, the error identification and correction efficiency gradually improves, realizing the system's "self-optimization" and reducing long-term use costs.
Smart Images

Figure CN122547820A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of multi-agent collaborative SQL technology, specifically to a method and system for generating and correcting multi-agent collaborative SQL for financial data analysis. Background Technology
[0002] In the field of financial data analysis, accurate conversion from natural language to SQL (Text-to-SQL) is a core capability for the interaction between financial data analysis agents and databases. The accuracy of this conversion directly determines the reliability of subsequent financial data query results and the validity of analytical conclusions. As corporate financial operations become increasingly complex, financial databases exhibit characteristics such as multi-layered structures, intricate inter-table relationships, and specialized field meanings. Simultaneously, users' financial query needs are becoming increasingly diverse, encompassing not only basic income and expenditure statistics queries but also complex requirements such as multi-dimensional financial indicator analysis and cross-period data comparisons. This places higher demands on Text-to-SQL technology.
[0003] Traditional Text-to-SQL methods generally have two major limitations when dealing with complex financial query scenarios: (1) Insufficient understanding of intent and structure: It is difficult to accurately capture the multi-level fuzzy intent in the user's natural language (such as query statements containing multi-dimensional intents such as time, region, subject, indicator, calculation method, etc.), and it cannot fully adapt to the complex pattern structure of financial databases (such as account tables, voucher tables, report tables, etc. with multiple tables), resulting in a large deviation between the generated SQL statement and the user's actual needs; (2) Lack of effective self-correction mechanism: The generated SQL statement often has two types of problems: syntax errors (such as keyword spelling errors, table join logic errors, improper use of aggregate functions) and semantic errors (such as field matching errors, condition filtering not matching the user's intent, data range deviation). Traditional methods have not built a targeted error detection and correction process, and cannot automatically correct the above errors, which ultimately leads to the failure of financial data query and affects the analysis efficiency.
[0004] To address some of the aforementioned issues, two representative frameworks have emerged in the existing technology: one is the MAC-SQL framework, which achieves step-by-step parsing of complex queries through the collaboration of multiple agents and can effectively correct syntax errors, but it cannot solve the problem of semantic inconsistency in SQL statements; the other is the SQLFixAgent framework, which significantly improves the semantic accuracy of SQL statements through the collaboration of three agents, using a "rubber duck debugging" method and a failure memory reflection mechanism, but it lacks the ability to perform layered parsing of complex financial query intentions and has not been adapted to the complex structure of financial databases.
[0005] Therefore, the existing technology still has the following problems: (1) The problem of adapting complex intents to database structures: Although the existing methods can parse some complex queries, the traditional Text-to-SQL method and the existing framework cannot simultaneously and accurately understand the multi-level fuzzy intents (such as multi-dimensional indicator calculations and cross-period comparisons) in the user's financial query and the complex pattern structure of the financial database (such as multi-table associations and specialized fields), which leads to the SQL generation direction deviating from the actual needs; (2) Incomplete SQL error correction: The traditional method lacks a self-correction mechanism, the MAC-SQL framework can only correct syntax errors, and the SQLFixAgent framework has insufficient statement generation capabilities. Some technologies cannot fully detect and correct syntax errors (such as keyword errors, table join logic errors) and semantic errors (such as field mismatches, conditions deviating from intent) in SQL statements based on enhancing statement generation capabilities, resulting in a high query failure rate; (3) Poor adaptability to financial scenarios: Existing Text-to-SQL frameworks have not customized designs for the professionalism of financial data (such as financial indicator definitions, accounting period rules), and the generated SQL statements are prone to problems that are inconsistent with financial business logic (such as ignoring the consistency of accounting periods, incorrect calculation of financial ratios), and lack an efficient processing mechanism for financial queries, resulting in low query efficiency and insufficient accuracy.
[0006] In summary, given the limitations of existing Text-to-SQL technology in complex financial scenarios, there is an urgent need for a multi-agent collaborative SQL generation and correction method and system for financial data analysis. Summary of the Invention
[0007] A brief overview of the invention is given below to provide a basic understanding of certain aspects of it. It should be understood that this overview is not an exhaustive summary of the invention. It is not intended to identify key or essential parts of the invention, nor is it intended to limit the scope of the invention. Its purpose is merely to present certain concepts in a simplified form as a prelude to the more detailed description that follows.
[0008] In view of this, in order to solve the problems of complex intents and database structures being difficult to adapt to and the incomplete correction of erroneous SQL statements in the traditional multi-agent collaborative SQL generation and correction methods and systems in the prior art, the present invention provides a multi-agent collaborative SQL generation and correction method and system for financial data analysis.
[0009] Technical Solution 1 is as follows: A multi-agent collaborative SQL generation and correction method for financial data analysis, comprising the following steps:
[0010] S1. Based on user input and message dictionary, filter and determine the financial database using a selector, which includes the extracted database schema description string, foreign key information string, and the selected database schema dictionary;
[0011] S2. The financial database is broken down into multiple executable subtasks by a decomposer, and a corresponding complete SQL statement is generated for each subtask;
[0012] S3. The generated complete SQL statement is checked for errors by the detector. If an error is found, the erroneous SQL statement to be repaired will proceed to step S4 for correction. If no error is found, the process will proceed directly to step S5.
[0013] Specifically, the database schema dictionary filtered by the selector and the complete SQL statement are used as input to the detector;
[0014] S4. Based on the erroneous SQL statement to be repaired, the statement generation module automatically generates five query variants. The SQL execution result is obtained through the query builder, and the corrected SQL statement is obtained through the optimizer. The process is then returned to step S3 for re-detection by the detector until there are no errors, and then proceeds to step S5.
[0015] S5. Output the final correct SQL statement or query result.
[0016] Furthermore, in S1, the user input includes the database path, the path to the table structure JSON file, the model name, and the dataset name;
[0017] The message dictionary includes: database ID, user query, additional evidence information, and preprocessed pattern information;
[0018] Using user input and a message dictionary as input to a selector, the selector filters the data to obtain a sub-database highly relevant to the user query. ;
[0019] Sub-database Represented as:
[0020]
[0021] Among them, sub-database Set containing sublists Subsequence set T represents the table, and C represents the column. The core function of the selector is derived from the large language model. drive, For natural language queries entered by the user, For the original and complete database, External knowledge.
[0022] Furthermore, in step S2, the user's natural language query, database schema description, foreign key information, and optional additional evidence are used as inputs to the decomposer, based on the sub-database. Get the complete SQL statement and large language models Conditional probability of generating SQL ;
[0023] The process of the resolver is represented as follows:
[0024]
[0025] in, The number of subproblems that the decomposer breaks down. For the j-th sub-SQL, For all sub-SQLs generated before the j-th sub-SQL, Let j be the j-th subproblem.
[0026] Furthermore, in step S4, the filtered database schema dictionary, database schema description, foreign key information, database path, additional evidence information, and the original user question composed of natural language are used as inputs to the query builder to obtain a valid SQL execution result.
[0027] Using large language models The original user question was rewritten into four different expressions, generating five SQL query variants;
[0028] The optimized SQL statement is obtained by taking the filtered database schema dictionary, database schema description, foreign key information, five SQL query variants, the currently valid SQL execution result, the index used for similarity retrieval, and the database path as input. ';
[0029] Corrected SQL statement Represented as:
[0030]
[0031] Where E represents SQL execution error messages (such as "table does not exist" or "field mismatch"). 'This is an incorrect SQL statement that needs to be repaired.'
[0032] Technical Solution 2: A multi-agent collaborative SQL generation and correction system for financial data analysis, used to execute the multi-agent collaborative SQL generation and correction method for financial data analysis described in Technical Solution 1, including a statement generation module and an error correction module;
[0033] The statement generation module includes a selector and a decomposer connected in sequence;
[0034] The error correction module includes a detector, a query builder, and an optimizer. The detector is connected to the query builder, the query builder is connected to the optimizer, and the builder is connected to the statement generation module.
[0035] The beneficial effects of the present invention are as follows: The present invention provides a multi-agent collaborative SQL generation and correction method for financial data analysis. By integrating the complex query parsing capabilities and error correction capabilities of previous methods, a multi-agent collaborative system is constructed to achieve accurate understanding of financial query intent, SQL statement generation, and dual error correction of syntax and semantics. Specifically: (1) High accuracy of intent and structure understanding: Through the collaboration of the selector and decomposer of the statement generation module, it can accurately filter the core information in the database, reduce irrelevant interference, and decompose complex financial queries into simple sub-problems, achieving synchronous adaptation to multi-level fuzzy intents and complex database structures, and solving the problem of "understanding deviation" in traditional methods; (2) Strong comprehensiveness of error correction: Through the "detection-reconstruction-verification" process of the error correction module, it can simultaneously correct the syntax errors (such as keyword spelling errors, table join logic errors, improper use of aggregate functions) and semantic errors (such as keyword spelling errors, table join logic errors, improper use of aggregate functions) of SQL statements. For example, there are two types of problems: field matching errors, condition filtering that does not match the user's intent, and data range deviation. Traditional methods do not have a targeted error detection and correction process, and cannot automatically correct the above errors. The earliest traditional methods would lead to financial data query failure, affecting the analysis efficiency. This invention overcomes the problems of low efficiency and query difficulty; (3) Excellent financial scenario adaptability: By constructing a financial domain thesaurus and financial business logic verification rules, customized design is carried out for the professionalism of financial data (such as indicator calculation and accounting period). The generated SQL statement conforms to the financial business specifications, avoiding the problem of "technically correct but business wrong", and adapting to various complex financial query needs; (4) Outstanding self-evolution capability: Through the failure memory bank and error pattern analysis mechanism, historical error correction experience can be recorded and reused. As the number of uses increases, the error identification and correction efficiency gradually improves, realizing the system's "self-optimization" and reducing long-term use costs.
[0036] Table 1 shows the comparative effects of the present invention and traditional methods in specific financial dataset scenarios.
[0037] Table 1
[0038]
[0039] Among them, the exact matching accuracy (EM%) metric requires that all clauses of the generated SQL be completely consistent with the standard answer to be considered correct, while the execution accuracy (EX%) metric requires that the execution result of the generated SQL be consistent with the execution result of the standard answer to be considered correct. This is more in line with actual use cases, further illustrating that the results obtained by this invention have higher accuracy. Attached Figure Description
[0040] The accompanying drawings, which are included to provide a further understanding of the invention and form part of this invention, illustrate exemplary embodiments of the invention and are used to explain the invention, but do not constitute an undue limitation of the invention. In the drawings:
[0041] Figure 1 A flowchart illustrating a multi-agent collaborative SQL generation and correction method for financial data analysis;
[0042] Figure 2 A schematic diagram of the structure of a multi-agent collaborative SQL generation and correction system for financial data analysis;
[0043] Figure 3 This is a schematic diagram of an embodiment of a multi-agent collaborative SQL generation and correction method for financial data analysis.
[0044] Figure 4 A schematic diagram illustrating an example of writing SQL to generate a balance sheet with a specified cutoff date;
[0045] Figure 5 This is a schematic diagram of an example of writing SQL to analyze the monthly cash flow of bank deposit accounts and calculate the month-on-month growth rate.
[0046] Figure descriptions: 1. Selector; 2. Decomposer; 3. Detector; 4. Query Builder; 5. Optimizer; 6. Statement Generation Module; 7. Error Correction Module. Detailed Implementation
[0047] To make the technical solutions and advantages of the embodiments of the present invention clearer, the exemplary embodiments of the present invention will be further described in detail below with reference to the accompanying drawings. Obviously, the described embodiments are only a part of the embodiments of the present invention, and not an exhaustive list of all embodiments. It should be noted that, unless otherwise specified, the embodiments and features in the embodiments of the present invention can be combined with each other.
[0048] Example 1: Reference Figures 1-5 This embodiment describes a multi-agent collaborative SQL generation and correction method for financial data analysis, specifically including the following steps:
[0049] S1. Based on user input and message dictionary, filter and determine the financial database using a selector, which includes the extracted database schema description string, foreign key information string, and the selected database schema dictionary;
[0050] S2. The financial database is broken down into multiple executable subtasks by a decomposer, and a corresponding complete SQL statement is generated for each subtask;
[0051] S3. The generated complete SQL statement is checked for errors by the detector. If an error is found, the erroneous SQL statement to be repaired will proceed to step S4 for correction. If no error is found, the process will proceed directly to step S5.
[0052] Specifically, the database schema dictionary filtered by the selector and the complete SQL statement are used as input to the detector;
[0053] S4. Based on the erroneous SQL statement to be repaired, the statement generation module automatically generates five query variants. The SQL execution result is obtained through the query builder, and the corrected SQL statement is obtained through the optimizer. The process is then returned to step S3 for re-detection by the detector until there are no errors, and then proceeds to step S5.
[0054] S5. Output the final correct SQL statement or query result.
[0055] Specifically, the overall workflow of this embodiment is as follows:
[0056] Input phase: The user inputs their financial query request in natural language, and the system loads the complete financial database;
[0057] Simplification and Decomposition Phase: The selector in the statement generation module filters relevant sub-databases, and the decomposer breaks down the query and generates the initial SQL;
[0058] Error detection phase: The error correction module's detector detects syntax and semantic errors in the initial SQL;
[0059] Refactoring and Validation Phase: The query builder generates query variants and drives the statement generation module to generate candidate SQL. The optimizer validates the candidate SQL and selects the optimal result.
[0060] Output phase: The system outputs the optimal SQL statement and updates the failure memory database at the same time;
[0061] The SQL statement generation method based on a large model provided by this invention includes the following steps:
[0062] Analyze the structure of the financial database and select the important tables and columns relevant to the query;
[0063] Determine whether schema pruning is needed based on database complexity. If pruning is needed, use an LLM model to analyze user queries and select the most relevant tables and columns.
[0064] The natural query is broken down into simpler sub-problems, the LLM is called to generate SQL queries, and the generated SQL statements are parsed and extracted.
[0065] The SQL statement detection and correction method based on a large model provided by this invention includes the following steps:
[0066] Execute the generated SQL query on the specified database and check the execution results, including whether data is returned and whether it contains null values;
[0067] If an error exists, call the query builder to write a new test case.
[0068] The query builder constructs the original problem into four different expressions to generate new SQL queries;
[0069] Execute the new query, retaining the query statements that can be executed correctly;
[0070] Pass the list of valid SQL variants to the optimizer for further processing;
[0071] The optimizer repairs the statements and retains failure records for reference;
[0072] The core function of the detector is to check whether the generated complete SQL statement is correct and determine whether further correction is needed. The implementation logic is as follows:
[0073] Check the SQL execution results for errors;
[0074] If an error is found, the task is sent to the query builder to write test cases;
[0075] If no errors are found, the prompt words are built and the large language model is invoked for further review;
[0076] Analyze the model response to determine if the SQL matches the problem intent;
[0077] The next step will be determined based on the review results: either end the process or continue the repair.
[0078] Furthermore, in S1, the user input includes the database path, the path to the table structure JSON file, the model name, and the dataset name;
[0079] The message dictionary includes: database ID, user query, additional evidence information, and preprocessed pattern information;
[0080] The user input and message dictionary are used as input to the selector, and after filtering by the selector, a sub-database (schema) highly relevant to the user query is obtained. ;
[0081] Sub-database Represented as:
[0082]
[0083] Among them, sub-database Set containing sublists Subsequence set T represents the table, and C represents the column. This is the core function of the selector, derived from the Large Language Model (LLM). drive, For natural language queries entered by the user, This is the original, complete database (including all tables T, columns C, and foreign key relationships). External knowledge (such as the financial calculation rule "net profit = revenue - cost").
[0084] Specifically, the core function of the selector is to analyze the database structure and select important tables and columns relevant to the query, providing concise and relevant database schema information for subsequent SQL generation. The implementation logic is as follows:
[0085] Read table structure information from the SQLite database file, including column names, data types, primary keys, foreign keys, etc.
[0086] Get sample values for the column to provide richer contextual information;
[0087] Determine whether pattern pruning is needed based on database complexity;
[0088] If pruning is needed, use an LLM model to analyze user queries and select the most relevant tables and columns;
[0089] Build a formatted database schema description and foreign key information for use by subsequent components.
[0090] Furthermore, in step S2, the user's natural language query, database schema description, foreign key information, and optional additional evidence are used as inputs to the decomposer, based on the sub-database. Get the complete SQL statement and large language models Conditional probability of generating SQL ;
[0091] Decomposer (based on sub-database only) The processing procedure for the task is represented as follows:
[0092]
[0093] in, This refers to the number of subproblems broken down by the decomposer; in this example, it is 1-5. A simple query will show this. Complex queries , This is the j-th sub-SQL (the SQL corresponding to the j-th sub-problem). All sub-SQLs generated before the j-th sub-SQL (reflecting the logical dependencies between sub-problems). For the j-th sub-question (the natural language query input by the user) (Disassembled)
[0094] Specifically, the core function of the decomposer is to break down natural language queries into simpler sub-problems and generate preliminary SQL queries based on the database schema. The implementation logic is as follows:
[0095] Select the appropriate prompt template based on the dataset type;
[0096] Combine user queries, database schema information, and foreign key information into a complete prompt;
[0097] Use the LLM model to generate SQL queries;
[0098] Parse and extract the generated SQL statement;
[0099] The generated SQL is passed to the next component for validation and optimization.
[0100] Furthermore, in step S4, the filtered database schema dictionary, database schema description, foreign key information, database path, additional evidence information, and the original user question composed of natural language are used as inputs to the query builder to obtain a valid SQL execution result.
[0101] Using large language models The original user question was rewritten into four different expressions, generating five SQL query variants;
[0102] The optimized SQL statement is obtained by taking the filtered database schema dictionary, database schema description, foreign key information, five SQL query variants, the currently valid SQL execution result, the index used for similarity retrieval, and the database path as input. ';
[0103] Corrected SQL statement Represented as:
[0104]
[0105] Where E represents SQL execution error messages (such as "table does not exist" or "field mismatch"). 'This is an incorrect SQL statement that needs to be repaired.'
[0106] Specifically, the core function of the optimizer is to repair problematic SQL statements based on historical error records and the current context. The implementation logic is as follows:
[0107] Maintain a historical error record in memory, containing similar problems and their correct SQL solutions;
[0108] During initialization, load training data and log execution errors;
[0109] The SimCSE model is used to calculate the similarity between the current problem and historical problems;
[0110] When SQL needs to be repaired, retrieve the most similar historical error cases for reference;
[0111] Multiple attempts will be made to repair the SQL, with a maximum of 3 attempts.
[0112] Record the failure history after each failure for reference in the next attempt;
[0113] Returns the final repair result or the original SQL;
[0114] The core functionality of the query builder lies in generating multiple SQL query variations by rephrasing the problem, increasing the chance of finding the correct answer. The implementation logic is as follows:
[0115] The original problem was rewritten into four different expressions using a large language model;
[0116] For each rewrite problem, the statement generation module generates the corresponding SQL query;
[0117] Execute each generated SQL statement and retain only the SQL statements that can be executed correctly;
[0118] The list of valid SQL execution results is passed to the optimizer for further processing.
[0119] refer to Figure 4 The user requested that SQL be written to generate a balance sheet with a specified cutoff date, and that the report only display the balances of asset, liability, and owner's equity accounts. The AI provided a complete MySQL query script based on this request, and explained that the data was taken from the voucher master table, voucher details table, and accounting chart, and that the required account data for the balance sheet was filtered out after summarizing and calculating the account balances.
[0120] The system provides SQL statements according to user requirements. These SQL statements are used to count posting vouchers completed before a specified date, calculate the balance of each accounting subject, and output the balance sheet details. First, the report statistics cutoff date is defined. Then, using common table expressions, the accounting subjects, voucher details, and vouchers are linked to filter out valid vouchers before the cutoff date. The cumulative debit and credit amounts of each subject are summarized and subtracted to obtain the subject balance. Finally, the three categories of subjects—assets, liabilities, and owner's equity—are filtered out, sorted according to the standard order of financial statements, and the subject type, subject name, and balance data that can be directly used to generate a balance sheet are output.
[0121] refer to Figure 5 The user's requirement was to write SQL to analyze the monthly cash flow of bank deposit accounts and calculate the month-on-month growth rate of the monthly cash flow. The AI outlined a four-step implementation approach, along with complete SQL code, to complete data extraction, summarization, and month-on-month calculation based on three data tables: accounting subjects, vouchers, and voucher details.
[0122] The system provides SQL statements according to user requirements. These SQL statements are used to calculate the net cash flow of bank deposit accounts on a monthly basis and to calculate the month-on-month growth rate. First, the system queries the account ID corresponding to the bank deposit account by account name and stores it in a variable. Then, it links the main voucher table and the voucher details table, filters the valid vouchers that have been posted under the account, and summarizes the difference between debit and credit entries for the current month by month and year to obtain the monthly net cash flow. Finally, it uses the LAG window function to retrieve the cash flow value of the previous month, applies the formula to calculate the month-on-month growth rate, and finally outputs three sets of data: month, current month net cash flow, and month-on-month growth rate, sorted by month.
[0123] Example 2: A multi-agent collaborative SQL generation and correction system for financial data analysis, used to execute the multi-agent collaborative SQL generation and correction method for financial data analysis described in Example 1, including a statement generation module 6 and an error correction module 7;
[0124] The statement generation module 6 includes a selector 1 and a decomposer 2 connected in sequence;
[0125] The error correction module 7 includes a detector 3, a query builder 4, and an optimizer 5. The detector 3 is connected to the query builder 4, the query builder 4 is connected to the optimizer 5, and the builder 4 is connected to the statement generation module 6.
[0126] Specifically, the system of this invention consists of five intelligent agents working together to form a collaborative Text-to-SQL parsing system that can automatically detect, analyze, and correct erroneous SQL queries, thereby improving the accuracy of text-to-SQL conversion. The statement generation module 6 is responsible for parsing the financial query intent and generating the initial SQL statement, while the error correction module 7 is responsible for detecting, correcting, and verifying SQL statement errors. The two main modules work together through a data interaction interface.
[0127] Although the invention has been described with reference to a limited number of embodiments, those skilled in the art will understand from the foregoing description that other embodiments are conceivable within the scope of the invention described herein. Furthermore, it should be noted that the language used in this specification has been chosen primarily for readability and edibility purposes, and not for the purpose of interpreting or limiting the subject matter of the invention. Therefore, many modifications and variations will be apparent to those skilled in the art without departing from the scope and spirit of the appended claims. The disclosure of the invention is illustrative and not restrictive, and the scope of the invention is defined by the appended claims.
Claims
1. A multi-agent collaborative SQL generation and correction method for financial data analysis, characterized in that, Includes the following steps: S1. Based on user input and message dictionary, filter and determine the financial database using a selector, which includes the extracted database schema description string, foreign key information string, and the selected database schema dictionary; S2. The financial database is broken down into multiple executable subtasks by a decomposer, and a corresponding complete SQL statement is generated for each subtask; S3. The generated complete SQL statement is checked for errors by the detector. If an error is found, the erroneous SQL statement to be repaired will proceed to step S4 for correction. If no error is found, the process will proceed directly to step S5. Specifically, the database schema dictionary filtered by the selector and the complete SQL statement are used as input to the detector; S4. Based on the erroneous SQL statement to be repaired, the statement generation module automatically generates five query variants. The SQL execution result is obtained through the query builder, and the corrected SQL statement is obtained through the optimizer. The process is then returned to step S3 for re-detection by the detector until there are no errors, and then proceeds to step S5. S5. Output the final correct SQL statement or query result.
2. The method for generating and correcting multi-agent collaborative SQL for financial data analysis according to claim 1, characterized in that, In S1, the user input includes the database path, the table structure JSON file path, the model name, and the dataset name; The message dictionary includes: database ID, user query, additional evidence information, and preprocessed pattern information; Using user input and a message dictionary as input to a selector, the selector filters the data to obtain a sub-database highly relevant to the user query. ; Sub-database Represented as: Among them, sub-database Set containing sublists Subsequence set T represents the table, and C represents the column. The core function of the selector is derived from the large language model. drive, For natural language queries entered by the user, For the original and complete database, External knowledge.
3. The method for generating and correcting multi-agent collaborative SQL for financial data analysis according to claim 2, characterized in that, In step S2, the user's natural language query, database schema description, foreign key information, and optional additional evidence are used as inputs to the decomposer, based on the sub-database. Get the complete SQL statement and large language models Conditional probability of generating SQL ; The process of the resolver is represented as follows: in, The number of subproblems that the decomposer breaks down. For the j-th sub-SQL, For all sub-SQLs generated before the j-th sub-SQL, Let j be the j-th subproblem.
4. The method for generating and correcting multi-agent collaborative SQL for financial data analysis according to claim 3, characterized in that, In step S4, the filtered database schema dictionary, database schema description, foreign key information, database path, additional evidence information, and the original user question in natural language are used as inputs to the query builder to obtain a valid SQL execution result. Using large language models The original user question was rewritten into four different expressions, generating five SQL query variants; The optimized SQL statement is obtained by taking the filtered database schema dictionary, database schema description, foreign key information, five SQL query variants, the currently valid SQL execution result, the index used for similarity retrieval, and the database path as input. '; Corrected SQL statement Represented as: Where E represents SQL execution error messages (such as "table does not exist" or "field mismatch"). 'This is an incorrect SQL statement that needs to be repaired.' 5. A multi-agent collaborative SQL generation and correction system for financial data analysis, characterized in that, The method for generating and correcting multi-agent collaborative SQL for financial data analysis as described in any one of claims 1-4 includes a statement generation module (6) and an error correction module (7). The statement generation module (6) includes a selector (1) and a decomposer (2) connected in sequence. The error correction module (7) includes a detector (3), a query builder (4) and an optimizer (5). The detector (3) is connected to the query builder (4), the query builder (4) is connected to the optimizer (5), and the builder (4) is connected to the statement generation module (6).