Database interaction method and device based on multi-agent cooperation, equipment and medium
By employing a multi-agent collaborative architecture and a multi-verification mechanism, the shortcomings of existing database interaction technologies in multimodal data processing and task planning are addressed, enabling efficient and accurate database interaction and data interpretation, thereby improving the system's intelligence level and user experience.
Patent Information
- Application Number
- CN202511317091.6
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2025-09-16
- Publication Date
- 2026-01-23
- Estimated Expiration
- 2045-09-16
AI Technical Summary
Existing database interaction technologies have limited preprocessing capabilities when dealing with multimodal inputs, making it difficult to fully capture the deep semantic features of the data, resulting in information loss or omission, low query efficiency and feedback accuracy, lack of flexibility in task planning, inability to effectively integrate user needs and multi-source retrieval results, and poor accuracy and execution success rate of generated query commands.
A multi-agent collaborative architecture is adopted, which performs semantic segmentation and vectorization through a format adapter. Combined with intelligent search and knowledge base retrieval, the task planning agent decomposes complex tasks into atomic subtasks, and uses a dual-agent collaboration and three-level matching mechanism for database interaction. Multiple verification mechanisms are introduced to ensure the accuracy of query statements and the success rate of execution.
It improves the parallel response capability of multimodal data processing, enhances the accuracy of semantic similarity retrieval and the comprehensiveness of information recall, ensures the robustness and efficient execution of the system in complex scenarios, and provides an intuitive, accurate and efficient data interpretation experience.
Smart Images

