SQL conversion and query method and device based on multi-agent cooperation, equipment and medium

By employing a multi-agent collaborative approach, the accuracy and robustness issues of natural language to SQL conversion in large-scale e-commerce, retail, and SaaS data platforms were addressed, enabling efficient querying and interpretable analysis of complex data warehouses.

CN122220360APending Publication Date: 2026-06-16SHANGHAI WEIMOB ENTERPRISE DEV CO LTD
View PDF 0 Cites 0 Cited by

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
SHANGHAI WEIMOB ENTERPRISE DEV CO LTD
Filing Date
2026-03-13
Publication Date
2026-06-16

AI Technical Summary

Technical Problem

Existing technologies for converting natural language to SQL in large-scale e-commerce, retail, and SaaS data platforms suffer from problems such as inability to handle large-scale table structures, information noise, cross-domain mixing, and lack of interaction and correction mechanisms. This results in insufficient accuracy and robustness of SQL conversion, making it difficult to handle ambiguous queries.

Method used

A multi-agent collaborative approach is adopted, which uses a semantic mapping engine to map industry slang and terminology and perform Self-Ask, combined with a schema filtering engine for multi-level filtering, an SQL generation engine for adaptive correction, and an SQL execution agent to execute queries. Finally, a chart generation engine performs analysis and plotting.

Benefits of technology

It improves the accuracy and robustness of SQL transformation, enhances the interpretability of database queries, and can effectively handle query requirements in complex data warehouses.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122220360A_ABST
    Figure CN122220360A_ABST
Patent Text Reader

Abstract

The application discloses a SQL conversion and query method and device based on multi-agent cooperation, equipment and medium, relates to the computer technical field, including: based on the semantic mapping engine, the industry slang and term mapping, Self-Ask, for the semantic enhancement after the query in the semantic mapping result, based on Schema screening engine, the preset mixed retrieval mechanism carries out screening;Based on the corresponding target screening result, SQL generation engine, the preset verification engine, large language model, semantic mapping result, the conversion and adaptive correction of SQL are carried out to determine the target SQL query;Based on the SQL execution agent and the target SQL query, the database query is carried out, based on the chart generation engine and the corresponding database query result, the target chart generation result is output.The application can solve the problems existing in the prior art, improve the accuracy and robustness of SQL conversion, and improve the explainability of database query.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of computer technology, and in particular to a method, apparatus, device, and medium for SQL conversion and querying based on multi-agent collaboration. Background Technology

[0002] For large e-commerce, retail, and SaaS (Software as a Service) data platforms, there are typically extremely complex data warehouses containing hundreds of business domains, hundreds of fact and dimension tables, and hundreds of fields with complex relationships. Due to the increasing demand for self-service data analysis from business users, these data are often expressed in natural language and contain a large amount of industry jargon and contextual dependencies.

[0003] However, existing solutions for converting natural language to SQL (Structured Query Language) based on large language models suffer from the following main problems: 1) Solutions relying on full schema hints: limited by the context window, they cannot handle large-scale table structures; numerous irrelevant fields create information noise, leading to the model selecting the wrong table or field; and they cannot be extended. 2) Solutions relying on simple vector retrieval: relying solely on semantic similarity, they easily miss strongly related tables with unclear descriptions; they lack control over the domain level, easily leading to cross-domain misuse. 3) Lack of interaction and correction mechanisms: these solutions are mostly generated in a one-time manner, lacking self-ask and multi-turn reasoning (ReAct), making it difficult to handle ambiguous queries. Summary of the Invention

[0004] In view of this, the purpose of this invention is to provide a method, apparatus, device, and medium for SQL conversion and querying based on multi-agent collaboration, which can solve the problems existing in existing related solutions, improve the accuracy and robustness of SQL conversion, and improve the interpretability of database queries. The specific solution is as follows: Firstly, this application provides a SQL transformation and query method based on multi-agent collaboration, including: Based on the semantic mapping engine, the natural language query to be processed and the context information are mapped to industry slang and terminology, and then Self-Ask is performed to determine the semantic mapping result; the semantic mapping result includes the semantically enhanced query. Based on the schema filtering engine, the preset hybrid retrieval mechanism, and the preset intelligent agent tool, the semantically enhanced query is filtered in multiple layers to determine the target filtering results; the schema filtering engine includes a domain filtering agent, a table filtering agent, and a field filtering agent. Based on the SQL generation engine, the preset verification engine, the large language model, the semantic mapping result, and the target filtering result, the SQL is transformed and adaptively corrected to determine the target SQL query corresponding to the natural language query. Based on the SQL execution agent and the target SQL query, a database query is performed to determine the database query result; Based on the chart generation engine, the database query results are analyzed and plotted to determine and output the target chart generation result.

[0005] Optionally, the semantic mapping engine performs industry slang and terminology mapping and Self-Ask on the natural language query and context information to be processed, in order to determine the semantic mapping result, including: Based on the semantic mapping engine, the dialogue history information corresponding to the natural language query is formatted to determine the mapping input information; Based on the mapping input information, the industry slang mapper and terminology mapper in the semantic mapping engine, the mapping of industry slang and terminology is performed to determine the initial mapping result; Based on the semantic agent in the semantic mapping engine, the initial mapping result is processed using Self-Ask to determine the processing result; Based on the processing result and the semantic agent in the semantic mapping engine, determine whether to call the preset mapping tool and the preset knowledge base tool to determine the tool call judgment result; If the tool call judgment result is negative, then based on the semantic agent and the initial mapping result, multiple rounds of reasoning are performed to determine the semantic mapping result; the semantic mapping result includes semantically enhanced query, structured semantic representation, fuzzy terms, the processing result, entity parsing result, and confidence level.

[0006] Optionally, the schema-based filtering engine, the preset hybrid retrieval mechanism, and the preset intelligent agent tool perform multi-level filtering on the semantically enhanced query to determine the target filtering results, including: Based on a preset hybrid retrieval mechanism, the semantically enhanced query is retrieved to determine the domain candidate set, table candidate set, and field candidate set. Based on the domain filtering agent, the semantically enhanced query, the entity parsing result, and the domain candidate set, domain filtering is performed to determine the target domain set. For any domain name in the target domain set, a list of table names corresponding to the current domain name is determined based on the table filtering agent, the semantically enhanced query, the entity parsing result, and the table candidate set; For any table name in the list of table names, field filtering is performed based on the field filtering agent, the semantically enhanced query, the entity parsing result, the field candidate set, the fuzzy terms, and the preset agent tool to determine the field filtering result corresponding to the current table name; The preset intelligent agent tools include table information acquisition tools; Based on the target domain set, the table name list, and the field filtering results, the target filtering results are determined.

[0007] Optionally, the step of performing SQL conversion and adaptive correction based on the SQL generation engine, the preset validation engine, the large language model, the semantic mapping result, and the target filtering result includes: Based on the large language model, the semantic mapping results, the target filtering results, and the planning and reasoning agents in the SQL generation engine, the initial SQL query is determined; Based on a preset verification engine, the initial SQL query is subjected to syntax and logic verification to determine the current logic verification result. If the current logical verification result indicates that the verification is successful, then the trial run corresponding to the initial SQL query is triggered based on the preset verification engine; When the trial run error information corresponding to the initial SQL query is captured, the inference agent, the trial run error information and the preset agent tool are used to perform error analysis to determine the error analysis result. Based on the reasoning agent and the error analysis results, the initial SQL query is corrected to determine the corrected SQL query; Based on a preset validation engine, the modified SQL query is subjected to syntax and logic validation to determine the current logic validation result. If the current logical verification result indicates that the verification is successful, then the trial run of the corrected SQL query is triggered based on the preset verification engine. If the modified SQL query is successfully tested, then the modified SQL query will be identified as the target SQL query.

[0008] Optionally, determining the initial SQL query based on the large language model, the semantic mapping result, the target filtering result, and the planning agent and reasoning agent in the SQL generation engine includes: Based on the structured semantic representation, the natural language query, and the reasoning agent, the visual intent is identified to determine the intent identification result; Based on the planning agent, the large language model, the structured semantic representation, the target filtering results, and the preset agent tools, the query content and query structure are planned to determine the initial SQL query; the preset agent tools include a domain information acquisition tool, a table information acquisition tool, and a similar SQL acquisition tool.

[0009] Optionally, the step of performing a database query based on the SQL execution agent and the target SQL query to determine the database query result includes: Based on an SQL execution agent, the target SQL query is executed on the target database or target database repository to determine the initial query results; The initial query results are encapsulated based on a preset data format to determine the database query results.

[0010] Optionally, the step of analyzing and plotting the database query results based on the chart generation engine to determine and output the target chart generation result includes: The database query results are analyzed based on the chart generation engine to determine the analysis results; Based on the chart generation engine, the analysis results, and the preset chart type filtering strategy, a chart is generated to determine and output the target chart generation result.

[0011] Secondly, this application provides a SQL transformation and query device based on multi-agent cooperation, comprising: The semantic mapping module is used to perform industry slang and terminology mapping and Self-Ask on the natural language query to be processed and the context information based on the semantic mapping engine, so as to determine the semantic mapping result; the semantic mapping result includes the semantically enhanced query; The data filtering module is used to perform multi-level filtering on the semantically enhanced query based on the schema filtering engine, the preset hybrid retrieval mechanism, and the preset intelligent agent tool to determine the target filtering results; the schema filtering engine includes a domain filtering intelligent agent, a table filtering intelligent agent, and a field filtering intelligent agent. The SQL conversion module is used to convert and adaptively correct SQL based on the SQL generation engine, the preset validation engine, the large language model, the semantic mapping result, and the target filtering result, so as to determine the target SQL query corresponding to the natural language query. The query result determination module is used to perform a database query based on the SQL execution agent and the target SQL query in order to determine the database query result; The chart generation module is used to analyze and plot the database query results based on the chart generation engine, so as to determine and output the target chart generation result.

[0012] Thirdly, this application provides an electronic device, comprising: Memory, used to store computer programs; A processor is used to execute the computer program to implement the steps of the aforementioned SQL transformation and query method based on multi-agent cooperation.

[0013] Fourthly, this application provides a computer-readable storage medium for storing a computer program, which, when executed by a processor, implements the steps of the aforementioned SQL transformation and query method based on multi-agent cooperation.

[0014] As can be seen, in this application, based on a semantic mapping engine, industry slang and terminology mapping and Self-Ask are performed on the natural language query and context information to be processed to determine the semantic mapping result; the semantic mapping result includes the semantically enhanced query; based on a schema filtering engine, a preset hybrid retrieval mechanism, and a preset intelligent agent tool, the semantically enhanced query is subjected to multi-level filtering to determine the target filtering result; the schema filtering engine includes a domain filtering agent, a table filtering agent, and a field filtering agent; based on an SQL generation engine, a preset validation engine, a large language model, the semantic mapping result, and the target filtering result, SQL is converted and adaptively corrected to determine the target SQL query corresponding to the natural language query; based on an SQL execution agent and the target SQL query, a database query is performed to determine the database query result; based on a chart generation engine, the database query result is analyzed and plotted to determine and output the target chart generation result. In other words, this application first uses a semantic mapping engine to map industry slang and terminology to the natural language query to be processed, and performs Self-Ask. Then, a schema filtering engine and a preset hybrid retrieval mechanism are used to filter the semantically enhanced query by domain, table, and field to determine the target filtering results. Next, an SQL generation engine, a preset validation engine, the semantic mapping results, and the target filtering results are used to perform SQL transformation and adaptive correction to determine the target SQL query. Finally, the target SQL query is executed, and charts are generated from the corresponding database query results. This approach solves the problems existing in related solutions, improves the accuracy and robustness of SQL transformation, and enhances the interpretability of database queries. Attached Figure Description

[0015] To more clearly illustrate the technical solutions in the embodiments of the present invention or the prior art, the drawings used in the description of the embodiments or the prior art will be briefly introduced below. Obviously, the drawings described below are only embodiments of the present invention. For those skilled in the art, other drawings can be obtained based on the provided drawings without creative effort.

[0016] Figure 1 A flowchart of a SQL transformation and query method based on multi-agent collaboration provided for this application; Figure 2 A schematic diagram of the structure of a SQL conversion and query device based on multi-agent collaboration provided in this application; Figure 3 This application provides a structural diagram of an electronic device. Detailed Implementation

[0017] The technical solutions of the embodiments of the present invention will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some embodiments of the present invention, and not all embodiments. Based on the embodiments of the present invention, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of the present invention.

[0018] Existing solutions for natural language to SQL conversion based on large language models suffer from the following main problems: 1) Solutions using full schema hints: limited by the context window, they cannot handle large-scale table structures; numerous irrelevant fields cause information noise, leading to the model selecting the wrong table or field; and they cannot be extended. 2) Simple vector retrieval solutions: relying solely on semantic similarity, they easily miss strongly related tables with unclear descriptions; they lack control over the domain level, easily leading to cross-domain misuse. 3) Lack of interaction and correction mechanisms: these solutions are mostly generated in a one-time manner, lacking self-ask and multi-turn reasoning, making it difficult to handle ambiguous queries. Therefore, this application provides a SQL conversion and query solution based on multi-agent collaboration, which can solve the problems existing in existing solutions, improve the accuracy and robustness of SQL conversion, and enhance the interpretability of database queries.

[0019] See Figure 1 As shown, this embodiment of the invention discloses a SQL transformation and query method based on multi-agent collaboration, including: Step S11: Based on the semantic mapping engine, perform industry slang and terminology mapping and Self-Ask on the natural language query and context information to be processed to determine the semantic mapping result; the semantic mapping result includes the semantically enhanced query.