Figure CN120821738B_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of database interaction technology, and more specifically, to a database interaction method, apparatus, device, and medium based on multi-agent collaboration. Background Technology
[0002] There is a significant demand for efficient and intelligent database interaction systems in the fields of computer science and artificial intelligence. In real-world applications, users often need to process multimodal data inputs, including text, structured data, and multimedia files, to support complex queries and decision analysis.
[0003] For example, in scenarios such as intelligent customer service and data analysis platforms, systems must respond quickly to diverse query requests while ensuring the integrity and semantic depth of information. These requirements necessitate that database interaction technologies possess efficient data preprocessing capabilities, accurate semantic parsing mechanisms, and dynamic task scheduling strategies to address the growing challenges of processing multi-source heterogeneous data.
[0004] Existing database interaction technologies have significant shortcomings in several key aspects. When handling multimodal input, the system's limited preprocessing capabilities often lead to information loss or omission, making it difficult to fully capture the deep semantic features of the data, thus affecting the accuracy of subsequent vectorization and similarity retrieval. In information retrieval, existing methods rely excessively on simple keyword matching, failing to effectively utilize high-quality embedding transformation and semantic segmentation techniques. This results in search results that do not accurately respond to users' actual needs, severely limiting query efficiency and feedback accuracy. Furthermore, task planning lacks flexibility, failing to effectively integrate user needs, historical interaction records, and multi-source search results. Complex query tasks are difficult to break down into independently executable subtasks, and the tool invocation process appears unintelligent and unadaptive, significantly reducing overall execution efficiency and task completion rate.
[0005] These shortcomings are further evident in the database interaction process. Existing technologies suffer from insufficient matching of tables, columns, and specific constraints in the process from input data parsing to SQL query generation. Furthermore, they lack multi-layered validation mechanisms covering syntax, semantics, and results, resulting in poor accuracy and execution success rates in the final generated query commands. These issues not only limit the system's robustness in diverse data scenarios but also hinder the improvement of user experience and data insight capabilities, impeding the development of intelligent database management technologies. Summary of the Invention
[0006] The present invention provides a database interaction method, apparatus, device and medium based on multi-agent collaboration to improve at least one of the above-mentioned technical problems.
[0007] In a first aspect, the present invention provides a database interaction method based on multi-agent collaboration, which includes steps S1 to S5.
[0008] S1. Obtain the query request, then perform semantic segmentation through a format adapter, and then vectorize it into a vector representation to obtain the retrieval vector set.
[0009] S2. Based on the retrieval vector set, the search source is selected by the search source selection agent, and a meta-search engine is used to search and obtain information blocks. Candidate knowledge is also obtained through knowledge base retrieval. Then, the information blocks and candidate knowledge are integrated to obtain a candidate information set.
[0010] S3. The task planning agent constructs a dynamic demand understanding model based on the query request and the candidate information set to generate atomically executable subtasks and obtain the task state matrix and tool invocation task.
[0011] S4. Invoke the corresponding auxiliary tool according to the tool invocation task and perform the operation. Update the task status matrix according to the operation result and return the updated task status matrix to the task planning agent to update the tool invocation task until the task planning agent no longer outputs the tool invocation task and obtains the task result.
[0012] S5. When the task planning agent calls the database interaction module, it generates a chart based on the output of the database interaction module and outputs it along with the task result. Otherwise, it directly outputs the task result.
[0013] Secondly, the present invention provides a database interaction device based on multi-agent collaboration, which includes a query acquisition module, a search source module, a task planning module, a task execution module, and an output module.
[0014] The query retrieval module is used to obtain query requests, then perform semantic segmentation through a format adapter, and finally vectorize them into vector representations to obtain a set of retrieval vectors.
[0015] The search source module is used to select a search source based on the retrieval vector set, use a meta-search engine to search, obtain information blocks, and retrieve candidate knowledge through a knowledge base. Then, the information blocks and candidate knowledge are integrated to obtain a candidate information set.
[0016] The task planning module is used to construct a dynamic demand understanding model based on the query request and the candidate information set through a task planning agent, so as to generate subtasks that can be executed atomically, and obtain the task state matrix and tool invocation task.
[0017] The task execution module is used to invoke the corresponding auxiliary tools and perform operations according to the tool invocation task, update the task status matrix according to the operation results, and return the updated task status matrix to the task planning agent to update the tool invocation task, until the task planning agent no longer outputs the tool invocation task and obtains the task result.
[0018] The output module is used to generate a chart based on the output of the database interaction module when the task planning agent calls the database interaction module, and output the chart along with the task result. Otherwise, the task result is output directly.
[0019] Thirdly, the present invention provides a database interaction device based on multi-agent cooperation, comprising a processor, a memory, and a computer program stored in the memory. The computer program can be executed by the processor to implement a database interaction method based on multi-agent cooperation as described in any paragraph of the first aspect.
[0020] Fourthly, the present invention provides a computer-readable storage medium comprising a stored computer program, wherein, when the computer program is executed, it controls the device where the computer-readable storage medium is located to perform a database interaction method based on multi-agent cooperation as described in any paragraph of the first aspect.
[0021] By adopting the above technical solution, the present invention can achieve the following technical effects:
[0022] Compared to existing technologies, this invention has made in-depth optimizations in key aspects such as multimodal data processing, intelligent retrieval, and task planning, and introduced a series of innovative mechanisms to improve the system's intelligence level, retrieval accuracy, and interactive experience, specifically including the following aspects:
[0023] 1. By adopting multimodal data preprocessing and format adapter parsing technology, real-time query and knowledge base construction are separated, which improves the system's parallel response capability and reduces the complexity of processing multiple data formats.
[0024] 2. By integrating multimodal embedding transformation and semantic segmentation processing, deep semantic features of diverse information such as text and images are captured to achieve higher-precision semantic similarity retrieval and obtain higher matching accuracy.
[0025] 3. The intelligent search and knowledge base retrieval processes are integrated in parallel. Through automatic keyword generation, cosine similarity matching, and re-ranking mechanisms, information blocks that are highly relevant to the user's query can be extracted more quickly in a wide range of searches, improving the comprehensiveness and accuracy of information retrieval.
[0026] 4. Utilize a task planning agent to integrate user queries, historical interactions, preset preferences, and search results from multiple dimensions, and decompose complex tasks into atomic subtasks. By implementing refined task scheduling and dynamic tool invocation, the robustness and efficient execution of the system in complex scenarios can be guaranteed.
[0027] 5. In the database interaction process, a dual-agent collaboration and three-level matching mechanism is adopted to perform precise matching from tables and columns to specific value types, and supplemented by a closed-loop error correction mechanism with triple verification (syntax, semantics, and result level) to ensure that the generated SQL query statements not only conform to the ANSI standard but also have a high execution success rate.
[0028] 6. In the visualization stage, by combining intelligent decision trees with a hierarchical summary architecture, we match users' explicit needs, implicit preferences, and data characteristics to achieve automated visualization selection and semantic alignment, thereby providing an intuitive, accurate, and efficient data interpretation experience. Attached Figure Description
[0029] Figure 1 This is an architecture diagram of the database interaction method.
[0030] Figure 2 This is a framework diagram of database interaction methods.
[0031] Figure 3 This is a flowchart of the database interaction method.
[0032] Figure 4 This is a visual example of the query results returned by the database interaction module. Detailed Implementation
[0033] Example 1, please refer to Figures 1 to 4 This invention provides a database interaction method based on multi-agent cooperation, which can be executed by a database interaction device based on multi-agent cooperation (hereinafter referred to as: database interaction device). Specifically, it is executed by one or more processors in the database interaction device to implement steps S0 to S5.
[0034] S0. Pre-built Database and Knowledge Base: Based on user-uploaded structured data, extract natural language structure information at the table, column, and value levels, vectorize it, and then store it in a vector database. Based on user-uploaded heterogeneous files, convert them into a unified processing format, perform data block processing and vectorization encoding, and obtain a searchable content mapping relation library. Heterogeneous files are unstructured or semi-structured data.
[0035] It should be noted that the knowledge base and database can directly use existing databases without needing to be built independently. Therefore, the construction of the knowledge base and database is not a necessary technical feature of this invention. In this embodiment, the database is built based on structured data. The knowledge base is built based on unstructured or semi-structured data.
[0036] Preferably, step S0 includes steps S01 to S06.
[0037] S01. During the database pre-construction process, the system first obtains the user-uploaded database file or database configuration information, as well as the database structure information file, and extracts and generates natural language structure information at the table, column, and value levels. After extracting the natural language structure information, it performs vectorization representation (embedding) and finally stores it in a vector database for semantic retrieval. The database file can be SQLite or a user-configured MySQL or PostgreSQL database. The logic for generating table, column, and value-level structure information is described below.
[0038] The table-level description for each table is defined as follows: .
[0039] In the formula: Indicates table-level description, For table name, express Description of uses Primary key field Description Indicates the first Description of each field (field name, type, meaning) The number of fields.
[0040] The column-level description for any column in the table is defined as: .
[0041] In the formula: Indicates column-level description, For field names, For table name, )for Data types Mark the key type (primary key or foreign key, omit if none). This describes the meaning of the field.
[0042] For a specific value, its natural language description is: .
[0043] In the formula: For value level description, For the specific field values, For field names, For table name, A description of the foreign key field relationships (if any). This describes the meaning of the field.
[0044] S02. Perform vectorization (embedding) on the generated structural information.
[0045] The natural language description text generated above Mapped to a high-dimensional vector .
[0046] .
[0047] Among them, the function Typically, OpenAI's embedding model (such as text-embedding-ada-002) is used, which generally produces 768 or 1536-dimensional vectors. For example: , , In the formula, for vectors, for vectors, for The vector.
[0048] S03. Store the vectorization (embedding) results in the vector database.
[0049] Each vector database record is as follows:
[0050] In the formula: Records in the database A unique identifier for a vector Describing text in raw natural language For the generated high-dimensional vector, For record types (table, column, or value), For the table name, This is for the column name (only required for column level and value level). This represents the actual value (value level only).
[0051] When users or subsequent tools need to perform searches using natural language, cosine similarity can be calculated to search the vector space. This finds the most similar natural language description records and quickly locates the corresponding table, column, or specific value in the database.
[0052] S04. During the knowledge base construction process, the heterogeneous files uploaded by users are first parsed through a format adapter to convert data of different formats into a unified processing format.
[0053] Specifically, the unified processing of heterogeneous files is achieved by relying on existing format parsing and adaptation technologies. The existing technologies used include multi-format file parsing libraries (such as Apache Tika for parsing text files such as PDF and DOCX, Pillow for processing image formats, and PyPDF2 for extracting text from PDFs), data format conversion frameworks (such as Pandas for processing semi-structured data such as CSV / Excel), and multimedia parsing tools (such as FFmpeg for extracting audio metadata).
[0054] S05. The parsed data is chunked to ensure appropriate granularity during knowledge base retrieval. In practice, the system typically uses simple paragraph-based chunking rules, such as using two newline characters (\n\n) as delimiters to divide the text into several semantic blocks.
[0055] S06. Vectorize and encode these knowledge blocks to obtain a searchable content mapping relationship library. Specifically, each block... Through vectorized encoding functions Convert to high-dimensional vector This ultimately forms a searchable content mapping database. Indicates the first Each block, express The vector.
[0056] S1. Query request preprocessing: Obtain the query request, then perform semantic segmentation through a format adapter, and then vectorize it into a vector representation to obtain the retrieval vector set.
[0057] Query requests can include content in various formats besides text, such as text, structured data, and multimedia files. In this embodiment, semantic segmentation using a format adapter is the same as in S04 to S05 of S0. Specifically, when performing semantic segmentation using a format adapter: no additional preprocessing is performed for text-type information. For structured data, additional parsing is required to extract key fields and convert it to a uniform format for alignment with other data types. Audio data is directly converted to text to simplify subsequent processing and ensure consistency with other text data. Image data is stored in its original format to ensure it can be matched and associated with other information during subsequent retrieval.
[0058] After semantic segmentation using a format adapter, a search term extraction agent is invoked to extract search keywords from the semantic segments. Then, the search keywords are vectorized to obtain a set of search vectors. The search term extraction agent is obtained by fine-tuning an existing large language model with prompt words (e.g., "You will act as a professional information retrieval assistant, responsible for extracting the most effective query phrases from given text content to find related information in knowledge base systems and search engines"). The search keywords are converted into high-dimensional vector representations using vectorization techniques for subsequent similarity matching of search information blocks.
[0059] For example, a user submits the following text: "I want to travel during the May Day holiday. Please recommend a city that is most suitable for a short trip, taking into account the weather conditions for the past week, the cost of living in the city, and the cultural atmosphere. Finally, output the conclusion in Chinese with a brief English summary." The search term extraction agent extracts key information into phrases and generates a list of search terms. The extracted search terms are as follows: ["Weather conditions for the past week", "City cost of living", "City cultural atmosphere", "Cities suitable for short trips"]. After extracting the corresponding phrase information, the system vectorizes each search term for similarity matching of subsequent search information blocks.
[0060] S2. Information Retrieval: Based on the retrieval vector set, the agent selects a search source and uses a meta-search engine to search and obtain information blocks. Candidate knowledge is retrieved through a knowledge base. Then, the information blocks and candidate knowledge are integrated to obtain a candidate information set.
[0061] The core objective of the system is to extract the most relevant information blocks to the user query to support subsequent intelligent task planning and reasoning generation. Preferably, the information retrieval in this embodiment employs a dual retrieval strategy, including an intelligent search process and a knowledge base retrieval process. On one hand, the intelligent search process automatically parses the user query and generates search keywords, initially filtering candidate information blocks through a meta-search engine. On the other hand, knowledge base retrieval technology is used to perform cosine similarity matching between the preprocessed user query embedding and pre-vectorized document data in the knowledge base. After matching, the system reorders the retrieved information blocks, filtering out the Top K candidate sets with the highest semantic relevance. Finally, the results of these two retrieval strategies are integrated into a unified candidate information set and passed to the task planning agent as background knowledge support. Specifically, step S2 includes steps S21 to S27.
[0062] S21. Based on the retrieval vector, the search source is selected by the search source selection agent. Specifically, the system passes the retrieval vector to the search source selection agent, which selects a suitable search source based on its semantic information. The search source selection agent is obtained by fine-tuning an existing large language model with prompt words (e.g., "You are a task classifier. Your task is to analyze user queries and determine whether a search operation is needed, and if so, select the appropriate search type").
[0063] S22. Based on the retrieval vector and the selected search source, use the meta-search engine to search and obtain information blocks relevant to the user's needs. This step is the initial screening.
[0064] S23. Vectorize the search results, converting text information into vector representations. Specifically, vectorize information blocks related to user needs.
[0065] S24. The semantic similarity algorithm is used to compare the vector representation of the search results with the retrieval vector, and the Top-K information blocks with the highest semantic relevance are selected, thereby ensuring that the returned content is highly consistent with the user's query at the semantic level. The semantic similarity algorithm used is an existing algorithm such as cosine similarity.
[0066] Specifically, before the formal search, each search phrase is fed into a "search source selection agent" with contextual understanding capabilities. The agent's goal is to determine whether the query requires a search operation and further determine which search type should be used. The system offers four search types: Academic Research, Social Community, Natural Sciences, and General Internet. Taking "City Living Costs" as an example, the classifier model outputs the General Internet category. Regardless of the search type, the returned results have the same format: {title, content, link, source}. The system uses the search source and search terms as input parameters and calls the corresponding search engine, returning the following example result: JSON text [{title: 2025 Ranking of Living Costs in Major Chinese Cities. Content: According to the latest data from 2025, the cost of living in Beijing, Shanghai, and Shenzhen remains the highest, while cities like City A and Xi'an are favored for their lower costs and better living conditions. Link: https: / / website. Source: Example data source.}].
[0067] As shown above, the search results typically include a content summary, title, link, source, and publication date. The system converts these structured results into JSON text and performs embedded vectorization. These vectors are then compared with the semantic vectors of the original search terms to extract the Top-K most relevant results as the output information blocks for intelligent search. Cosine similarity is typically used for similarity calculation.
[0068] S26. Perform similarity matching between the retrieved vector set and the pre-built knowledge base to identify the most similar document fragments and obtain candidate knowledge. The knowledge base contains pre-divided and stored document data.
[0069] Specifically, the entire knowledge base content is first processed by vector embedding, then phrase vectors are extracted and compared one by one with the vectors. The system will use a semantic matching mechanism to find the document paragraphs or knowledge nodes most similar to the phrase, and select the candidate knowledge with the highest similarity score as the knowledge base retrieval output.
[0070] Example output using "cities suitable for short trips" as the search phrase: JSON text [{Title: Top 5 domestic destinations suitable for short trips. Content: For short trips of three to five days, cities F, C, B, A, and D are widely recommended. These cities not only have convenient transportation but also offer a balanced experience in terms of culture and consumption, making them suitable for a relaxing holiday. Source: "2024 City Cultural Tourism White Paper". Document number: .... Chapter identifier: ...}]. This information block comes from a document in the knowledge base. The system determines that it is highly relevant to "cities suitable for short trips" through semantic matching and returns it as a search result from the knowledge base.
[0071] Ultimately, the candidate knowledge, along with the information blocks, will serve as the semantic context supporting input for the city recommendation generation task. Each retrieval vector involves one intelligent search and one knowledge base matching, thus requiring multiple information extraction steps throughout the process.
[0072] S27. Incorporate information blocks and candidate knowledge into a unified candidate information set.
[0073] The candidate information set serves as background knowledge, passed to the subsequent task planning agent to assist the model in providing more accurate, detailed, and reliable supporting information during reasoning and generation. By integrating intelligent search and knowledge base retrieval strategies in parallel, the system can mine and extract potential key information from a wider range, thereby improving the overall accuracy and efficiency of the system. This process ensures that the system can not only retrieve content matching keywords but also accurately understand user needs at the semantic level, thus improving the accuracy and reliability of overall intelligent decision-making.
[0074] S3. Task Planning: The task planning agent constructs a dynamic demand understanding model based on the query request and the candidate information set to generate atomically executable subtasks and obtain the task state matrix and tool invocation tasks.
[0075] The task planning agent is derived by fine-tuning an existing large language model using prompt words. (Prompt words, for example: Role setting: "You are a task planning agent. Your core responsibility is to break down complex user query tasks into a series of executable subtasks that satisfy atomicity constraints (i.e., satisfy the single tool call principle and the single call principle). Combine user input, knowledge blocks, and task status to dynamically optimize and adjust the task sequence. Based on the update of the real-time task status matrix (S), re-participate in task scheduling when necessary to ensure effective task progress and maximize task utility.")
[0076] During the task planning phase, the task planning agent, as the core scheduling module of the system, achieves requirement analysis through multi-dimensional information fusion. This agent first integrates query requests, candidate information sets, user preset preferences (such as data filtering conditions), historical interaction records (such as common query patterns), and personalized requirements (such as specific field priorities) to construct a dynamic requirement understanding model.
[0077] Based on this model, the agent performs in-depth analysis of complex tasks and breaks them down into a series of atomically executable subtasks. This decomposition logic strictly adheres to the principle that "a single tool can complete the task in a single call." For example, when it is necessary to simultaneously retrieve data from a database and call a weather API, the system will generate two independent subtasks to ensure the independence and non-interference of each function.
[0078] During the task execution phase, the system dynamically invokes a pre-defined list of tools (including database query tools, code interpretation interfaces, weather interfaces, and other auxiliary tools). After each tool invocation, the system updates the task status matrix in real time, recording the completion status of each subtask, the returned results, and any potential exception codes. If incomplete results or tool errors occur, the agent automatically initiates a loop iteration mechanism. By reassessing remaining requirements, adjusting the tool invocation order, or adding supplementary conditions, the system continues to advance the task until a pre-defined completion threshold is met, or triggers an error termination after reaching the maximum number of iterations. This mechanism aims to improve task completion and result accuracy while ensuring the system's robustness and efficiency in complex scenarios.
[0079] The Task Planning Agent (TPA) aims to break down complex user query tasks into a series of executable atomic subtasks and dynamically adjust task execution strategies using multi-source heterogeneous information to ensure successful task completion.
[0080] The entire process can be expressed by the following formula: In the formula, For task sequences, Planning agents for tasks To help users retrieve information, For the candidate information set, Preset user preferences For dialogue history information, To meet users' personalized needs, For the task state matrix, Indicates the first Sub-tasks.
[0081] During the task decomposition phase, the task planning agent needs to break down complex query tasks into several atomic subtasks: In the formula, Indicates the first Sub-tasks For the first The names of the tools that each subtask needs to call. For the first The parameters for calling the tool for each subtask. Specifically, each subtask... The following constraints must be met: Single instrument principle: Single-call principle: In the formula, For tool name, For atomicity, The value indicates that the value is true.
[0082] Based on the task sequence, generate a task state matrix. Task State Matrix Used for real-time tracking and feedback of the execution status of each subtask: In the formula, For tool name, To call tool parameters, For execution status, Returning results for the tool and This is the start and end timestamp for the subtask execution.
[0083] The task status matrix will be updated in real time: In the formula, For the updated task state matrix, Indicates update, For time steps Task state matrix at time, For the tasks currently being performed, For the current calling tool parameter information, This refers to the feedback content returned by the tool. It includes error messages, supplementary requests, additional data, etc.
[0084] When a subtask fails or produces incomplete results, the system will trigger a loop iteration mechanism to re-call the task. Make task corrections: In the formula, It indicates the first The task state matrix at the next iteration.
[0085] The loop continues until either of the following conditions is met: 1. The completion threshold is reached: 2. The system determines that the task cannot be completed and triggers an error termination: 3. Complete the task. In the formula, This indicates that the system assesses the overall task completion based on result completeness, consistency, and tool call quality, with a value range of [0,1]. This indicates the preset completion threshold (e.g., 0.95). This indicates a termination condition function, such as user interruption, exceeding the limit of consecutive failures, or resource exhaustion.
[0086] During the task planning phase, the task planning agent receives input from the preceding steps, combines it with several other pieces of information, performs task planning, and returns a list of corresponding tool calls. The task planning agent primarily accepts the following input information: user query information, candidate information set, user preset preferences, dialogue history information, user personalized needs, and a real-time task status matrix.
[0087] Here's a specific example with the following input information for the task planning agent: 1. User query: "I want to travel during the May Day holiday. Please recommend a city most suitable for a short trip, considering the weather conditions for the past week, the cost of living in the city, and the cultural atmosphere. Output the conclusion in Chinese with a brief English summary." 2. Retrieved knowledge blocks: Candidate information set. 3. User preset preferences: ["Answer in Chinese"]. 4. Dialogue history information: [Specific historical information]. 5. User personalized needs: ["Prefers a pleasant climate and sunny weather for travel", "Prefers coastal cities or cities with natural scenery"]. 6. Real-time task state matrix: Empty (empty for the first input; in subsequent iterations, the result of the previous iteration is used as input).
[0088] After receiving the user input, the task planning agent performs a long period of thought and outputs a task state matrix.
[0089] Table 1 Task Status Matrix (Example)
[0090]
[0091] S4. Task Execution: Based on the tool call task, call the corresponding auxiliary tool and perform the operation. Update the task state matrix based on the operation result, and return the updated task state matrix to the task planning agent to update the tool call task, until the task planning agent no longer outputs the tool call task, and obtain the task result.
[0092] During task planning and execution, the system includes auxiliary tools such as a database interaction module, a calculator, a code interpreter, a weather interface, and a translation interface.
[0093] When the Task Planning Agent (TPA) invokes an auxiliary tool, the tool receives tool call parameters from the TPA. ), and execute the corresponding tool calls, feed back the execution results to TPA, and update the task status matrix at the same time ( The specific formulaic expression for this step is as follows:
[0094] .
[0095] In the formula: The execution result returned by the tool For tool actuators, ∈{calculator, code interpreter, weather interface, translation interface} represents the type of tool being invoked. These are the specific parameters for the tool call.
[0096] The database interaction module employs a multi-agent collaborative architecture to achieve high-precision query construction and end-to-end supervision. After the task planning agent issues sub-tasks, the system first uses a semantic parsing engine to deeply analyze the input content, automatically extracting key entities (e.g., table name "order"), attributes (e.g., column name "amount"), and constraints (e.g., numerical range ">1000"). Then, combined with a pre-built database, it performs a three-level matching: first, it accurately determines the target data source through relational table mapping; second, it locates specific fields using column association information; and finally, it ensures the validity of each constraint through value type validation. Successfully matched elements are encoded into a structured context, which then drives the SQL generation agent to construct ANSI-compliant query statements using a thought chain reasoning mechanism and a few-shot library. Furthermore, the task correction agent employs a triple-validation mechanism to rigorously supervise and correct the entire process: at the syntactic level, the system verifies the legality of the SQL structure using an Abstract Syntax Tree (AST); at the semantic level, it uses execution plan pre-playing to detect potential logical contradictions (such as missing fields or data mismatches); and at the result level, it sets threshold alarms for empty result sets or results exceeding limits. When an anomaly is detected, the correction intelligence dynamically injects specific prompts (such as supplementing missing JOIN conditions or correcting GROUP BY grouping logic) and automatically reverts to the schema extraction or SQL generation stage for re-execution, thus forming a closed-loop error correction mechanism. The semantic parsing engine is an existing Large Language Model (LLM).
[0097] When the task planning agent invokes the database interaction module, during the information extraction and schema association phase, the module first receives the tool call parameters from the task planning agent (which is actually the natural language description of the database query processed by the task planning agent). Then, it uses a Large Language Model (LLM) to perform preliminary analysis and extraction of the input information, mainly extracting keywords from the query information.
[0098] Record the user query information as The information extraction model is The extracted information is The information extraction stage model is as follows: .
[0099] Before performing database structure information matching, some preprocessing is required for the current database. Let the original database structure information be: . .in: For the original database schema, For the first individual tables for The Middle individual columns, for The Values.
[0100] The specific operations for preprocessing database structure information include: vectorized computational representations of table names, column names, and typical values to facilitate semantic matching. Let the vectorization operation be a function. Then: the vectorized representation of the table is: The vectorized representation of a column is: The vectorized representation of the value is: In the formula, Represents a vector.
[0101] In the structural information association extraction stage, semantic matching is performed between the vector of user questions and the vector of structural information to obtain the degree of association between tables, columns, and values:
[0102] In step S1, the vector representation of the query request has been obtained through vectorization: The formula for scoring the association between query requests and the tables is as follows: The degree of correlation between the question and the column: The degree of correlation between the problem and the specific value: In the formula, For related ratings, Let be the cosine similarity.
[0103] Then, models with a correlation degree exceeding a threshold are used as the correlation structure information. Table selection: Column selection: Value selection: In the formula, For related tables, For related columns, For associated values, For the threshold of the degree of association of the table, Threshold for the degree of association of columns, The threshold for the degree of correlation of the values.
[0104] After the above preprocessing of structural information and derivation of correlation formulas, the extracted set of structural information is as follows: In the formula, For structural information set, For the specific field values, For field names, This is the table name.
[0105] During the SQL statement generation phase, after matching information and structural information, this information is passed to a large language model. Using the Chain of Thought (CoT) and few-shot methods, a structured SQL statement is generated. Let the generated SQL be... The corresponding model is ,but: When generating SQL, LLM combines few-shot learning examples to mimic prior examples, thereby obtaining more accurate and compliant SQL expressions.
[0106] During the task correction and feedback iteration phase: After the SQL is generated, it is executed and the corresponding execution results are produced. ( The corrective agent will examine the execution results and compare them with the semantics of the original problem to determine the correctness or deviation of the SQL statement. (The specific result set or error message returned by the database after execution) .in, The task correction agent, based on the comparison between the execution result and the original semantics, identifies the consistency or discrepancy between the current execution result and the user's intent. Revise corresponds to the task correction agent.
[0107] If a problem is detected, the task correction intelligence will... Passed to , The SQL will be corrected based on this context, and new SQL statements will be generated:
[0108] .
[0109] The above process will be executed iteratively until the result of the SQL statement execution satisfies the semantic requirements of the problem, or the upper limit of the number of iterations is reached:
[0110] .
[0111] in, Indicates the final output, Indicates the current iteration number, This indicates the maximum allowed number of iterations.
[0112] When the number of iterations reaches the upper limit or the execution result is correct, the task correction agent will provide the execution result and a summary to the task planning agent and update the corresponding task state matrix.
[0113] A calculator is used to perform calculations on input data.
[0114] A code interpreter is used to execute the input code and return the execution result and status.
[0115] The Weather API is used to obtain weather data based on input parameters.
[0116] The Translation API is used to translate input text.
[0117] The task status matrix is updated after each tool is invoked. For example, here's an example of the update after invoking the calculator: .
[0118] For example: based on the tool call task of the first task planning, the task first calls the weather interface to process the task, obtains a return result, updates the task state matrix based on the result, and then returns the updated task state matrix to the task planning agent.
[0119] The task planning agent re-executes step S3, undergoes a long period of reflection after receiving the updated input, and outputs a new tool invocation task. For example: JSON text [{Tool: Database interaction module. Tool parameters: {Query: Query comparative data on the cost of living in six cities: City A, City B, City C, City D, City E, and City F}}].
[0120] Then, step S4 is executed again, and the database interaction module is invoked. In this stage, the database interaction module accepts the tool parameters passed from the previous step, passes these parameters to the information extraction agent, and receives a corresponding return result: ["City A", "City B", "City C", "City D", "City E", "City F", "City", "Cost of Living", "Comparison Data"]. Next, each keyword is vectorized to obtain a vector representation with the same dimensions as the embedded database structure. These keyword vectors are then compared with the table-level, column-level, and value-level natural language description vectors already stored in the vector database using cosine similarity calculations to identify the most relevant database entities. Based on the above information, the complete structure information of the associated database table / column / value is obtained below. Using the preceding structure information and the tool parameter: "Query the cost of living comparison data for six cities: City A, City B, City C, City D, City E, and City F," as input, the SQL generation agent is invoked. The SQL statement is obtained. The semantic parsing engine, SQL generation agent, and task correction agent are all obtained by fine-tuning the existing large language model using prompt words. Semantic parsing engine prompts, for example: Extract all keywords related to database structure matching from the following sentence. SQL generation agent prompts, for example: You are an efficient, accurate, and professional SQL generation assistant. Your task is to infer and generate accurate, standardized, and executable SQL query statements based on the user's natural language query and the database's schema. Task correction agent prompts, for example: As the full-process supervisor, please use a triple verification mechanism (Abstract Syntax Tree (AST) verification, semantic pre-analysis detection, and result threshold alarm) to perform closed-loop error correction on the SQL generation process. When an anomaly is detected, automatically inject prompts and revert to the association pattern extraction or SQL generation stage. Finally, update the task state matrix based on the output of the database interaction module, and then return the updated task state matrix to the task planning agent.
[0121] Repeat the above steps until the task planning agent stops outputting tool invocation tasks, providing the complete output of the task planning agent for this iteration as the final result. In this embodiment, when the task planning agent stops outputting a list of invoked tools, it is considered an end marker.
[0122] S5. Visualization and Result Synthesis: When the task planning agent calls the database interaction module, a chart is generated based on the output of the database interaction module and output along with the task result. Otherwise, the task result is output directly.
[0123] Preferably, when the database interaction module is invoked during the task, the system first performs a compliance check on the results returned by the database, and then determines the best presentation method based on visualization decision logic (e.g., prioritizing line charts for trend data and time series charts for time series data). This process comprehensively considers user needs (e.g., prioritizing line charts when the query contains "trend") and the characteristics of the data itself (e.g., time series data is more suitable for time series charts).
[0124] Finally, the system employs a hierarchical summary architecture to synthesize the output results. This hierarchical summary architecture presents the data in a structured manner, improving readability and analytical efficiency. The bottom layer generates data snapshots by extracting key indicators (such as maximum values and outliers). The middle layer matches appropriate analysis templates based on the query type, for example, highlighting the percentage of data change in comparative analysis tasks. The top layer, combined with the original requirements from the task planning phase, performs semantic validation and intent alignment on the final results.
[0125] Finally, the system integrates visual charts, structured data summaries, and natural language interpretations into a Markdown rich text format, employing an optimized spatial layout to conform to user cognitive habits and provide a clear and efficient data interpretation experience. This ensures that users can intuitively and accurately understand the query results.
[0126] Preferably, step S5 specifically includes steps S51 to S55.
[0127] S51. Check the task status matrix to obtain the call status of the database interaction module.
[0128] S52. When it is detected that a database interaction module has been called during the task iteration process, retrieve the query results returned by each database interaction module. Otherwise, directly output the task result.
[0129] S53. After the system obtains the database query results, a structured summary is generated from the result data, and then the semantics of the fields are initially categorized according to preprocessing rules. These preprocessing rules include: time fields, categorization fields, numeric fields, and / or proportion fields. The structured summary includes the attribute name, data type, unique value statistics, frequency distribution, missing rate, and example values for each field.
[0130] The specific rules for preprocessing are as follows:
[0131] 1. Time Field Recognition (Time / Date / Timestamp): Data type is time-based, such as datetime, date, timestamp, etc. Field name contains keywords, such as "date", "time", "timestamp", "created", "updated", "year", "month". Example value format matches time, such as 2023-01-01, 2024 / 05 / 12 08:00:00. There are many unique values, and the values are distributed in an ordered or periodic manner.
[0132] 2. Categorical Field Identification (Category / Label / Enumeration): Data type is string or integer, but the number of unique values is small (e.g., <100). Field names contain keywords: such as "type", "category", "label", "status", "gender", "region". Frequency distribution is long-tailed or clearly concentrated. High repetition rate: that is, the first few values cover most of the samples (e.g., the top 5 account for more than 80%).
[0133] 3. Numeric Field Recognition (Continuous / Discrete Values): Data type is numeric: such as int, float, decimal. Field name contains keywords: such as "count", "number", "age", "amount", "score". There are many unique values (a threshold may be set depending on the scenario, such as >100). The numerical distribution is reasonable, with no obvious category label features.
[0134] 4. Ratio Field Identification (Percentage / Ratio): Field names contain keywords such as "rate", "ratio", "percent", "pct". Value range is concentrated in [0, 1] or [0%, 100%]. Data type is float or string (with the % symbol). Precision limitations or duplicate digits may exist (e.g., 0.25, 0.5, 0.75).
[0135] 5. Identifier / Primary Key Field Identification: Field names contain keywords such as "id", "uuid", "key", and "code". Unique values equal to the number of samples, with no duplicates. Fields are used for indexing or linking other tables.
[0136] 6. Text Field Recognition (Description / Content): Field names contain keywords such as "description", "comment", "remark", "text", and "content". Average character length is relatively long (e.g., >50 characters). Data type is string / text. Content lacks clear structured information (unsuitable for categorization).
[0137] S54. Based on the summary information about the query results extracted from the preceding operations, and using the user's query information as context, provide it to a data analysis agent. The data analysis agent will then select the necessary charts for visualization based on preset discrimination rules.
[0138] The data analysis agent is obtained by fine-tuning the prompt words of an existing large language model. For example, the prompt words of the data analysis agent are: "Task description: Based on the provided database query result summary and the user's original requirement (origin_query), use the chain-of-thought reasoning method to systematically deduce and determine the most suitable visualization chart type and related parameters, and output the recommended chart in ECharts JSON format."
[0139] The preset discrimination rules include: when the query involves a combination of time series and numeric fields, a line chart or area chart is recommended (e.g., date + sales amount). When the query involves a combination of category and numeric fields, a bar chart, column chart, or pie chart is recommended (e.g., product category + amount). When the query involves proportional data, a pie chart or donut chart is selected (e.g., product category + sales percentage). When the query involves a combination of multiple numeric fields, a radar chart or parallel column chart is recommended (e.g., date + page views + click-through rate + conversion rate). For some difficult-to-discriminate field combinations, the query results are simply listed without additional visualization processing.
[0140] Specifically, in the chart type decision-making process, the model considers not only the type and combination of fields, but also the implicit semantic goals in the user's query (e.g., whether to emphasize trends, highlight contrasts, or require multi-dimensional combined analysis). Simultaneously, it automatically derives the key parameter information required for visualization, such as the main axis field, comparison dimensions, aggregation method, and time granularity, and outputs the corresponding chart parameters as rendering input for subsequent visualizations. Ultimately, through this visualization generation logic, the system ensures intelligent processing from structured query summaries to automatic chart configuration, possessing the ability to autonomously determine chart types, automatically aggregate multi-dimensional data, and adapt to visualization, providing users with data presentation results that are semantically adaptable and visually accurate.
[0141] S55. The structured summary is passed to the data analysis agent. After receiving the above input, the data analysis agent performs a long thought process and outputs the JSON text of the chart.
[0142] S56. Generate a visualization chart based on the selected chart type and the chart's JSON text.
[0143] S57. Integrate the visualization charts and the final results returned by the task planning agent into a Markdown rich text format, obtain the final output results and display them to the user, and then end.
[0144] After the entire process is completed, the system records the status and feedback information of each stage in real time, forming a closed-loop optimization mechanism. By statistically analyzing the execution results of each subtask and generating a task completion matrix, the system dynamically adjusts the collaboration strategies between the agents, combining user interaction feedback and execution logs. When an anomaly is detected, the system automatically triggers a feedback correction mechanism, adding supplementary conditions or readjusting the tool invocation order, and re-executing the task until the expected goal is achieved. This embodiment, through the above processing and feedback optimization measures, aims to improve the accuracy and response speed of database queries, enhance user experience, and improve the system's data insight capabilities.
[0145] Specifically, step S5 mainly visualizes the query results returned by the database interaction module in the preceding steps, aiming to make the information presentation more intuitive and clear. This step is not always triggered; it is only triggered when the preceding task planning agent calls the tool, which includes the database interaction module, and the tool successfully returns the corresponding query results. This visualization step will only start after the two preceding steps have been completed, and it will only be called once, ending at the end.
[0146] If checking the task status matrix reveals that multiple database interaction modules were called and correctly returned query results, then the records need to be organized and summaries extracted from each module.
[0147] Summary format description: The summary is returned in the format of "list [dictionary]", where each item in the list represents a query result returned by a database interaction module call. Each dictionary (dict) contains three fields: the input query parameter that called this database interaction module (origin_query), the markdown format of the returned result (result), and detailed information for each column of the returned result (columns). Columns includes column name (column_name), column data type (data_type), number of unique values (unique_values_count), example values (example_values, randomly extracted), unique values and their frequencies (value_frequencies, extracting the top three most frequent values, sorted in descending order), number of missing values (missing_count), and missing rate (missing_rate).
[0148] Next, the abstract format is processed and passed to the data analysis agent. After receiving the input, the data analysis agent performs a long deliberation and outputs the JSON text of the chart. The system uses the ECharts tool to visualize the JSON text of the chart, as shown below. Figure 4 As shown. Finally, the final output of the task planning agent, along with the chart shown here, will be displayed to the user, and then the process will end.
[0149] This invention presents a database interaction method based on multi-agent collaboration. By improving data preprocessing, information retrieval mechanisms, intelligent task planning, database interaction, and final result visualization synthesis, this method achieves efficient processing of data in different formats and enhances query accuracy, thereby reducing redundant information transmission and improving user experience. The database interaction method possesses multi-format input data processing capabilities, significantly improving the efficiency and accuracy of information retrieval and enabling intelligent and adaptive task scheduling. By optimizing the collaboration strategy among multiple agents, the method improves the response speed to user query requests, enhances the flexibility and accuracy of database queries, and introduces visualization optimization schemes in the interactive interface design, further strengthening the system's human-computer interaction experience and data insight capabilities.
[0150] Example 2: The present invention provides a database interaction device based on multi-agent collaboration, which includes a query acquisition module, a search source module, a task planning module, a task execution module, and an output module.
[0151] The query retrieval module is used to obtain query requests, then perform semantic segmentation through a format adapter, and finally vectorize them into vector representations to obtain a set of retrieval vectors.
[0152] The search source module is used to select a search source based on the retrieval vector set, use a meta-search engine to search, obtain information blocks, and retrieve candidate knowledge through a knowledge base. Then, the information blocks and candidate knowledge are integrated to obtain a candidate information set.
[0153] The task planning module is used to construct a dynamic demand understanding model based on the query request and the candidate information set through a task planning agent, so as to generate subtasks that can be executed atomically, and obtain the task state matrix and tool invocation task.
[0154] The task execution module is used to invoke the corresponding auxiliary tools and perform operations according to the tool invocation task, update the task status matrix according to the operation results, and return the updated task status matrix to the task planning agent to update the tool invocation task, until the task planning agent no longer outputs the tool invocation task and obtains the task result.
[0155] The output module is used to generate a chart based on the output of the database interaction module when the task planning agent calls the database interaction module, and output the chart along with the task result. Otherwise, the task result is output directly.
[0156] Example 3: This invention provides a database interaction device based on multi-agent cooperation, comprising a processor, a memory, and a computer program stored in the memory. The computer program can be executed by the processor to implement a database interaction method based on multi-agent cooperation as described in any paragraph of Example 1.
[0157] Example 4: The present invention provides a computer-readable storage medium, the computer-readable storage medium including a stored computer program, wherein, when the computer program is executed, it controls the device where the computer-readable storage medium is located to execute a database interaction method based on multi-agent cooperation as described in any paragraph of Example 1.
[0158] Obviously, the embodiments described above are only some embodiments of the present invention, and not all embodiments. All other embodiments obtained by those skilled in the art based on the embodiments of the present invention without inventive effort are within the scope of protection of the present invention.
[0159] In the several embodiments provided in this invention, it should be understood that the disclosed apparatus and methods can also be implemented in other ways. The apparatus and method embodiments described above are merely illustrative. For example, the flowcharts and block diagrams in the accompanying drawings illustrate the architecture, functionality, and operation of possible implementations of apparatus, methods, and computer program products according to various embodiments of the present invention. In this regard, each block in a flowchart or block diagram may represent a module, segment, or portion of code containing one or more executable instructions for implementing a specified logical function. It should also be noted that in some alternative implementations, the functions marked in the blocks may occur in a different order than those marked in the drawings. For example, two consecutive blocks may actually be executed substantially in parallel, and they may sometimes be executed in reverse order, depending on the functions involved. It should also be noted that each block in a block diagram and / or flowchart, and combinations of blocks in block diagrams and / or flowcharts, can be implemented using a dedicated hardware-based system that performs the specified function or action, or using a combination of dedicated hardware and computer instructions.
[0160] In addition, the functional modules in the various embodiments of the present invention can be integrated together to form an independent part, or each module can exist independently, or two or more modules can be integrated to form an independent part.
[0161] If the aforementioned functions are implemented as software functional modules and sold or used as independent products, they can be stored in a computer-readable storage medium. Based on this understanding, the technical solution of the present invention, or the part that contributes to the prior art, or a part of the technical solution, can be embodied in the form of a software product. This computer software product is stored in a storage medium and includes several instructions to cause a computer device (which may be a personal computer, electronic device, or network device, etc.) to execute all or part of the steps of the methods described in the various embodiments of the present invention. The aforementioned storage medium includes various media capable of storing program code, such as USB flash drives, portable hard drives, read-only memory, random access memory, magnetic disks, or optical disks. It should be noted that, in this document, 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.
[0162] The terminology used in the embodiments of this invention is for the purpose of describing particular embodiments only and is not intended to limit the invention. The singular forms “a,” “the,” and “the” as used in the embodiments of this invention and the appended claims are also intended to include the plural forms unless the context clearly indicates otherwise.
[0163] It should be understood that the term "and / or" used in this article is merely a description of the relationship between related objects, indicating that three relationships can exist. For example, A and / or B can represent: A existing alone, A and B existing simultaneously, and B existing alone. Additionally, the character " / " in this article generally indicates that the preceding and following related objects have an "or" relationship.
[0164] Depending on the context, the word "if" as used here can be interpreted as "when," "when," "in response to determination," or "in response to detection." Similarly, depending on the context, the phrase "if determination" or "if detection (of the stated condition or event)" can be interpreted as "when determination," "in response to determination," "when detection (of the stated condition or event)," or "in response to detection (of the stated condition or event)."
[0165] The terms "first" and "second" used in the embodiments are merely to distinguish similar objects and do not represent a specific ordering of objects. It is understood that "first" and "second" can be interchanged in a specific order or sequence where permitted. It should be understood that the objects distinguished by "first" and "second" can be interchanged where appropriate so that the embodiments described herein can be implemented in an order other than those illustrated or described herein.
[0166] The above description is merely a preferred embodiment of the present invention and is not intended to limit the invention. Various modifications and variations can be made to the present invention by those skilled in the art. Any modifications, equivalent substitutions, improvements, etc., made within the spirit and principles of the present invention should be included within the scope of protection of the present invention.
Claims
1. A database interaction method based on multi-agent collaboration, characterized in that, Include: The query request is obtained, then semantically segmented using a format adapter, and finally vectorized into a vector representation to obtain the set of retrieval vectors. Based on the retrieval vector set, the search source is selected by the search source selection agent and the meta-search engine is used to search and obtain information blocks, and candidate knowledge is obtained through knowledge base retrieval; then the information blocks and candidate knowledge are integrated to obtain a candidate information set; The task planning agent constructs a dynamic demand understanding model based on the query request and the candidate information set to generate atomically executable subtasks and obtain the task state matrix and tool invocation tasks. The tool invokes the corresponding auxiliary tool according to the tool invocation task and performs the operation. The task state matrix is updated according to the operation result, and the updated task state matrix is returned to the task planning agent to update the tool invocation task. The process continues until the task planning agent no longer outputs the tool invocation task and the task result is obtained. When the task planning agent calls the database interaction module, it generates a chart based on the output of the database interaction module and outputs it together with the task result; otherwise, it outputs the task result directly. The task planning agent is obtained by fine-tuning existing large language models with prompt words. The task planning agent aims to break down complex user query tasks into a series of executable atomic subtasks and dynamically adjust task execution strategies using multi-source heterogeneous information to ensure successful task completion. The entire process can be expressed by the following formula: In the formula, For task sequences, Planning agents for tasks To help users retrieve information, For the candidate information set, Preset user preferences For dialogue history information, To meet users' personalized needs, For the task state matrix, Indicates the first Sub-tasks; During the task decomposition phase, the task planning agent needs to break down complex query tasks into several atomic subtasks: In the formula, Indicates the first Sub-tasks For the first The names of the tools that each subtask needs to call. For the first The calling tool parameters for each subtask; where each subtask The following constraints must be met: Single instrument principle: Single call principle: In the formula, For tool name, For atomicity, The value indicates that the value is true. Based on the task sequence, a task state matrix is generated; the task state matrix Used for real-time tracking and feedback of the execution status of each subtask: In the formula, For tool name, To call tool parameters, For execution status, Returning results for the tool and This is the start and end timestamp for the subtask execution.
2. The database interaction method based on multi-agent collaboration according to claim 1, characterized in that, During task planning and execution, the system's tools include: a database interaction module, a calculator, a code interpreter, a weather interface, and a translation interface; The database interaction module adopts a multi-agent collaborative architecture to achieve high-precision query construction and full-process supervision. After the task planning agent issues sub-tasks, the system first relies on the semantic parsing engine to perform deep analysis of the input content, automatically extracting key entities, attributes, and constraints. Then, combined with the pre-built database, it performs three-level matching: first, it accurately determines the target data source through association table mapping; second, it locates specific fields using column association information; and finally, it ensures the validity of each constraint through value type validation. Successfully matched elements are encoded into structured context, which then drives the SQL generation agent to construct query statements that conform to the ANSI standard using the thought chain reasoning mechanism and a few-sample example library. In addition, the task correction agent adopts a triple verification mechanism to strictly supervise and correct the entire process: at the syntactic level, the system verifies the legality of the SQL structure through an abstract syntax tree; at the semantic level, it uses execution plan pre-playing to detect potential logical contradictions. At the result level, threshold alarms are set for empty result sets or results exceeding limits; when an anomaly is detected, the correction intelligence will dynamically inject specific prompts and automatically fall back to the process of extracting related structure information or SQL generation to re-execute, thereby forming a closed-loop error correction mechanism.
3. The database interaction method based on multi-agent collaboration according to claim 1, characterized in that, When the task planning agent calls the database interaction module, it generates a chart based on the output of the database interaction module and outputs it together with the task results. Otherwise, directly output the task results, specifically including: Check the task status matrix to obtain the call status of the database interaction module; When it is detected that a database interaction module is called during the task iteration process, the query results returned by each database interaction module are obtained respectively; otherwise, the task result is output directly. After the system obtains the database query results, it generates a structured summary of the result data, and then performs preliminary classification of the field semantics through preprocessing rules. The preprocessing rules include: time field, category field, numerical field and / or proportion field; the structured summary includes the attribute name, data type, unique value statistics, frequency distribution, missing rate and example value of each field. Based on the summary information of the query results extracted from the preceding operations, and using the user's query information as context, a data analysis agent is provided. The agent then selects the appropriate charts for visualization based on preset discrimination rules. These rules include: when the query involves a combination of time series and numeric fields, line charts or area charts are recommended; when the query involves a combination of category and numeric fields, bar charts, column charts, or pie charts are recommended; when the query involves proportional data, pie charts or donut charts are selected; when the query involves a combination of multiple numeric fields, radar charts or parallel column charts are recommended; for some difficult-to-discriminate field combinations, the query results are simply listed without additional visualization processing. The structured summary is passed to the data analysis agent, which receives the input, performs a long deliberation, and outputs the JSON text of the chart. Generate a visualization chart based on the selected chart type and the chart's JSON text; The visualization charts and the final results returned by the task planning agent are integrated and output as a Markdown rich text format. The final output is then displayed to the user and the process ends.
4. The database interaction method based on multi-agent collaboration according to any one of claims 1 to 3, characterized in that, Based on the retrieval vector set, the search source is selected by the search source selection agent, and a meta-search engine is used to search and obtain information blocks. Candidate knowledge is then retrieved through a knowledge base. Finally, the information blocks and candidate knowledge are integrated to obtain a candidate information set, specifically including: Based on the retrieval vector, the agent selects the search source by selecting the search source; Based on the retrieval vector and the selected search source, a meta-search engine is used to search and obtain information blocks related to the user's needs; The search results are vectorized, converting text information into vector representations; The semantic similarity algorithm is used to compare the vector representation of the search results with the retrieval vector, and the Top-K information blocks with the highest semantic relevance are selected. The retrieval vector set is matched with the pre-built knowledge base for similarity matching to identify the most similar document fragments and obtain candidate knowledge; wherein, the knowledge base stores document data in pre-divided blocks. Information blocks and candidate knowledge are uniformly incorporated into the candidate information set.
5. The database interaction method based on multi-agent cooperation according to any one of claims 1 to 3, characterized in that, The query request is obtained, then semantically segmented using a format adapter, and finally vectorized into a vector representation to obtain the retrieval vector set, specifically including: Get the query request; The query request is semantically segmented using a format adapter. For text-type information, no additional preprocessing is performed. For structured data, additional parsing is required to extract key fields and convert them into a uniform format for alignment with other data types. Audio data is directly converted to text to simplify subsequent processing and ensure consistency with other text data. Image data is stored in its original format to ensure that it can be matched and associated with other information during subsequent retrieval. The search term extraction agent extracts search keywords from semantic blocks; the search term extraction agent is obtained through fine-tuning of prompt words. Vectorize the search keywords to obtain a set of search vectors.
6. The database interaction method based on multi-agent cooperation according to any one of claims 1 to 3, characterized in that, It also includes pre-built databases and knowledge bases: based on the structured data uploaded by users, natural language structure information at the table level, column level, and value level is extracted, vectorized, and then stored in a vector database; based on the heterogeneous files uploaded by users, they are converted into a unified processing format, and data is processed by data block processing and vectorization encoding to obtain a searchable content mapping relationship library; Pre-construction of databases and knowledge bases, specifically including: During the database pre-construction process, the database file or database configuration information uploaded by the user, as well as the database structure information file, are first obtained, and natural language structure information at the table level, column level, and value level is extracted and generated from them. The generated structural information is vectorized. The vectorization results are stored in a vector database: each record in the vector database is as follows: In the formula: Records in the database A unique identifier for a vector Describing text in raw natural language For the generated high-dimensional vector, For record type, For the table name, For the column names, The actual value; During the knowledge base construction process, the heterogeneous files uploaded by users are first parsed through a format adapter to convert data of different formats into a unified processing format; The parsed data is then divided into blocks for processing; These knowledge blocks are vectorized and encoded to obtain a searchable content mapping relationship library.
7. A database interaction device based on multi-agent collaboration, characterized in that, Suitable for performing the database interaction method based on multi-agent cooperation as described in any one of claims 1 to 6; the database interaction device comprises: The query retrieval module is used to obtain query requests, then perform semantic segmentation through a format adapter, and finally vectorize them into vector representations to obtain a set of retrieval vectors. The search source module is used to select a search source through a search source selection agent based on the retrieval vector set and use a meta-search engine to search, obtain information blocks, and retrieve candidate knowledge through a knowledge base; then, the information blocks and candidate knowledge are integrated to obtain a candidate information set. The task planning module is used to construct a dynamic demand understanding model based on the query request and the candidate information set through a task planning intelligent agent, so as to generate subtasks that can be executed atomically, and obtain the task state matrix and tool invocation task; The task execution module is used to invoke the corresponding auxiliary tool according to the tool invocation task and perform the operation, update the task status matrix according to the operation result, and return the updated task status matrix to the task planning agent to update the tool invocation task, until the task planning agent no longer outputs the tool invocation task and obtains the task result; The output module is used to generate a chart based on the output of the database interaction module when the task planning agent calls the database interaction module, and output the chart along with the task result; otherwise, the task result is output directly.
8. A database interaction device based on multi-agent collaboration, characterized in that, It includes a processor, a memory, and a computer program stored in the memory; the computer program can be executed by the processor to implement the database interaction method based on multi-agent cooperation as described in any one of claims 1 to 6.
9. A computer-readable storage medium, characterized in that, The computer-readable storage medium includes a stored computer program, wherein, when the computer program is executed, it controls the device on which the computer-readable storage medium is located to perform the database interaction method based on multi-agent cooperation as described in any one of claims 1 to 6.
Citation Information
Patent Citations
Mine prospecting prediction method based on multi-agent technology
CN120234387A
Natural language query processing
US12346315B1