[0020] In this embodiment, when a user initiates a natural language query Q, the semantic mapping engine is first invoked: it performs industry slang mapping, terminology explanation, self-Ask, and entity parsing on Q and its context to output semantic mapping results. These results include an enhanced query and a structured semantic representation (MappedQuery). Specifically, based on the semantic mapping engine, the dialogue history information corresponding to the natural language query is formatted to determine the mapping input information; based on the mapping input information, the industry slang mapper, and the terminology mapper in the semantic mapping engine... The process involves mapping industry slang and terminology to determine an initial mapping result; then, based on the semantic agent in the semantic mapping engine, performing Self-Ask processing on the initial mapping result to determine a processing result; finally, based on the processing result and the semantic agent in the semantic mapping engine, determining whether to call a preset mapping tool and a preset knowledge base tool to determine a tool call judgment result; if the tool call judgment result is negative, then performing multiple rounds of reasoning based on the semantic agent and the initial mapping result to determine the semantic mapping result; the semantic mapping result includes semantically enhanced query, structured semantic representation, fuzzy terms, the processing result, entity parsing result, and confidence level.

[0021] It is important to understand that the semantic mapping engine is based on a state graph orchestration, integrating industry slang mapping (JargonMapper) and term interpretation (TermMapper). On the other hand, it constructs a unified semantic agent, which performs Self-Ask and multi-turn inference (ReAct) within a single node, mapping ambiguous time expressions and abbreviations to standard semantic representations (MappedQuery) and calculating confidence.

[0022] Furthermore, regarding the implementation of LangGraph (a graph orchestration framework for multi-agent systems) in the semantic mapping engine and the design of a unified semantic agent: 1) State definition: This engine uses 'dataclass' to define the global state 'SemanticState', and key fields include: ① Input fields: query: the user's original query; context: context information (such as brief schema information, user profile, etc.); history: dialogue history, used for pronoun resolution and context completion.

[0023] ② Intermediate state: : A list of input texts used for mapping (merging query and history); : Semantic-enhanced queries; A collection of industry slang mapping results; : A collection of terminology explanation results; : Remaining list of ambiguous terms; clarifications: Clarification questions and answers generated by Self-Ask; : The parsed list of entities (including entity names and business descriptions).

[0024] ③ Output fields: : Structured MappedQueryOutput; confidence: overall confidence level; errors: list of errors and exceptions.

[0025] In addition, using 'Annotated[list[T],operator.add]' to declare an accumulative list field allows the results returned by parallel nodes to be automatically merged, simplifying the data aggregation logic for multiple nodes in the graph.

[0026] 2) LangGraph graph structure: This semantic mapping engine uses StateGraph to construct the following process: ① The prepare node: combines the query with the most recent few rounds of history to generate mapping input information, that is... Format historical dialogues and mark roles and content.

[0027] ② Parallel mapping nodes: :based on Perform industry slang string mapping to map GMV (Gross Merchandise Volume) and UV (Unique Visitor) to standard metrics; :based on Perform terminology interpretation and standardization.

[0028] ③、 Node (Unified Semantic Agent): First, use the Self-Ask method to determine whether the current information is sufficient to understand the user's intent; If there is ambiguity or missing information, raise clarification questions and simulate answers internally, or trigger the upstream clarification mechanism; Use mapping and knowledge base tools as needed to complete the remaining terms and entities; Output structured semantic mapping results, including semantically enhanced queries ( ), processing results (clarifications), fuzzy terms ( ), entity parsing results ( Fields such as confidence level.

[0029] The unified semantic agent completes Self-Ask and ReAct reasoning in one node, maintaining the continuity of the reasoning chain, and centrally records all reasoning processes and tool call records, which facilitates debugging and auditing.

[0030] Step S12: Based on the schema filtering engine, the preset hybrid retrieval mechanism, and the preset intelligent agent tool, perform multi-level filtering on the semantically enhanced query to determine the target filtering result; the schema filtering engine includes a domain filtering intelligent agent, a table filtering intelligent agent, and a field filtering intelligent agent.

[0031] In this embodiment, the Schema Filter Engine (SchemaFilterEngine) is then triggered: Candidate filtering of domains, tables, and fields is performed through vector retrieval, keyword retrieval, and relation retrieval. Specifically: Based on a preset hybrid retrieval mechanism, the semantically enhanced query is retrieved to determine a candidate set of domains, a candidate set of tables, and a candidate set of fields; based on the domain filtering agent, the semantically enhanced query, the entity parsing result, and the domain candidate set, domain filtering is performed to determine a target domain set; for any domain name in the target domain set, a list of table names corresponding to the current domain name is determined based on the table filtering agent, the semantically enhanced query, the entity parsing result, and the table candidate set; for any table name in the table name list, field filtering is performed based on the field filtering agent, the semantically enhanced query, the entity parsing result, the field candidate set, the fuzzy terms, and a preset agent tool to determine the field filtering result corresponding to the current table name; wherein, the preset agent tool includes a table information acquisition tool; and based on the target domain set, the table name list, and the field filtering result, the target filtering result is determined.

[0032] It's important to understand that the schema filtering engine employs a three-tiered filtering agent structure: Domain → Table → Field. Specifically: The DomainFilterAgent filters relevant domains from candidate domains based on semantic retrieval results. The TableFilterAgent performs fine-grained filtering by distinguishing between fact tables and dimension tables within a specific domain. The FieldFilterAgent further filters specific fields and, in conjunction with the get_table_detailed tool (a table information retrieval tool), retrieves metadata such as enumeration values ​​and dimension relationships as needed.

[0033] Furthermore, regarding the multi-agent design of the schema filtering engine: (1) Domain-selecting intelligent agents.

[0034] ① Input fields: Query after semantic enhancement; The list of entities parsed by the semantic mapping engine, such as time range, business metrics, and dimensions; A collection of candidate domains obtained through search engines such as Milvus, including names, descriptions, relevant fact tables, and dimension table summaries.

[0035] ② The agent adopts a tool-free structured output mode: use (DomainFilterResult) enforces constraints on the output format; System Prompt establishes fixed judgment rules, such as 'prioritizing ensuring no relevant areas are omitted' and 'prioritizing the matching of indicators and dimensions'; User Prompt dynamically injects query content and candidate domains.

[0036] ③ Decision-making logic includes: 1. If a certain field's true abstract or data table summary If a domain contains a description that highly matches the query metrics / dimensions, that domain will be retained first. 2. For domains with moderate semantic matching but potentially weak relevance to the query, retention is preferred when uncertainty arises to avoid over-filtering; 3. Returns a list of one or more candidate domain names, such as ["Product Domain", "Order Domain"].

[0037] (2) Filter the intelligent agent.

[0038] ① Input fields: Query after semantic enhancement; Entity parsing results; : A single target domain name; : A collection of table-level search results related to this field.

[0039] ② Key features: Single-domain focus: Each agent call processes only one domain. This helps avoid the LLM's focus being scattered across multiple domains; Toolless mode + Pydantic structured output: Returns a list of table names, such as ; Pre-filtering strategy: Used before entering LLM Remove those that do not belong The table.

[0040] ③ The decision-making basis includes: 1. Metric matching: Does the fact table's 'metrics' cover the key metrics in the query? 2. Dimension matching: Whether the 'dimensions' of the dimension table appear in the query entities or filter conditions; 3. Understanding table types: Distinguish between fact tables used for measurement and dimension tables used for supplementary descriptions and JOIN operations; 4. Search score: Semantic search score is used as an auxiliary judgment, without setting a hard threshold.

[0041] (3) Field filtering agent.

[0042] ① Input fields: Query after semantic enhancement; Entity parsing results; Target domain; : List of table names already filtered by the filtering agent; Field-level search results include field name, description, type, enumeration value, and association relationship; : Ambiguous terms that have not yet been resolved (reserved interface).

[0043] ② The agent adopts a tool-based model, and its main tools include: 1. : Retrieve complete field information and field metadata (such as enumeration values) of a table as needed. ), dimensional association ( Is this field required? )wait); 2. Submit the final screening results.

[0044] ③ Overview of the Agent's Logic: 1. Initial stage according to Based on the scores, select candidate fields that are highly relevant to the query; 2. If information is insufficient for important tables or key fields, retrieve information as needed. Retrieve complete field metadata; 3. Divide the fields into: Metric fields: Data used for calculation or display; Dimension fields: used for grouping, filtering, and association; Required field: i.e., ' Fields marked with '=True' should be automatically included unless there is an explicit requirement to exclude them. Related fields: those with ' ', used for JOIN dimension tables.

[0045] 4. Combining the entity parsing results and business semantics, generate a field list mapping for each table. The relevant code statements are shown below: ; Through the three-layer filtering described above, SchemaFilterEngine compresses the original large-scale schema into a small number of domains, tables, and fields, providing a high-quality context for subsequent SQL generation.

[0046] Regarding the preset hybrid retrieval mechanism, Milvus hybrid search is introduced in the knowledge retrieval layer (SearchKB). It supports sparse vector (BM25), dense vector (Embedding), and RRF (Reciprocal Rank Fusion) modes. This is achieved through hybrid detailed search (…). The sparse and dense scoring mode preserves the details of the scores, assisting the agent in making more accurate decisions.

[0047] Furthermore, regarding knowledge base search integrating the preset hybrid retrieval mechanism and RRF: (1) Search mode design: MilvusHelper encapsulates multiple search modes: 1) Sparse: Keyword search based on sparse vectors (BM25), suitable for matching precise keywords and field names; 2) Dense: Semantic search based on dense vectors (Embedding), suitable for matching semantically similar descriptive text; 3) Hybrid: Using Milvus native... The ability to merge sparse and dense results by weight; 4) Perform sparse and dense searches separately, combine the results locally with weighted values, and retain them in the metadata. , And detailed information such as weights; 5) Based on the RRF algorithm, different search results are merged, relying only on the ranking position to avoid alignment problems between different score scales.

[0048] (2) Application in this embodiment; 1) In domain, table, and field retrieval, you can select hybrid, ... ,or Patterns are used to balance semantic matching and keyword matching; 2) For key metric fields (such as GMV, payment amount, number of visitors), a hybrid mode can be used to improve recall rate, and semantic judgment can be performed at the upper layer through LLM; 3) For fields with rich metadata (including enumeration values, relationships, etc.), The detailed scores provided by the model help the agent make more sophisticated choices.

[0049] Through the hybrid retrieval mechanism described above, this embodiment significantly improves relevance and robustness while maintaining search performance, providing a high-quality candidate set for subsequent agent decision-making.

[0050] Furthermore, regarding the design and context management of pre-defined intelligent agent tools, in this embodiment: (1) Tool design principles.

[0051] Optimize agent cognition: The input and output of tools should be as close as possible to the business semantics, rather than the underlying technical details; High signal return: The tool only returns the information needed to make the current decision, avoiding returning all the data at once; Clear namespaces: Tool names reflect business semantics and scope, such as... , wait.

[0052] (2) Context management strategy.

[0053] Just-in-Time Retrieval: This tool is invoked only when absolutely necessary to load detailed information about a file or table; Sub-agent architecture: Complex tasks are broken down into multiple specialized agents (such as semantic mapping and schema filtering), with each agent working in a clean context window; Context compression: When the conversation history is long, compress key decisions, unresolved issues, and brief summaries into short texts to avoid context decay.

[0054] (3) Evaluation and iteration.

[0055] The evaluation task set is constructed based on real-world data, such as multi-industry idiom query, cross-domain query, and complex time condition query. By recording the agent's reasoning process and tool call sequences, failure modes are analyzed and the tool design and prompts are optimized in reverse. By utilizing the structured status recording capabilities of this embodiment, playback and audit reports can be automatically generated.

[0056] Step S13: Based on the SQL generation engine, preset verification engine, large language model, semantic mapping result and target filtering result, perform SQL conversion and adaptive correction to determine the target SQL query corresponding to the natural language query.

[0057] In this embodiment, the filtering results from the MappedQuery and Schema filtering engines are input into the SQL generation engine (SQLGenerationEngine) to generate candidate SQL. If necessary, historical SQL is used for alignment and optimization. The SQL validation engine (SQLValidationEngine) then performs trial runs, syntax checks, and result analysis on the generated SQL to automatically correct potential problems or revert to regeneration. Specifically: based on the structured semantic representation, the natural language query, and the reasoning agent, visual intent is identified to determine the intent identification result; based on the planning agent, the large language model, the structured semantic representation, the target filtering results, and the preset agent tools, query content and query structure are planned to determine the initial SQL query; the preset agent tools include a domain information acquisition tool, a table information acquisition tool, and a similar SQL acquisition tool. The tool performs syntax and logic checks on the initial SQL query based on a preset validation engine to determine the current logic validation result. If the current logic validation result indicates that the validation is successful, a trial run corresponding to the initial SQL query is triggered based on the preset validation engine. When trial run error information corresponding to the initial SQL query is captured, error analysis is performed using the inference agent, the trial run error information, and the preset agent tool to determine the error analysis result. Based on the inference agent and the error analysis result, the initial SQL query is corrected to determine the corrected SQL query. The corrected SQL query is then performed syntax and logic checks on the preset validation engine to determine the current logic validation result. If the current logic validation result indicates that the validation is successful, a trial run corresponding to the corrected SQL query is triggered based on the preset validation engine. If the trial run of the corrected SQL query is successful, the corrected SQL query is identified as the target SQL query.

[0058] It is important to understand the SQL generation engine, its location, and its specific implementation in this embodiment: 1) During the SQL generation phase, how does the LLM call tools as needed to obtain supplementary context such as Domain information, table information, and field information? 2) After the SQL is executed, the result is output as a DataFrame (a two-dimensional tabular data structure, hereinafter referred to as df) to facilitate the generation of subsequent reports and visualizations.

[0059] Furthermore, the SQL generation engine is structured as a 'Planner + Executor + Reflexion', which can be broken down into several roles or intelligent agents: (1) Planning agent, which reads MappedQuery (structured semantic representation) and (Schema filtering results); plan the fact tables and dimension tables, JOIN relationships, filtering conditions, aggregation methods, and sorting and pagination strategies required for the query; decide whether further details about domains, tables, or fields are needed.

[0060] (2) Execute the agent, which receives the planned SQL or SQL template; calls the underlying database connection pool to execute the SQL; and converts the result into a standardized df type (e.g., pandas.DataFrame or equivalent table structure).

[0061] (3) Reasoning agent (also known as reflective correction agent): This agent combines the error information and execution samples provided by the SQL retrieval engine to correct the SQL; and if necessary, it rolls back to the planning agent to replan.

[0062] The aforementioned intelligent agents exist as nodes within orchestration frameworks such as LangGraph, forming a closed loop from planning to execution to reflection and correction.

[0063] Furthermore, regarding the tool invocation mechanism in the SQL generation phase, to avoid passing all schema details at once during SQL generation, this invention designs a set of tools that can be invoked on demand, enabling the LLM to obtain necessary supplementary information at any time during SQL generation. Typical tools include, but are not limited to: 1) Input: Domain name, such as 'Product Domain'; Output: Core business description, key fact table and dimension table list, common indicators and dimension descriptions for this domain; Purpose: When only the business intent is given in MappedQuery without specifying the domain, it helps the planning agent to determine whether SQL should be generated within a single domain, or to determine whether cross-domain queries are involved.

[0064] 2) Input: Table name, such as Output: Table type (facts / dimensions), primary and foreign key relationships, common JOIN relationships with other tables, list of key fields; Purpose: To provide high-signal structural information for LLM when planning JOIN paths and filtering conditions, avoiding incorrect associations.

[0065] 3) Input: Table name and field names; Output: Field type, business meaning, and whether it is required. ), enumeration values ​​( ), dimensional association ( (e.g., WHERE conditions, GROUPBY fields, and measure fields) Purpose: To assist LLM in understanding the meaning and constraints of fields when determining WHERE conditions, GROUPBY fields, and measure fields.

[0066] 4) (Optional): Input: Signatures based on MappedQuery (including metrics, dimensions, and time ranges); Output: Similar SQL snippets executed historically and their performance metrics; Purpose: To provide referenceable SQL templates for LLM during the planning phase, improving generation quality and performance controllability.

[0067] 5) Input: The SQL text to be executed and the optional `limit` number of rows; Output: The original execution result (row set) or the internally normalized 'df'; Purpose: It can be used for small-sample dry-run in the planning phase, and for formal execution and generation of DataFrame in the final stage.

[0068] Based on this, the planning agent follows the following strategy in the SQL generation process: 1) First, try to use MappedQuery and 1) Complete SQL planning within the current context; 2) Actively invoke the above tools when encountering the following situations: when it is necessary to confirm whether a certain domain contains specific indicators or dimensions. When AA needs to confirm JOIN relationships or table granularity, call... When you need to understand the business meaning or enumeration value of a field, call... When you want to reuse historical best practice SQL, call 3) After the planning is completed, the SQL draft and its reasoning process are recorded in the state so that the SQL retrieval engine and reasoning agent can use them later.

[0069] Through the above-mentioned tool-based design, the SQL generation stage is decoupled from schema management and historical experience base, while maintaining high signal and low noise context input, which is in line with the overall architecture concept of 'on-demand retrieval + progressive focus' proposed in this embodiment.

[0070] Furthermore, regarding the SQL inference agent based on visualization requirements, this embodiment introduces an LLM-based SQL inference agent during the SQL generation stage. This agent is responsible for automatically planning a data structure that meets the requirements of the front-end components based on the visualization intent in the query (such as line charts, trend charts, and comparison charts), and generating matching SQL. The core capabilities of this agent include: 1) Visual intent recognition: Extract visualization-related information from the original query and MappedQuery, such as 'line chart', 'trend', 'change', 'comparison with last month', etc.; map the intent to standard chart types (such as line chart, bar / column chart, pie chart) and their parameters (such as time granularity, comparison dimension, etc.).

[0071] 2) Chart-driven SQL structure planning: For line charts / trend-based requirements: automatically select the time dimension field as the horizontal axis (e.g., 'dd', 'date', '...'). 'etc.), and if necessary, through Validate field types; infer the time granularity (day / week / month) and use the corresponding date truncation function or enumeration condition in the SQL; output a structure in the SELECT clause that at least contains 'horizontal axis time column + one or more indicator columns', and ensure that ORDER BY time column is ASCII; for multi-series line charts or comparison requirements (such as 'channel-specific trend comparison'): identify grouping dimension fields (such as 'channel', '...') ',' Add the corresponding GROUPBY field to the SQL to allow the results to be split into different series; ensure the output structure conforms to the expected format of the chart components, for example: column structure: 'date', 'channel', and ' ', or a wide table structure with column aliases: 'date', ' 'and' '.

[0072] 3) Component-oriented output contract: Define the data schema that the chart component can accept internally (e.g., ... (The agent specifies fields such as series and value). When generating SQL, it will explicitly constrain the SELECT columns so that the SQL results can be mapped to the data schema without loss.

[0073] Through the above mechanism, this embodiment ensures that the conversion from natural language to SQL not only meets the semantic correctness, but also takes into account the structural requirements that it can be directly used in report components such as line charts, reducing post-processing logic.

[0074] Furthermore, regarding the error-driven SQL iterative adjustment mechanism, in this embodiment, even with meticulous planning, the initially generated SQL may still fail to execute due to differences in field names, table names, permissions, syntax, or business constraints in a real database environment. Therefore, this embodiment designs an adaptive correction mechanism based on error feedback between the inference agent and the SQL retrieval engine, enabling the system to automatically and iteratively adjust erroneous SQL until successful execution or the iteration limit is reached. The specific process includes: 1) Dry-Run and Error Collection: For the SQL generated by the inference agent, first... Alternatively, the SQL search engine can be run in 'LIMITn' mode; afterwards, capture the error messages returned by the database (such as 'column not found', 'table does not exist', 'syntax error'), as well as any execution plans or runtime alerts.

[0075] 2) Error Analysis and Tool Integration: The inference agent reads error text and uses it as part of the input for the next round of inference; it calls upon tools as needed. , Use tools to check: whether the field is misspelled or belongs to another table; whether the target table exists or belongs to the current domain; whether the functions and operators are supported by the target database; for logical problems such as 'too many result rows' or 'missing necessary dimensions / metrics', make adjustments based on the analysis results of the SQL retrieval engine, such as adding time filtering, adding LIMIT, or supplementing grouping fields.

[0076] 3) ReAct / Reflexion Iterative Correction: The reasoning agent adopts a ReAct / Reflexion-like pattern: First, it thinks and records the assumptions and analysis of the cause of the error; then it acts, modifies the SQL or calls a new tool; in multiple iterations, it accumulates experience and correction trajectory for the same query; each iteration records 'error information → adjustment reason → new SQL' in the state, which is convenient for subsequent playback and optimization.

[0077] 4. Termination and Success Conditions: The iteration process terminates when the SQL is successfully executed and passes the logical verification of the SQL retrieval engine (including field integrity, row count rationality, performance indicators, etc.); or, if multiple iterations fail to generate usable SQL, the current status, error information, and attempted SQL are handed over to upstream suppliers or manual processing.

[0078] Through the aforementioned error-driven adaptive correction mechanism, this embodiment enables the SQL generation process to automatically retry and self-repair, continuously converging to executable SQL that meets visualization requirements in complex and ever-changing database environments.

[0079] Step S14: Based on the SQL execution agent and the target SQL query, perform a database query to determine the database query result.

[0080] In this embodiment, after determining the SQL statement to be executed, i.e. the target SQL query, the execution agent is responsible for executing the target SQL query on the target data warehouse or database and uniformly converting the result into a DataFrame type. Specifically: based on the SQL execution agent, the target SQL query is executed on the target database or target database warehouse to determine the initial query result; based on a preset data format, the initial query result is encapsulated to determine the database query result.

[0081] It's important to understand the SQL query execution and DataFrame output of the executing agent: 1) Execute the intelligent agent to receive parameters: : The SQL text that has been validated; Database connection configuration; optional pagination or rate limiting parameters, such as 'limit', 'offset', etc.

[0082] 2) The agent executes the call to the underlying database driver (such as a connection pool based on PythonDB-API), executes SQL, and obtains the original row set.

[0083] 3) Encapsulate the row set into a DataFrame type (df for short) to ensure that: column names correspond to field names or aliases in SQL; column types are as close as possible to database field types (numeric, time, string, etc.); and row data can be directly used for subsequent statistics, plotting, and exporting.

[0084] 4) Output the data chart (df) and necessary metadata (such as the number of data rows, column types, sampling statistics, etc.) to the chart generation engine and upper-level applications.

[0085] Among them, DataFrame, as a unified data carrier format, has the following advantages: it facilitates re-aggregation, filtering, and deriving indicator calculations in memory; it facilitates integration with chart generation libraries, report engines, and visualization components; and it facilitates the reuse of the same query results in multi-turn dialogues (e.g., reusing the same df from different chart perspectives).

[0086] Step S15: Based on the chart generation engine, analyze and plot the database query results to determine and output the target chart generation result.

[0087] In this embodiment, the ChartGenerationEngine ultimately analyzes, plots, and recommends the database query results, returning visualizations and insights to the user. Specifically, the ChartGenerationEngine analyzes the database query results to determine the analysis results; based on the ChartGenerationEngine, the analysis results, and a preset chart type filtering strategy, plotting is performed to determine and output the target chart generation result.

[0088] It's important to understand that the process of generating reports and visualizations based on DataFrames using a chart generation engine involves the following steps: 1) Analyze the column types and business meanings of the datasheet (df) to identify the measure fields and dimension fields; 2) Select the appropriate chart type (line chart, bar chart, pie chart, funnel chart, etc.) based on user intent and preset strategies. 3) Generate one or more chart configuration objects (such as ECharts or other front-end visualization configurations) and return them along with 'df'; 4) When necessary, attach natural language analysis text to explain the main trends, outliers, and comparative relationships.

[0089] Since the data already exists in the standardized DataFrame format, the chart generation engine can easily perform secondary processing, such as: generating slice reports of different dimensions from the same 'df'; comparing historical 'df' to output month-on-month, year-on-year, and other analyses; and exporting 'df' to formats such as CSV and Excel for users to download.

[0090] Through the above SQL generation, execution, and DataFrame output process, this embodiment achieves a complete closed loop from natural language intent to structured query results and report output, while ensuring high availability, high interpretability, and good scalability.

[0091] In summary, the proposed solution in this embodiment can solve the problems of low accuracy, poor interpretability, and difficulty in expansion of existing natural language to SQL solutions when faced with large-scale schemas, industry terminology mappings, custom logic definitions, and context dependencies. Through multi-agent collaboration and a hierarchical filtering mechanism, it achieves accurate conversion from natural language to high-performance, interpretable SQL. Specific beneficial effects are as follows: 1. High accuracy: Three-layer filtering significantly reduces noise in the LLM context, and combined with a hybrid retrieval mechanism, it significantly improves the accuracy of schema selection.

[0092] 2. Strong robustness: The unified semantic agent effectively solves the problem of understanding industry slang, abbreviations and ambiguous time, and supports cross-domain queries and context completion in multi-turn dialogues.

[0093] 3. Explainability and controllability: The system records the complete intermediate states and confidence levels of domain filtering, table filtering, and semantic clarification, supporting structured auditing; human intervention can be triggered when the confidence level is low (Human-in-the-loop).

[0094] 4. Visually friendly: The generated SQL results are output as a standardized DataFrame, and the structure has been optimized for chart types, directly connecting the last step of data analysis.

[0095] Therefore, in this embodiment, a semantic mapping engine is first used to map industry slang and terminology to the natural language query to be processed, and then perform self-asking. Next, a schema filtering engine and a preset hybrid retrieval mechanism are used to filter the semantically enhanced query by domain, table, and field to determine the target filtering results. Then, an SQL generation engine, a preset validation engine, the semantic mapping results, and the target filtering results are used to perform SQL transformation and adaptive correction to determine the target SQL query. Finally, the target SQL query is executed, and charts are generated from the corresponding database query results. This approach solves the problems existing in related solutions, improves the accuracy and robustness of SQL transformation, and enhances the interpretability of database queries.

[0096] See Figure 2 As shown in the figure, this application also discloses a SQL conversion and query device based on multi-agent cooperation, including: Semantic mapping module 11 is used to perform industry slang and terminology mapping and Self-Ask based on the natural language query to be processed and context information, based on the semantic mapping engine, in order to determine the semantic mapping result; the semantic mapping result includes the semantically enhanced query; Data filtering module 12 is used to perform multi-level filtering on the semantically enhanced query based on the schema filtering engine, the preset hybrid retrieval mechanism and the preset intelligent agent tool to determine the target filtering result; the schema filtering engine includes a domain filtering agent, a table filtering agent and a field filtering agent. SQL conversion module 13 is used to convert and adaptively correct SQL based on SQL generation engine, preset verification engine, large language model, semantic mapping result and target filtering result, so as to determine the target SQL query corresponding to the natural language query. The query result determination module 14 is used to perform a database query based on the SQL execution agent and the target SQL query in order to determine the database query result; The chart generation module 15 is used to analyze and draw the database query results based on the chart generation engine, so as to determine and output the target chart generation result.

[0097] In some specific embodiments, the semantic mapping module 11 may specifically include: Based on the semantic mapping engine, the dialogue history information corresponding to the natural language query is formatted to determine the mapping input information; Based on the mapping input information, the industry slang mapper and terminology mapper in the semantic mapping engine, the mapping of industry slang and terminology is performed to determine the initial mapping result; Based on the semantic agent in the semantic mapping engine, the initial mapping result is processed using Self-Ask to determine the processing result; Based on the processing result and the semantic agent in the semantic mapping engine, determine whether to call the preset mapping tool and the preset knowledge base tool to determine the tool call judgment result; If the tool call judgment result is negative, then based on the semantic agent and the initial mapping result, multiple rounds of reasoning are performed to determine the semantic mapping result; the semantic mapping result includes semantically enhanced query, structured semantic representation, fuzzy terms, the processing result, entity parsing result, and confidence level.

[0098] In some specific embodiments, the data filtering module 12 may specifically include: The candidate set determination unit is used to perform retrieval on the semantically enhanced query based on a preset hybrid retrieval mechanism to determine the domain candidate set, table candidate set, and field candidate set; The domain filtering unit is used to perform domain filtering based on the domain filtering agent, the semantically enhanced query, the entity parsing result, and the domain candidate set to determine the target domain set. The table filtering unit is used to determine a list of table names corresponding to the current domain name based on the table filtering agent, the semantically enhanced query, the entity parsing result, and the table candidate set for any domain name in the target domain set. The field filtering unit is used to perform field filtering on any table name in the table name list, based on the field filtering agent, the semantically enhanced query, the entity parsing result, the field candidate set, the fuzzy terms, and the preset agent tool, to determine the field filtering result corresponding to the current table name; wherein, the preset agent tool includes a table information acquisition tool. The filtering result determination unit is used to determine the target filtering result based on the target domain set, the table name list, and the field filtering result.

[0099] In some specific embodiments, the SQL conversion module 13 may specifically include: The initial query determination unit is used to determine the initial SQL query based on the large language model, the semantic mapping result, the target filtering result, and the planning agent and reasoning agent in the SQL generation engine. The first SQL verification unit is used to perform syntax and logic verification on the initial SQL query based on a preset verification engine in order to determine the current logic verification result. The first trial run unit is used to trigger the trial run corresponding to the initial SQL query based on the preset verification engine if the current logical verification result shows that the verification is successful. The error analysis unit is used to perform error analysis using the reasoning agent, the trial run error information, and the preset agent tool when the trial run error information corresponding to the initial SQL query is captured, so as to determine the error analysis result. The correction unit is used to correct the initial SQL query based on the reasoning agent and the error analysis results, so as to determine the corrected SQL query; The second SQL verification unit is used to perform syntax and logic verification on the corrected SQL query based on a preset verification engine to determine the current logic verification result. The second trial run unit is used to trigger the trial run of the corrected SQL query based on the preset verification engine if the current logical verification result shows that the verification is passed. The target SQL query determination unit is used to determine the modified SQL query as the target SQL query if the trial run of the modified SQL query is successful.

[0100] In some specific embodiments, the initial query determination unit may specifically include: The intent recognition subunit is used to recognize the visual intent based on the structured semantic representation, the natural language query, and the reasoning agent, so as to determine the intent recognition result. The planning subunit is used to plan the query content and query structure based on the planning agent, the large language model, the structured semantic representation, the target filtering results, and the preset agent tools, so as to determine the initial SQL query; the preset agent tools include a domain information acquisition tool, a table information acquisition tool, and a similar SQL acquisition tool.

[0101] In some specific embodiments, the query result determination module 14 may specifically include: The initial query result determination unit is used to execute the target SQL query on the target database or target database warehouse based on the SQL execution agent to determine the initial query result; The encapsulation unit is used to encapsulate the initial query results based on a preset data format in order to determine the database query results.

[0102] In some specific embodiments, the chart generation module 15 may specifically include: The results analysis unit is used to analyze the database query results based on the chart generation engine in order to determine the analysis results; The chart generation unit is used to draw based on the chart generation engine, the analysis results, and the preset chart type filtering strategy, so as to determine and output the target chart generation result.

[0103] Furthermore, embodiments of this application also disclose an electronic device, Figure 3 This is a structural diagram of an electronic device 20 according to an exemplary embodiment. The content of the diagram should not be construed as limiting the scope of this application.

[0104] Figure 3 This is a schematic diagram of the structure of an electronic device 20 provided in an embodiment of this application. Specifically, the electronic device 20 may include: at least one processor 21, at least one memory 22, a power supply 23, a communication interface 24, an input / output interface 25, and a communication bus 26. The memory 22 stores a computer program, which is loaded and executed by the processor 21 to implement the relevant steps in the SQL conversion and query method based on multi-agent cooperation disclosed in any of the foregoing embodiments. Alternatively, the electronic device 20 in this embodiment may specifically be an electronic computer.

[0105] In this embodiment, the power supply 23 is used to provide operating voltage for each hardware device on the electronic device 20; the communication interface 24 can create a data transmission channel between the electronic device 20 and external devices, and the communication protocol it follows can be any communication protocol applicable to the technical solution of this application, and is not specifically limited here; the input / output interface 25 is used to acquire external input data or output data to the outside world, and its specific interface type can be selected according to specific application needs, and is not specifically limited here.

[0106] In addition, the memory 22, as a carrier for resource storage, can be a read-only memory, random access memory, disk or optical disk, etc. The resources stored thereon can include operating system 221, computer program 222, etc., and the storage method can be temporary storage or permanent storage.

[0107] The operating system 221 is used to manage and control the various hardware devices on the electronic device 20 and the computer program 222, which may be Windows Server, Netware, Unix, Linux, etc. In addition to including a computer program capable of performing the SQL conversion and query method based on multi-agent cooperation disclosed in any of the foregoing embodiments, the computer program 222 may further include computer programs capable of performing other specific tasks.

[0108] Furthermore, this application also discloses a computer-readable storage medium for storing a computer program; wherein, when the computer program is executed by a processor, it implements the aforementioned disclosed SQL transformation and query method based on multi-agent cooperation. Specific steps of this method can be found in the corresponding content disclosed in the foregoing embodiments, and will not be repeated here.

[0109] The various embodiments in this specification are described in a progressive manner, with each embodiment focusing on its differences from other embodiments. Similar or identical parts between embodiments can be referred to interchangeably. For the apparatus disclosed in the embodiments, since it corresponds to the method disclosed in the embodiments, the description is relatively simple; relevant parts can be referred to in the method section.

[0110] Those skilled in the art will further recognize that the units and algorithm steps of the various examples described in conjunction with the embodiments disclosed herein can be implemented in electronic hardware, computer software, or a combination of both. To clearly illustrate the interchangeability of hardware and software, the components and steps of the various examples have been generally described in terms of functionality in the foregoing description. Whether these functions are implemented in hardware or software depends on the specific application and design constraints of the technical solution. Those skilled in the art can use different methods to implement the described functions for each specific application, but such implementation should not be considered beyond the scope of this application.

[0111] The steps of the methods or algorithms described in conjunction with the embodiments disclosed herein can be implemented directly by hardware, a software module executed by a processor, or a combination of both. The software module can be located in random access memory (RAM), main memory, read-only memory (ROM), electrically programmable ROM, electrically erasable programmable ROM, registers, hard disk, removable disk, CD-ROM, or any other form of storage medium known in the art.

[0112] Finally, it should be noted that in this document, relational terms such as "first" and "second" are used only to distinguish one entity or operation from another, and do not necessarily require or imply any such actual relationship or order between these entities or operations. Furthermore, the terms "comprising," "including," or any other variations thereof are intended to cover non-exclusive inclusion, such that a process, method, article, or apparatus that comprises a list of elements includes not only those elements but also other elements not expressly listed, or elements inherent to such a process, method, article, or apparatus. Without further limitations, an element defined by the phrase "comprising one..." does not exclude the presence of other identical elements in the process, method, article, or apparatus that includes said element.

[0113] The technical solutions provided in this application have been described in detail above. Specific examples have been used to illustrate the principles and implementation methods of this application. The descriptions of the above embodiments are only for the purpose of helping to understand the methods and core ideas of this application. At the same time, for those skilled in the art, there will be changes in the specific implementation methods and application scope based on the ideas of this application. Therefore, the content of this specification should not be construed as a limitation of this application.

Claims

1. A SQL transformation and query method based on multi-agent collaboration, characterized in that, include: Based on the semantic mapping engine, the natural language query to be processed and the context information are mapped to industry slang and terminology, and Self-Ask is performed to determine the semantic mapping result; The semantic mapping result includes semantically enhanced queries; Based on the schema filtering engine, the preset hybrid retrieval mechanism, and the preset intelligent agent tool, the semantically enhanced query is filtered in multiple layers to determine the target filtering results. The schema filtering engine includes domain filtering agents, table filtering agents, and field filtering agents; Based on the SQL generation engine, the preset verification engine, the large language model, the semantic mapping result, and the target filtering result, the SQL is transformed and adaptively corrected to determine the target SQL query corresponding to the natural language query. Based on the SQL execution agent and the target SQL query, a database query is performed to determine the database query result; Based on the chart generation engine, the database query results are analyzed and plotted to determine and output the target chart generation result.

2. The SQL transformation and query method based on multi-agent collaboration according to claim 1, characterized in that, The semantic mapping engine performs industry slang and terminology mapping and Self-Ask on the natural language query and context information to be processed, in order to determine the semantic mapping result, including: Based on the semantic mapping engine, the dialogue history information corresponding to the natural language query is formatted to determine the mapping input information; Based on the mapping input information, the industry slang mapper and terminology mapper in the semantic mapping engine, the mapping of industry slang and terminology is performed to determine the initial mapping result; Based on the semantic agent in the semantic mapping engine, the initial mapping result is processed using Self-Ask to determine the processing result; Based on the processing result and the semantic agent in the semantic mapping engine, determine whether to call the preset mapping tool and the preset knowledge base tool to determine the tool call judgment result; If the tool call judgment result is negative, then based on the semantic agent and the initial mapping result, multiple rounds of reasoning are performed to determine the semantic mapping result; the semantic mapping result includes semantically enhanced query, structured semantic representation, fuzzy terms, the processing result, entity parsing result, and confidence level.

3. The SQL transformation and query method based on multi-agent collaboration according to claim 2, characterized in that, The schema-based filtering engine, preset hybrid retrieval mechanism, and preset intelligent agent tool perform multi-level filtering on the semantically enhanced query to determine the target filtering results, including: Based on a preset hybrid retrieval mechanism, the semantically enhanced query is retrieved to determine the domain candidate set, table candidate set, and field candidate set. Based on the domain filtering agent, the semantically enhanced query, the entity parsing result, and the domain candidate set, domain filtering is performed to determine the target domain set. For any domain name in the target domain set, a list of table names corresponding to the current domain name is determined based on the table filtering agent, the semantically enhanced query, the entity parsing result, and the table candidate set; For any table name in the list of table names, field filtering is performed based on the field filtering agent, the semantically enhanced query, the entity parsing result, the field candidate set, the fuzzy terms, and the preset agent tool to determine the field filtering result corresponding to the current table name; The preset intelligent agent tools include table information acquisition tools; Based on the target domain set, the table name list, and the field filtering results, the target filtering results are determined.

4. The SQL transformation and query method based on multi-agent cooperation according to claim 3, characterized in that, The process of converting and adaptively correcting SQL based on the SQL generation engine, the preset validation engine, the large language model, the semantic mapping results, and the target filtering results includes: Based on the large language model, the semantic mapping results, the target filtering results, and the planning and reasoning agents in the SQL generation engine, the initial SQL query is determined; Based on a preset verification engine, the initial SQL query is subjected to syntax and logic verification to determine the current logic verification result. If the current logical verification result indicates that the verification is successful, then the trial run corresponding to the initial SQL query is triggered based on the preset verification engine; When the trial run error information corresponding to the initial SQL query is captured, the inference agent, the trial run error information and the preset agent tool are used to perform error analysis to determine the error analysis result. Based on the reasoning agent and the error analysis results, the initial SQL query is corrected to determine the corrected SQL query; Based on a preset validation engine, the modified SQL query is subjected to syntax and logic validation to determine the current logic validation result. If the current logical verification result indicates that the verification is successful, then the trial run of the corrected SQL query is triggered based on the preset verification engine. If the modified SQL query is successfully tested, then the modified SQL query will be identified as the target SQL query.

5. The SQL transformation and query method based on multi-agent collaboration according to claim 4, characterized in that, The process of determining the initial SQL query based on the large language model, the semantic mapping result, the target selection result, and the planning and reasoning agents in the SQL generation engine includes: Based on the structured semantic representation, the natural language query, and the reasoning agent, the visual intent is identified to determine the intent identification result; Based on the planning agent, the large language model, the structured semantic representation, the target filtering results, and the preset agent tools, the query content and query structure are planned to determine the initial SQL query; the preset agent tools include a domain information acquisition tool, a table information acquisition tool, and a similar SQL acquisition tool.

6. The SQL transformation and query method based on multi-agent collaboration according to claim 1, characterized in that, The process of performing a database query based on the SQL execution agent and the target SQL query to determine the database query results includes: Based on an SQL execution agent, the target SQL query is executed on the target database or target database repository to determine the initial query results; The initial query results are encapsulated based on a preset data format to determine the database query results.

7. The SQL transformation and query method based on multi-agent cooperation according to any one of claims 1 to 6, characterized in that, The process of analyzing and plotting the database query results based on the chart generation engine to determine and output the target chart generation result includes: The database query results are analyzed based on the chart generation engine to determine the analysis results; Based on the chart generation engine, the analysis results, and the preset chart type filtering strategy, a chart is generated to determine and output the target chart generation result.

8. A SQL conversion and query device based on multi-agent collaboration, characterized in that, include: The semantic mapping module is used to perform industry slang and terminology mapping and Self-Ask on the natural language query and context information to be processed, based on the semantic mapping engine, in order to determine the semantic mapping result; The semantic mapping result includes semantically enhanced queries; The data filtering module is used to perform multi-level filtering on the semantically enhanced query based on the schema filtering engine, the preset hybrid retrieval mechanism and the preset intelligent agent tool, so as to determine the target filtering results. The schema filtering engine includes domain filtering agents, table filtering agents, and field filtering agents; The SQL conversion module is used to convert and adaptively correct SQL based on the SQL generation engine, the preset validation engine, the large language model, the semantic mapping result, and the target filtering result, so as to determine the target SQL query corresponding to the natural language query. The query result determination module is used to perform a database query based on the SQL execution agent and the target SQL query in order to determine the database query result; The chart generation module is used to analyze and plot the database query results based on the chart generation engine, so as to determine and output the target chart generation result.

9. An electronic device, characterized in that, include: Memory, used to store computer programs; A processor for executing the computer program to implement the SQL transformation and query method based on multi-agent cooperation as described in any one of claims 1 to 7.

10. A computer-readable storage medium, characterized in that, Used to store computer programs, which, when executed by a processor, implement the SQL transformation and query method based on multi-agent cooperation as described in any one of claims 1 to 7.